code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
from mercurial import cmdutil _hgignore_content = """\ syntax: glob *~ *.pyc *.pyo *.bak cache/* databases/* sessions/* errors/* """ def commit(): app = request.args[0] path = apath(app, r=request) uio = ui.ui() uio.quiet = True if not os.environ.get('HGUSER') and not uio.config("ui", "username"): os.environ['HGUSER'] = 'web2py@localhost' try: r = hg.repository(ui=uio, path=path) except: r = hg.repository(ui=uio, path=path, create=True) hgignore = os.path.join(path, '.hgignore') if not os.path.exists(hgignore): open(hgignore, 'w').write(_hgignore_content) form = FORM('Comment:',INPUT(_name='comment',requires=IS_NOT_EMPTY()), INPUT(_type='submit',_value='Commit')) if form.accepts(request.vars,session): oldid = r[r.lookup('.')] cmdutil.addremove(r) r.commit(text=form.vars.comment) if r[r.lookup('.')] == oldid: response.flash = 'no changes' files = r[r.lookup('.')].files() return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r)
henkelis/sonospy
web2py/applications/admin/controllers/mercurial.py
Python
gpl-3.0
1,107
# coding=utf-8 """InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on Population. Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Rizky Maulana Nugraha' from safe.common.utilities import OrderedDict from safe.defaults import ( default_minimum_needs, default_gender_postprocessor, age_postprocessor, minimum_needs_selector) from safe.impact_functions.impact_function_metadata import \ ImpactFunctionMetadata from safe.utilities.i18n import tr from safe.definitions import ( layer_mode_continuous, layer_geometry_raster, hazard_flood, hazard_category_single_event, unit_metres, unit_feet, count_exposure_unit, exposure_population ) class FloodEvacuationRasterHazardMetadata(ImpactFunctionMetadata): """Metadata for FloodEvacuationFunction. .. versionadded:: 2.1 We only need to re-implement as_dict(), all other behaviours are inherited from the abstract base class. """ @staticmethod def as_dict(): """Return metadata as a dictionary. This is a static method. You can use it to get the metadata in dictionary format for an impact function. :returns: A dictionary representing all the metadata for the concrete impact function. :rtype: dict """ dict_meta = { 'id': 'FloodEvacuationRasterHazardFunction', 'name': tr('Raster flood on population'), 'impact': tr('Need evacuation'), 'title': tr('Need evacuation'), 'function_type': 'old-style', 'author': 'AIFDR', 'date_implemented': 'N/A', 'overview': tr( 'To assess the impacts of flood inundation in raster ' 'format on population.'), 'detailed_description': tr( 'The population subject to inundation exceeding a ' 'threshold (default 1m) is calculated and returned as a ' 'raster layer. In addition the total number of affected ' 'people and the required needs based on the user ' 'defined minimum needs are reported. The threshold can be ' 'changed and even contain multiple numbers in which case ' 'evacuation and needs are calculated using the largest number ' 'with population breakdowns provided for the smaller numbers. ' 'The population raster is resampled to the resolution of the ' 'hazard raster and is rescaled so that the resampled ' 'population counts reflect estimates of population count ' 'per resampled cell. The resulting impact layer has the ' 'same resolution and reflects population count per cell ' 'which are affected by inundation.'), 'hazard_input': tr( 'A hazard raster layer where each cell represents flood ' 'depth (in meters).'), 'exposure_input': tr( 'An exposure raster layer where each cell represent ' 'population count.'), 'output': tr( 'Raster layer contains people affected and the minimum ' 'needs based on the people affected.'), 'actions': tr( 'Provide details about how many people would likely need ' 'to be evacuated, where they are located and what ' 'resources would be required to support them.'), 'limitations': [ tr('The default threshold of 1 meter was selected based ' 'on consensus, not hard evidence.') ], 'citations': [], 'layer_requirements': { 'hazard': { 'layer_mode': layer_mode_continuous, 'layer_geometries': [layer_geometry_raster], 'hazard_categories': [hazard_category_single_event], 'hazard_types': [hazard_flood], 'continuous_hazard_units': [unit_feet, unit_metres], 'vector_hazard_classifications': [], 'raster_hazard_classifications': [], 'additional_keywords': [] }, 'exposure': { 'layer_mode': layer_mode_continuous, 'layer_geometries': [layer_geometry_raster], 'exposure_types': [exposure_population], 'exposure_units': [count_exposure_unit], 'exposure_class_fields': [], 'additional_keywords': [] } }, 'parameters': OrderedDict([ ('thresholds [m]', [1.0]), ('postprocessors', OrderedDict([ ('Gender', default_gender_postprocessor()), ('Age', age_postprocessor()), ('MinimumNeeds', minimum_needs_selector()), ])), ('minimum needs', default_minimum_needs()) ]) } return dict_meta
wonder-sk/inasafe
safe/impact_functions/inundation/flood_raster_population/metadata_definitions.py
Python
gpl-3.0
5,408
/** * */ package cz.geokuk.core.napoveda; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.net.MalformedURLException; import java.net.URL; import cz.geokuk.core.program.FConst; import cz.geokuk.framework.Action0; import cz.geokuk.util.process.BrowserOpener; /** * @author Martin Veverka * */ public class ZadatProblemAction extends Action0 { private static final long serialVersionUID = -2882817111560336824L; /** * @param aBoard */ public ZadatProblemAction() { super("Zadat problém ..."); putValue(SHORT_DESCRIPTION, "Zobrazí stránku na code.google.com, která umožní zadat chybu v Geokuku nebo požadavek na novou funkcionalitu."); putValue(MNEMONIC_KEY, KeyEvent.VK_P); } /* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(final ActionEvent aE) { try { BrowserOpener.displayURL(new URL(FConst.POST_PROBLEM_URL)); } catch (final MalformedURLException e) { throw new RuntimeException(e); } } }
marvertin/geokuk
src/main/java/cz/geokuk/core/napoveda/ZadatProblemAction.java
Java
gpl-3.0
1,073
/** * Copyright 2013, 2014 Ioana Ileana @ Telecom ParisTech * 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 instance; import java.util.ArrayList; public class Parser { private ArrayList<ArrayList<String>> m_relationals; private ArrayList<String[]> m_equalities; int m_pos; public Parser() { m_relationals = new ArrayList<ArrayList<String>>(); m_equalities = new ArrayList<String[]>(); m_pos=0; } public void flush() { m_pos = 0; m_relationals.clear(); m_equalities.clear(); } public boolean charIsValidForRelation(char c) { return ((c>='A' && c<='Z') || (c>='0' && c<='9') || (c=='_')); } public boolean charIsValidForTerm(char c) { return ((c>='a' && c<='z') || (c>='0' && c<='9') || (c=='_') || (c=='.') ); } public ArrayList<String> parseAtom(String line) { ArrayList<String> list = new ArrayList<String>(); String relation=""; while (m_pos<line.length()) { if (charIsValidForRelation(line.charAt(m_pos))) { relation+=line.charAt(m_pos); m_pos++; } else if (line.charAt(m_pos)=='(') { m_pos++; list.add(relation); parseTerms(line, list); return list; } else { m_pos++; } } return null; } public void parseTerms(String line, ArrayList<String> list) { while (m_pos<line.length()) { if (line.charAt(m_pos) == ')') { m_pos++; return; } else if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else { String term=parseSingleTerm(line); list.add(term); } } } public String parseSingleTerm(String line) { String term=""; while (m_pos<line.length() && charIsValidForTerm(line.charAt(m_pos))) { term+=line.charAt(m_pos); m_pos++; } return term; } public void parseRelationals(String line) { m_pos = 0; while (m_pos<line.length()) { if (line.charAt(m_pos)<'A' || line.charAt(m_pos)>'Z') m_pos++; else { ArrayList<String> relStr = parseAtom(line); m_relationals.add(relStr); } } } public void parseEqualities(String line) { m_pos = 0; while (m_pos<line.length()) { if (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; else parseEquality(line); } } public void parseEquality(String line) { String[] terms=new String[2]; terms[0] = parseSingleTerm(line); while (m_pos<line.length() && !charIsValidForTerm(line.charAt(m_pos))) m_pos++; terms[1] = parseSingleTerm(line); m_equalities.add(terms); } public ArrayList<String[]> getEqualities() { return m_equalities; } public ArrayList<ArrayList<String>> getRelationals() { return m_relationals; } public ArrayList<String> parseProvenance(String line) { ArrayList<String> provList = new ArrayList<String>(); while (m_pos < line.length()) { while (!charIsValidForTerm(line.charAt(m_pos))) m_pos++; String term = parseSingleTerm(line); if (!(term.equals(""))) { provList.add(term); } } return provList; } }
IoanaIleana/ProvCB
src/instance/Parser.java
Java
gpl-3.0
3,628
(function() { 'use strict'; angular .module('app.grid') .service('GridDemoModelSerivce', GridDemoModelSerivce) .service('GridUtils',GridUtils) .factory('GridFactory',GridFactory) ; GridFactory.$inject = ['modelNode','$q','$filter']; function GridFactory(modelNode,$q,$filter) { return { buildGrid: function (option) { return new Grid(option,modelNode,$q,$filter); } } } function Grid(option,modelNode,$q,$filter) { var self = this; this.page = angular.extend({size: 9, no: 1}, option.page); this.sort = { column: option.sortColumn || '_id', direction: option.sortDirection ||-1, toggle: function (column) { if (column.sortable) { if (this.column === column.name) { this.direction = -this.direction || -1; } else { this.column = column.name; this.direction = -1; } self.paging(); } } }; this.searchForm = option.searchForm; this.rows = []; this.rawData = []; this.modelling = false; //必须有的 this.model = option.model; if (angular.isString(this.model)) { this.model = modelNode.services[this.model]; } if (!this.model) this.model = angular.noop; var promise; if (angular.isFunction(this.model)) { this.model = this.model(); } promise = $q.when(this.model).then(function (ret) { if (angular.isArray(ret)) { self.rawData = ret; } else { self.modelling = true; } self.setData = setData; self.query = query; self.paging = paging; return self; }); return promise; function setData(data) { self.rawData = data; } function query(param) { var queryParam = angular.extend({}, self.searchForm, param); if (self.modelling) { self.rows = self.model.page(self.page, queryParam, null, (self.sort.direction > 0 ? '' : '-') + self.sort.column); //服务端totals在查询数据时计算 self.model.totals(queryParam).$promise.then(function (ret) { self.page.totals = ret.totals; }); } else { if (self.rawData) self.rows = $filter('filter')(self.rawData, queryParam); } } function paging() { if (this.modelling) { this.query(); } } } GridDemoModelSerivce.$inject = ['Utils']; function GridDemoModelSerivce(Utils) { this.query = query; this.find = find; this.one = one; this.save = save; this.update = update; this.remove = remove; this._demoData_ = []; function query(refresh) { refresh = this._demoData_.length == 0 || refresh; if (refresh) { this._demoData_.length = 0; var MAX_NUM = 10 * 50; for (var i = 0; i < MAX_NUM; ++i) { var id = Utils.rand(0, MAX_NUM); this._demoData_.push({ id: i + 1, name: 'Name' + id, // 字符串类型 followers: Utils.rand(0, 100 * 1000 * 1000), // 数字类型 birthday: moment().subtract(Utils.rand(365, 365 * 50), 'day').toDate(), // 日期类型 summary: '这是一个测试' + i, income: Utils.rand(1000, 100000) // 金额类型 }); } } return this._demoData_; } function one(properties) { return _.findWhere(this._demoData_, properties); } function find(id) { return _.find(this._demoData_, function (item) { return item.id == id; }); } ///为了保证何$resource中的save功能一样此方法用于添加 function save(data) { //添加 this._demoData_.push(_.defaults(data, {})); //if (id != 'new') { // //修改 // var dest = _.bind(find, this, id); // _.extend(dest, data); //} //else { // //} } function update(id,data){ var dest = _.bind(find, this, id); _.extend(dest, data); } function remove(ids) { console.log(this._demoData_.length); this._demoData_ = _.reject(this._demoData_, function (item) { return _.contains(ids, item.id); }); console.log(this._demoData_.length); } } GridUtils.$inject = ['$filter','ViewUtils']; function GridUtils($filter,ViewUtils) { return { paging: paging, totals: totals, hide: hide, width: width, toggleOrderClass: toggleOrderClass, noResultsColspan: noResultsColspan, revertNumber: revertNumber, calcAge: calcAge, formatter: formatter, populateFilter: populateFilter, boolFilter: boolFilter, diFilter: diFilter, repeatInfoCombo: repeatInfoCombo, orFilter: orFilter }; function paging(items, vm) { if (!items) return []; if(vm.serverPaging){ //服务端分页 vm.paged = items; } else{ //客户端分页 var offset = (vm.page.no - 1) * vm.page.size; vm.paged = items.slice(offset, offset + vm.page.size); ////客户端totals在分页数据时计算 vm.page.totals = items.length;//客户端分页是立即触发结果 } return vm.paged; } function totals(items,filter,vm) { if (!items) return 0; if (vm.serverPaging) { //服务端分页 return vm.page.totals; } else { //客户端分页 return items.length || 0 } } function hide(column) { if (!column) return true; return column.hidden === true; } function width(column) { if (!column) return 0; return column.width || 100; } function toggleOrderClass(direction) { if (direction === -1) return "glyphicon-chevron-down"; else return "glyphicon-chevron-up"; } function noResultsColspan(vm) { if (!vm || !vm.columns) return 1; return 1 + vm.columns.length - _.where(vm.columns, {hidden: true}).length; } function revertNumber(num,notConvert) { if (num && !notConvert) { return -num; } return num; } function calcAge(rowValue) { return ViewUtils.age(rowValue) } function formatter(rowValue, columnName, columns) { var one = _.findWhere(columns, {name: columnName}); if(one && !one.hidden) { if (one.formatterData) { if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ return one.formatterData[o]; }); } else{ return one.formatterData[rowValue]; } } } return rowValue; } function populateFilter(rowValue, key) { key = key || 'name'; if(_.isArray(rowValue)){ return _.map(rowValue,function(o){ console.log(o); return ViewUtils.getPropery(o, key); }); } else{ return ViewUtils.getPropery(o, key); } return rowValue; } function boolFilter(rowValue){ return {"1": "是", "0": "否", "true": "是", "false": "否"}[rowValue]; } function diFilter(rowValue,di) { if (_.isArray(rowValue)) { return _.map(rowValue, function (o) { return di[o] || (_.findWhere(di, {value: rowValue}) || {}).name; }); } else { return di[rowValue] || (_.findWhere(di, {value: rowValue}) || {}).name; } } function repeatInfoCombo(repeatValues, repeat_start) { if (_.isArray(repeatValues) && repeatValues.length > 0) { return _.map(repeatValues, function (r) { return r + repeat_start; }).join('\r\n'); } else { return repeat_start; } } /** * AngularJS default filter with the following expression: * "person in people | filter: {name: $select.search, age: $select.search}" * performs a AND between 'name: $select.search' and 'age: $select.search'. * We want to perform a OR. */ function orFilter(items, props) { var out = []; if (_.isArray(items)) { _.each(items,function (item) { var itemMatches = false; var keys = Object.keys(props); for (var i = 0; i < keys.length; i++) { var prop = keys[i]; var text = props[prop].toLowerCase(); if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { itemMatches = true; break; } } if (itemMatches) { out.push(item); } }); } else { // Let the output be the input untouched out = items; } return out; }; } })();
zppro/4gtour
src/vendor-1.x/js/modules/grid/grid.service.js
JavaScript
gpl-3.0
11,119
<?php /** * Core Class To Style RAD Builder Components * @author Abhin Sharma * @dependency none * @since IOA Framework V1 */ if(!class_exists('RADStyler')) { class RADStyler { function registerbgColor($key='' ,$target='') { $code ='<h5 class="sub-styler-title">'.__('Set Background Color','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Background Color",'ioa') , "name" => $key."_bg_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "background-color" ) )); return $code.'</div>'; } function registerBorder($key='' ,$target='') { $code ='<h5 class="sub-styler-title">'.__('Set Border','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Top Border Color",'ioa') , "name" => $key."_tbr_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "border-top-color" ) )); $code .= getIOAInput(array( "label" => __("Top Border Size(ex : 1px)",'ioa') , "name" => $key."_tbr_width" , "default" => "" , "type" => "text", "description" => "", "length" => 'small', "class" => ' rad_style_property ', "value" => "0px" , "data" => array( "target" => $target , "property" => "border-top-width" ) )); $code .= getIOAInput(array( "label" => __("Bottom Border Color",'ioa') , "name" => $key."_bbr_color" , "default" => "" , "type" => "colorpicker", "description" => "", "length" => 'small', "value" => "" , "data" => array( "target" => $target , "property" => "border-bottom-color" ) )); $code .= getIOAInput(array( "label" => __("Bottom Border Size(ex : 1px)",'ioa') , "name" => $key."_bbr_width" , "default" => "" , "type" => "text", "description" => "", "length" => 'small', "class" => ' rad_style_property ', "value" => "0px" , "data" => array( "target" => $target , "property" => "border-bottom-width" ) )); return $code.'</div>'; } function registerbgImage($key ,$target) { $code ='<h5 class="sub-styler-title">'.__('Set Background Image','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix">'; $code .= getIOAInput(array( "label" => __("Add Background Image",'ioa') , "name" => $key."_bg_image" , "default" => "" , "type" => "upload", "description" => "" , "length" => 'small' , "title" => __("Use as Background Image",'ioa'), "std" => "", "button" => __("Add Image",'ioa'), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); $code .= getIOAInput(array( "label" => __("Background Position",'ioa') , "name" => $key."_bgposition" , "default" => "top left" , "type" => "select", "class" => ' rad_style_property ', "description" => "" , "length" => 'medium' , "options" => array("top left","top right","bottom left","bottom right","center top","center center","center bottom","center left","center right"), "data" => array( "target" => $target , "property" => "background-position" ) ) ); $code .= getIOAInput(array( "label" => __("Background Cover",'ioa') , "name" => $key."_bgcover" , "default" => "auto" , "type" => "select", "class" => ' rad_style_property ', "description" => "" , "length" => 'medium' , "options" => array("auto","contain","cover"), "data" => array( "target" => $target , "property" => "background-size" ) ) ); $code .= getIOAInput(array( "label" => __("Background Repeat",'ioa') , "name" => $key."_bgrepeat" , "default" => "repeat" , "type" => "select", "description" => "" , "length" => 'medium' , "options" => array("repeat","repeat-x","repeat-y","no-repeat"), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-repeat" ) ) ); $code .= getIOAInput(array( "label" => __("Background Scroll",'ioa') , "name" => $key."_bgscroll" , "default" => "" , "type" => "select", "description" => "" , "length" => 'medium' , "options" => array("scroll","fixed"), "class" => ' rad_style_property ', "data" => array( "target" => $target , "property" => "background-attachment" ) ) ); return $code.'</div>'; } function registerbgGradient($key ,$target) { $code ='<h5 class="sub-styler-title">'.__('Set Background Gradient','ioa').'<i class="angle-downicon- ioa-front-icon"></i></h5><div class="sub-styler-section clearfix"><a class="set-rad-gradient button-default" href="">'.__('Apply','ioa').'</a> '; $code .= getIOAInput(array( "label" => __("Use Background Gradient",'ioa') , "name" => $key."_gradient_dir" , "default" => "no" , "type" => "select", "description" => "" , "length" => 'small' , "options" => array("horizontal" => __("Horizontal",'ioa'),"vertical"=> __("Vertical",'ioa'),"diagonaltl" => __("Diagonal Top Left",'ioa'),"diagonalbr" => __("Diagonal Bottom Right",'ioa') ), "class" => ' hasGradient dir ', "data" => array( "target" => $target , "property" => "removable" ) ) ); $code .= getIOAInput(array( "label" => __("Select Start Background Color for title area",'ioa') , "name" => $key."_grstart" , "default" => " << " , "type" => "colorpicker", "description" => " " , "length" => 'small' , "alpha" => false, "class" => ' hasGradient grstart no_listen ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); $code .= getIOAInput(array( "label" => __("Select Start Background Color for title area",'ioa') , "name" => $key."_grend" , "default" => " << " , "type" => "colorpicker", "description" => " " , "length" => 'small' , "alpha" => false, "class" => ' hasGradient grend no_listen ', "data" => array( "target" => $target , "property" => "background-image" ) ) ); return $code.'</div>'; } } }
lithqube/sedesgroup
IT/wp-content/themes/limitless/backend/rad_builder/class_radstyler.php
PHP
gpl-3.0
7,651
#if defined (_MSC_VER) && !defined (_WIN64) #pragma warning(disable:4244) // boost::number_distance::distance() // converts 64 to 32 bits integers #endif #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/IO/read_xyz_points.h> #include <CGAL/Point_with_normal_3.h> #include <CGAL/property_map.h> #include <CGAL/Shape_detection_3.h> #include <CGAL/Timer.h> #include <iostream> #include <fstream> // Type declarations typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel; typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal; typedef std::vector<Point_with_normal> Pwn_vector; typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map; typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map; // In Shape_detection_traits the basic types, i.e., Point and Vector types // as well as iterator type and property maps, are defined. typedef CGAL::Shape_detection_3::Shape_detection_traits <Kernel, Pwn_vector, Point_map, Normal_map> Traits; typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac; typedef CGAL::Shape_detection_3::Region_growing<Traits> Region_growing; typedef CGAL::Shape_detection_3::Plane<Traits> Plane; struct Timeout_callback { mutable int nb; mutable CGAL::Timer timer; const double limit; Timeout_callback(double limit) : nb(0), limit(limit) { timer.start(); } bool operator()(double advancement) const { // Avoid calling time() at every single iteration, which could // impact performances very badly ++ nb; if (nb % 1000 != 0) return true; // If the limit is reach, interrupt the algorithm if (timer.time() > limit) { std::cerr << "Algorithm takes too long, exiting (" << 100. * advancement << "% done)" << std::endl; return false; } return true; } }; // This program both works for RANSAC and Region Growing template <typename ShapeDetection> int run(const char* filename) { Pwn_vector points; std::ifstream stream(filename); if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()). normal_map(Normal_map()))) { std::cerr << "Error: cannot read file cube.pwn" << std::endl; return EXIT_FAILURE; } ShapeDetection shape_detection; shape_detection.set_input(points); shape_detection.template add_shape_factory<Plane>(); // Create callback that interrupts the algorithm if it takes more than half a second Timeout_callback timeout_callback(0.5); // Detects registered shapes with default parameters. shape_detection.detect(typename ShapeDetection::Parameters(), timeout_callback); return EXIT_SUCCESS; } int main (int argc, char** argv) { if (argc > 1 && std::string(argv[1]) == "-r") { std::cout << "Efficient RANSAC" << std::endl; return run<Efficient_ransac> ((argc > 2) ? argv[2] : "data/cube.pwn"); } std::cout << "Region Growing" << std::endl; return run<Region_growing> ((argc > 1) ? argv[1] : "data/cube.pwn"); }
FEniCS/mshr
3rdparty/CGAL/examples/Point_set_shape_detection_3/shape_detection_with_callback.cpp
C++
gpl-3.0
3,227
public class Rectangulo { public int Base; public int Altura; //Ejercicio realizado con ayuda de esta pagina:http://diagramas-de-flujo.blogspot.com/2013/02/calcular-perimetro-rectangulo-Java.html //aqui llamamos las dos variables que utilizaremos. Rectangulo(int Base, int Altura) { this.Base = Base; this.Altura = Altura; } //COmo pueden observar aqui se obtiene la base y se asigna el valor de la base. int getBase () { return Base; } //aqui devolvemos ese valor void setBase (int Base) { this.Base = Base; } //aqui de igual forma se obtiene la altura y se le asigna el valor int getAltura () { return Altura; } //aqui devuelve el valor de la altura void setAltura (int Altura) { this.Altura = Altura; } //aqui con una formula matematica se obtiene el perimetro hacemos una suma y una multiplicacion int getPerimetro() { return 2*(Base+Altura); } //aqui solo se hace un calculo matematico como la multiplicacion int getArea() { return Base*Altura; } }
IvethS/Tarea2
src/Rectangulo.java
Java
gpl-3.0
1,004
/* * This file is part of "U Turismu" project. * * U Turismu is an enterprise application in support of calabrian tour operators. * This system aims to promote tourist services provided by the operators * and to develop and improve tourism in Calabria. * * Copyright (C) 2012 "LagrecaSpaccarotella" team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uturismu.dao; import uturismu.dto.Booking; /** * @author "LagrecaSpaccarotella" team. * */ public interface BookingDao extends GenericDao<Booking> { }
spa-simone/u-turismu
src/main/java/uturismu/dao/BookingDao.java
Java
gpl-3.0
1,133
/** * Module dependencies. */ var express = require('express') , http = require('http') , path = require('path') , mongo = require('mongodb') , format = require('util').format; var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } var server = new mongo.Server("localhost", 27017, {auto_reconnect: true}); var dbManager = new mongo.Db("applique-web", server, {safe:true}); dbManager.open(function(err, db) { require('./routes/index')(app, db); app.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); });
jkamga/INM5151-payGoStore
app.js
JavaScript
gpl-3.0
991
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2016 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmdlineparser.h" #include "cppcheck.h" #include "cppcheckexecutor.h" #include "filelister.h" #include "path.h" #include "settings.h" #include "timer.h" #include "check.h" #include "threadexecutor.h" // Threading model #include <algorithm> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <cstring> #include <cstdlib> // EXIT_FAILURE #ifdef HAVE_RULES // xml is used for rules #include <tinyxml2.h> #endif static void AddFilesToList(const std::string& FileList, std::vector<std::string>& PathNames) { // To keep things initially simple, if the file can't be opened, just be silent and move on. std::istream *Files; std::ifstream Infile; if (FileList.compare("-") == 0) { // read from stdin Files = &std::cin; } else { Infile.open(FileList.c_str()); Files = &Infile; } if (Files && *Files) { std::string FileName; while (std::getline(*Files, FileName)) { // next line if (!FileName.empty()) { PathNames.push_back(FileName); } } } } static void AddInclPathsToList(const std::string& FileList, std::list<std::string>* PathNames) { // To keep things initially simple, if the file can't be opened, just be silent and move on. std::ifstream Files(FileList.c_str()); if (Files) { std::string PathName; while (std::getline(Files, PathName)) { // next line if (!PathName.empty()) { PathName = Path::removeQuotationMarks(PathName); PathName = Path::fromNativeSeparators(PathName); // If path doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (PathName.back() != '/') #else if (PathName[PathName.size() - 1] != '/') #endif PathName += '/'; PathNames->push_back(PathName); } } } } static void AddPathsToSet(const std::string& FileName, std::set<std::string>* set) { std::list<std::string> templist; AddInclPathsToList(FileName, &templist); set->insert(templist.begin(), templist.end()); } CmdLineParser::CmdLineParser(Settings *settings) : _settings(settings) , _showHelp(false) , _showVersion(false) , _showErrorMessages(false) , _exitAfterPrint(false) { } void CmdLineParser::PrintMessage(const std::string &message) { std::cout << message << std::endl; } void CmdLineParser::PrintMessage(const char* message) { std::cout << message << std::endl; } bool CmdLineParser::ParseFromArgs(int argc, const char* const argv[]) { bool def = false; bool maxconfigs = false; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (std::strcmp(argv[i], "--version") == 0) { _showVersion = true; _exitAfterPrint = true; return true; } // Flag used for various purposes during debugging else if (std::strcmp(argv[i], "--debug") == 0) _settings->debug = _settings->debugwarnings = true; // Show --debug output after the first simplifications else if (std::strcmp(argv[i], "--debug-normal") == 0) _settings->debugnormal = true; // Show debug warnings else if (std::strcmp(argv[i], "--debug-warnings") == 0) _settings->debugwarnings = true; // dump cppcheck data else if (std::strcmp(argv[i], "--dump") == 0) _settings->dump = true; // (Experimental) exception handling inside cppcheck client else if (std::strcmp(argv[i], "--exception-handling") == 0) _settings->exceptionHandling = true; else if (std::strncmp(argv[i], "--exception-handling=", 21) == 0) { _settings->exceptionHandling = true; const std::string exceptionOutfilename = &(argv[i][21]); CppCheckExecutor::setExceptionOutput((exceptionOutfilename=="stderr") ? stderr : stdout); } // Inconclusive checking else if (std::strcmp(argv[i], "--inconclusive") == 0) _settings->inconclusive = true; // Enforce language (--language=, -x) else if (std::strncmp(argv[i], "--language=", 11) == 0 || std::strcmp(argv[i], "-x") == 0) { std::string str; if (argv[i][2]) { str = argv[i]+11; } else { i++; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: No language given to '-x' option."); return false; } str = argv[i]; } if (str == "c") _settings->enforcedLang = Settings::C; else if (str == "c++") _settings->enforcedLang = Settings::CPP; else { PrintMessage("cppcheck: Unknown language '" + str + "' enforced."); return false; } } // Filter errors else if (std::strncmp(argv[i], "--exitcode-suppressions=", 24) == 0) { // exitcode-suppressions=filename.txt std::string filename = 24 + argv[i]; std::ifstream f(filename.c_str()); if (!f.is_open()) { PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\"."); return false; } const std::string errmsg(_settings->nofail.parseFile(f)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Filter errors else if (std::strncmp(argv[i], "--suppressions-list=", 20) == 0) { std::string filename = argv[i]+20; std::ifstream f(filename.c_str()); if (!f.is_open()) { std::string message("cppcheck: Couldn't open the file: \""); message += filename; message += "\"."; if (std::count(filename.begin(), filename.end(), ',') > 0 || std::count(filename.begin(), filename.end(), '.') > 1) { // If user tried to pass multiple files (we can only guess that) // e.g. like this: --suppressions-list=a.txt,b.txt // print more detailed error message to tell user how he can solve the problem message += "\nIf you want to pass two files, you can do it e.g. like this:"; message += "\n cppcheck --suppressions-list=a.txt --suppressions-list=b.txt file.cpp"; } PrintMessage(message); return false; } const std::string errmsg(_settings->nomsg.parseFile(f)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } else if (std::strncmp(argv[i], "--suppress=", 11) == 0) { std::string suppression = argv[i]+11; const std::string errmsg(_settings->nomsg.addSuppressionLine(suppression)); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } } // Enables inline suppressions. else if (std::strcmp(argv[i], "--inline-suppr") == 0) _settings->inlineSuppressions = true; // Verbose error messages (configuration info) else if (std::strcmp(argv[i], "-v") == 0 || std::strcmp(argv[i], "--verbose") == 0) _settings->verbose = true; // Force checking of files that have "too many" configurations else if (std::strcmp(argv[i], "-f") == 0 || std::strcmp(argv[i], "--force") == 0) _settings->force = true; // Output relative paths else if (std::strcmp(argv[i], "-rp") == 0 || std::strcmp(argv[i], "--relative-paths") == 0) _settings->relativePaths = true; else if (std::strncmp(argv[i], "-rp=", 4) == 0 || std::strncmp(argv[i], "--relative-paths=", 17) == 0) { _settings->relativePaths = true; if (argv[i][argv[i][3]=='='?4:17] != 0) { std::string paths = argv[i]+(argv[i][3]=='='?4:17); for (;;) { std::string::size_type pos = paths.find(';'); if (pos == std::string::npos) { _settings->basePaths.push_back(Path::fromNativeSeparators(paths)); break; } else { _settings->basePaths.push_back(Path::fromNativeSeparators(paths.substr(0, pos))); paths.erase(0, pos + 1); } } } else { PrintMessage("cppcheck: No paths specified for the '" + std::string(argv[i]) + "' option."); return false; } } // Write results in results.xml else if (std::strcmp(argv[i], "--xml") == 0) _settings->xml = true; // Define the XML file version (and enable XML output) else if (std::strncmp(argv[i], "--xml-version=", 14) == 0) { std::string numberString(argv[i]+14); std::istringstream iss(numberString); if (!(iss >> _settings->xml_version)) { PrintMessage("cppcheck: argument to '--xml-version' is not a number."); return false; } if (_settings->xml_version < 0 || _settings->xml_version > 2) { // We only have xml versions 1 and 2 PrintMessage("cppcheck: '--xml-version' can only be 1 or 2."); return false; } // Enable also XML if version is set _settings->xml = true; } // Only print something when there are errors else if (std::strcmp(argv[i], "-q") == 0 || std::strcmp(argv[i], "--quiet") == 0) _settings->quiet = true; // Append user-defined code to checked source code else if (std::strncmp(argv[i], "--append=", 9) == 0) { const std::string filename = 9 + argv[i]; if (!_settings->append(filename)) { PrintMessage("cppcheck: Couldn't open the file: \"" + filename + "\"."); return false; } } // Check configuration else if (std::strcmp(argv[i], "--check-config") == 0) { _settings->checkConfiguration = true; } // Check library definitions else if (std::strcmp(argv[i], "--check-library") == 0) { _settings->checkLibrary = true; } else if (std::strncmp(argv[i], "--enable=", 9) == 0) { const std::string errmsg = _settings->addEnabled(argv[i] + 9); if (!errmsg.empty()) { PrintMessage(errmsg); return false; } // when "style" is enabled, also enable "warning", "performance" and "portability" if (_settings->isEnabled("style")) { _settings->addEnabled("warning"); _settings->addEnabled("performance"); _settings->addEnabled("portability"); } } // --error-exitcode=1 else if (std::strncmp(argv[i], "--error-exitcode=", 17) == 0) { std::string temp = argv[i]+17; std::istringstream iss(temp); if (!(iss >> _settings->exitCode)) { _settings->exitCode = 0; PrintMessage("cppcheck: Argument must be an integer. Try something like '--error-exitcode=1'."); return false; } } // User define else if (std::strncmp(argv[i], "-D", 2) == 0) { std::string define; // "-D define" if (std::strcmp(argv[i], "-D") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-D' is missing."); return false; } define = argv[i]; } // "-Ddefine" else { define = 2 + argv[i]; } // No "=", append a "=1" if (define.find('=') == std::string::npos) define += "=1"; if (!_settings->userDefines.empty()) _settings->userDefines += ";"; _settings->userDefines += define; def = true; } // User undef else if (std::strncmp(argv[i], "-U", 2) == 0) { std::string undef; // "-U undef" if (std::strcmp(argv[i], "-U") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-U' is missing."); return false; } undef = argv[i]; } // "-Uundef" else { undef = 2 + argv[i]; } _settings->userUndefs.insert(undef); } // -E else if (std::strcmp(argv[i], "-E") == 0) { _settings->preprocessOnly = true; } // Include paths else if (std::strncmp(argv[i], "-I", 2) == 0) { std::string path; // "-I path/" if (std::strcmp(argv[i], "-I") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-I' is missing."); return false; } path = argv[i]; } // "-Ipath/" else { path = 2 + argv[i]; } path = Path::removeQuotationMarks(path); path = Path::fromNativeSeparators(path); // If path doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (path.back() != '/') #else if (path[path.size() - 1] != '/') #endif path += '/'; _settings->includePaths.push_back(path); } else if (std::strncmp(argv[i], "--include=", 10) == 0) { std::string path = argv[i] + 10; path = Path::fromNativeSeparators(path); _settings->userIncludes.push_back(path); } else if (std::strncmp(argv[i], "--includes-file=", 16) == 0) { // open this file and read every input file (1 file name per line) AddInclPathsToList(16 + argv[i], &_settings->includePaths); } else if (std::strncmp(argv[i], "--config-exclude=",17) ==0) { std::string path = argv[i] + 17; path = Path::fromNativeSeparators(path); _settings->configExcludePaths.insert(path); } else if (std::strncmp(argv[i], "--config-excludes-file=", 23) == 0) { // open this file and read every input file (1 file name per line) AddPathsToSet(23 + argv[i], &_settings->configExcludePaths); } // file list specified else if (std::strncmp(argv[i], "--file-list=", 12) == 0) { // open this file and read every input file (1 file name per line) AddFilesToList(12 + argv[i], _pathnames); } // Ignored paths else if (std::strncmp(argv[i], "-i", 2) == 0) { std::string path; // "-i path/" if (std::strcmp(argv[i], "-i") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-i' is missing."); return false; } path = argv[i]; } // "-ipath/" else { path = 2 + argv[i]; } if (!path.empty()) { path = Path::removeQuotationMarks(path); path = Path::fromNativeSeparators(path); path = Path::simplifyPath(path); if (FileLister::isDirectory(path)) { // If directory name doesn't end with / or \, add it #if GCC_VERSION >= 40600 if (path.back() != '/') #else if (path[path.size() - 1] != '/') #endif path += '/'; } _ignoredPaths.push_back(path); } } // --library else if (std::strncmp(argv[i], "--library=", 10) == 0) { if (!CppCheckExecutor::tryLoadLibrary(_settings->library, argv[0], argv[i]+10)) return false; } // Report progress else if (std::strcmp(argv[i], "--report-progress") == 0) { _settings->reportProgress = true; } // --std else if (std::strcmp(argv[i], "--std=posix") == 0) { _settings->standards.posix = true; } else if (std::strcmp(argv[i], "--std=c89") == 0) { _settings->standards.c = Standards::C89; } else if (std::strcmp(argv[i], "--std=c99") == 0) { _settings->standards.c = Standards::C99; } else if (std::strcmp(argv[i], "--std=c11") == 0) { _settings->standards.c = Standards::C11; } else if (std::strcmp(argv[i], "--std=c++03") == 0) { _settings->standards.cpp = Standards::CPP03; } else if (std::strcmp(argv[i], "--std=c++11") == 0) { _settings->standards.cpp = Standards::CPP11; } // Output formatter else if (std::strcmp(argv[i], "--template") == 0 || std::strncmp(argv[i], "--template=", 11) == 0) { // "--template path/" if (argv[i][10] == '=') _settings->outputFormat = argv[i] + 11; else if ((i+1) < argc && argv[i+1][0] != '-') { ++i; _settings->outputFormat = argv[i]; } else { PrintMessage("cppcheck: argument to '--template' is missing."); return false; } if (_settings->outputFormat == "gcc") _settings->outputFormat = "{file}:{line}: {severity}: {message}"; else if (_settings->outputFormat == "vs") _settings->outputFormat = "{file}({line}): {severity}: {message}"; else if (_settings->outputFormat == "edit") _settings->outputFormat = "{file} +{line}: {severity}: {message}"; } // Checking threads else if (std::strncmp(argv[i], "-j", 2) == 0) { std::string numberString; // "-j 3" if (std::strcmp(argv[i], "-j") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-j' is missing."); return false; } numberString = argv[i]; } // "-j3" else numberString = argv[i]+2; std::istringstream iss(numberString); if (!(iss >> _settings->jobs)) { PrintMessage("cppcheck: argument to '-j' is not a number."); return false; } if (_settings->jobs > 10000) { // This limit is here just to catch typos. If someone has // need for more jobs, this value should be increased. PrintMessage("cppcheck: argument for '-j' is allowed to be 10000 at max."); return false; } } else if (std::strncmp(argv[i], "-l", 2) == 0) { std::string numberString; // "-l 3" if (std::strcmp(argv[i], "-l") == 0) { ++i; if (i >= argc || argv[i][0] == '-') { PrintMessage("cppcheck: argument to '-l' is missing."); return false; } numberString = argv[i]; } // "-l3" else numberString = argv[i]+2; std::istringstream iss(numberString); if (!(iss >> _settings->loadAverage)) { PrintMessage("cppcheck: argument to '-l' is not a number."); return false; } } // print all possible error messages.. else if (std::strcmp(argv[i], "--errorlist") == 0) { _showErrorMessages = true; _settings->xml = true; _exitAfterPrint = true; } // documentation.. else if (std::strcmp(argv[i], "--doc") == 0) { std::ostringstream doc; // Get documentation.. for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { const std::string& name((*it)->name()); const std::string info((*it)->classInfo()); if (!name.empty() && !info.empty()) doc << "## " << name << " ##\n" << info << "\n"; } std::cout << doc.str(); _exitAfterPrint = true; return true; } // show timing information.. else if (std::strncmp(argv[i], "--showtime=", 11) == 0) { const std::string showtimeMode = argv[i] + 11; if (showtimeMode == "file") _settings->showtime = SHOWTIME_FILE; else if (showtimeMode == "summary") _settings->showtime = SHOWTIME_SUMMARY; else if (showtimeMode == "top5") _settings->showtime = SHOWTIME_TOP5; else if (showtimeMode.empty()) _settings->showtime = SHOWTIME_NONE; else { std::string message("cppcheck: error: unrecognized showtime mode: \""); message += showtimeMode; message += "\". Supported modes: file, summary, top5."; PrintMessage(message); return false; } } #ifdef HAVE_RULES // Rule given at command line else if (std::strncmp(argv[i], "--rule=", 7) == 0) { Settings::Rule rule; rule.pattern = 7 + argv[i]; _settings->rules.push_back(rule); } // Rule file else if (std::strncmp(argv[i], "--rule-file=", 12) == 0) { tinyxml2::XMLDocument doc; if (doc.LoadFile(12+argv[i]) == tinyxml2::XML_SUCCESS) { tinyxml2::XMLElement *node = doc.FirstChildElement(); for (; node && strcmp(node->Value(), "rule") == 0; node = node->NextSiblingElement()) { Settings::Rule rule; tinyxml2::XMLElement *tokenlist = node->FirstChildElement("tokenlist"); if (tokenlist) rule.tokenlist = tokenlist->GetText(); tinyxml2::XMLElement *pattern = node->FirstChildElement("pattern"); if (pattern) { rule.pattern = pattern->GetText(); } tinyxml2::XMLElement *message = node->FirstChildElement("message"); if (message) { tinyxml2::XMLElement *severity = message->FirstChildElement("severity"); if (severity) rule.severity = Severity::fromString(severity->GetText()); tinyxml2::XMLElement *id = message->FirstChildElement("id"); if (id) rule.id = id->GetText(); tinyxml2::XMLElement *summary = message->FirstChildElement("summary"); if (summary) rule.summary = summary->GetText() ? summary->GetText() : ""; } if (!rule.pattern.empty()) _settings->rules.push_back(rule); } } } #endif // Specify platform else if (std::strncmp(argv[i], "--platform=", 11) == 0) { std::string platform(11+argv[i]); if (platform == "win32A") _settings->platform(Settings::Win32A); else if (platform == "win32W") _settings->platform(Settings::Win32W); else if (platform == "win64") _settings->platform(Settings::Win64); else if (platform == "unix32") _settings->platform(Settings::Unix32); else if (platform == "unix64") _settings->platform(Settings::Unix64); else if (platform == "native") _settings->platform(Settings::Unspecified); else if (!_settings->platformFile(platform)) { std::string message("cppcheck: error: unrecognized platform: \""); message += platform; message += "\"."; PrintMessage(message); return false; } } // Set maximum number of #ifdef configurations to check else if (std::strncmp(argv[i], "--max-configs=", 14) == 0) { _settings->force = false; std::istringstream iss(14+argv[i]); if (!(iss >> _settings->maxConfigs)) { PrintMessage("cppcheck: argument to '--max-configs=' is not a number."); return false; } if (_settings->maxConfigs < 1) { PrintMessage("cppcheck: argument to '--max-configs=' must be greater than 0."); return false; } maxconfigs = true; } // Print help else if (std::strcmp(argv[i], "-h") == 0 || std::strcmp(argv[i], "--help") == 0) { _pathnames.clear(); _showHelp = true; _exitAfterPrint = true; break; } else { std::string message("cppcheck: error: unrecognized command line option: \""); message += argv[i]; message += "\"."; PrintMessage(message); return false; } } else { std::string path = Path::removeQuotationMarks(argv[i]); path = Path::fromNativeSeparators(path); _pathnames.push_back(path); } } if (_settings->force) _settings->maxConfigs = ~0U; else if ((def || _settings->preprocessOnly) && !maxconfigs) _settings->maxConfigs = 1U; if (_settings->isEnabled("unusedFunction") && _settings->jobs > 1) { PrintMessage("cppcheck: unusedFunction check can't be used with '-j' option. Disabling unusedFunction check."); } if (_settings->inconclusive && _settings->xml && _settings->xml_version == 1U) { PrintMessage("cppcheck: inconclusive messages will not be shown, because the old xml format is not compatible. It's recommended to use the new xml format (use --xml-version=2)."); } if (argc <= 1) { _showHelp = true; _exitAfterPrint = true; } if (_showHelp) { PrintHelp(); return true; } // Print error only if we have "real" command and expect files if (!_exitAfterPrint && _pathnames.empty()) { PrintMessage("cppcheck: No C or C++ source files found."); return false; } // Use paths _pathnames if no base paths for relative path output are given if (_settings->basePaths.empty() && _settings->relativePaths) _settings->basePaths = _pathnames; return true; } void CmdLineParser::PrintHelp() { std::cout << "Cppcheck - A tool for static C/C++ code analysis\n" "\n" "Syntax:\n" " cppcheck [OPTIONS] [files or paths]\n" "\n" "If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c,\n" "*.tpp, and *.txx files are checked recursively from the given directory.\n\n" "Options:\n" " --append=<file> This allows you to provide information about functions\n" " by providing an implementation for them.\n" " --check-config Check cppcheck configuration. The normal code\n" " analysis is disabled by this flag.\n" " --check-library Show information messages when library files have\n" " incomplete info.\n" " --config-exclude=<dir>\n" " Path (prefix) to be excluded from configuration\n" " checking. Preprocessor configurations defined in\n" " headers (but not sources) matching the prefix will not\n" " be considered for evaluation.\n" " --config-excludes-file=<file>\n" " A file that contains a list of config-excludes\n" " --dump Dump xml data for each translation unit. The dump\n" " files have the extension .dump and contain ast,\n" " tokenlist, symboldatabase, valueflow.\n" " -D<ID> Define preprocessor symbol. Unless --max-configs or\n" " --force is used, Cppcheck will only check the given\n" " configuration when -D is used.\n" " Example: '-DDEBUG=1 -D__cplusplus'.\n" " -U<ID> Undefine preprocessor symbol. Use -U to explicitly\n" " hide certain #ifdef <ID> code paths from checking.\n" " Example: '-UDEBUG'\n" " -E Print preprocessor output on stdout and don't do any\n" " further processing.\n" " --enable=<id> Enable additional checks. The available ids are:\n" " * all\n" " Enable all checks. It is recommended to only\n" " use --enable=all when the whole program is\n" " scanned, because this enables unusedFunction.\n" " * warning\n" " Enable warning messages\n" " * style\n" " Enable all coding style checks. All messages\n" " with the severities 'style', 'performance' and\n" " 'portability' are enabled.\n" " * performance\n" " Enable performance messages\n" " * portability\n" " Enable portability messages\n" " * information\n" " Enable information messages\n" " * unusedFunction\n" " Check for unused functions. It is recommend\n" " to only enable this when the whole program is\n" " scanned.\n" " * missingInclude\n" " Warn if there are missing includes. For\n" " detailed information, use '--check-config'.\n" " Several ids can be given if you separate them with\n" " commas. See also --std\n" " --error-exitcode=<n> If errors are found, integer [n] is returned instead of\n" " the default '0'. '" << EXIT_FAILURE << "' is returned\n" " if arguments are not valid or if no input files are\n" " provided. Note that your operating system can modify\n" " this value, e.g. '256' can become '0'.\n" " --errorlist Print a list of all the error messages in XML format.\n" " --exitcode-suppressions=<file>\n" " Used when certain messages should be displayed but\n" " should not cause a non-zero exitcode.\n" " --file-list=<file> Specify the files to check in a text file. Add one\n" " filename per line. When file is '-,' the file list will\n" " be read from standard input.\n" " -f, --force Force checking of all configurations in files. If used\n" " together with '--max-configs=', the last option is the\n" " one that is effective.\n" " -h, --help Print this help.\n" " -I <dir> Give path to search for include files. Give several -I\n" " parameters to give several paths. First given path is\n" " searched for contained header files first. If paths are\n" " relative to source files, this is not needed.\n" " --includes-file=<file>\n" " Specify directory paths to search for included header\n" " files in a text file. Add one include path per line.\n" " First given path is searched for contained header\n" " files first. If paths are relative to source files,\n" " this is not needed.\n" " --include=<file>\n" " Force inclusion of a file before the checked file. Can\n" " be used for example when checking the Linux kernel,\n" " where autoconf.h needs to be included for every file\n" " compiled. Works the same way as the GCC -include\n" " option.\n" " -i <dir or file> Give a source file or source file directory to exclude\n" " from the check. This applies only to source files so\n" " header files included by source files are not matched.\n" " Directory name is matched to all parts of the path.\n" " --inconclusive Allow that Cppcheck reports even though the analysis is\n" " inconclusive.\n" " There are false positives with this option. Each result\n" " must be carefully investigated before you know if it is\n" " good or bad.\n" " --inline-suppr Enable inline suppressions. Use them by placing one or\n" " more comments, like: '// cppcheck-suppress warningId'\n" " on the lines before the warning to suppress.\n" " -j <jobs> Start <jobs> threads to do the checking simultaneously.\n" #ifdef THREADING_MODEL_FORK " -l <load> Specifies that no new threads should be started if\n" " there are other threads running and the load average is\n" " at least <load>.\n" #endif " --language=<language>, -x <language>\n" " Forces cppcheck to check all files as the given\n" " language. Valid values are: c, c++\n" " --library=<cfg>\n" " Load file <cfg> that contains information about types\n" " and functions. With such information Cppcheck\n" " understands your your code better and therefore you\n" " get better results. The std.cfg file that is\n" " distributed with Cppcheck is loaded automatically.\n" " For more information about library files, read the\n" " manual.\n" " --max-configs=<limit>\n" " Maximum number of configurations to check in a file\n" " before skipping it. Default is '12'. If used together\n" " with '--force', the last option is the one that is\n" " effective.\n" " --platform=<type>, --platform=<file>\n" " Specifies platform specific types and sizes. The\n" " available builtin platforms are:\n" " * unix32\n" " 32 bit unix variant\n" " * unix64\n" " 64 bit unix variant\n" " * win32A\n" " 32 bit Windows ASCII character encoding\n" " * win32W\n" " 32 bit Windows UNICODE character encoding\n" " * win64\n" " 64 bit Windows\n" " * native\n" " Unspecified platform. Type sizes of host system\n" " are assumed, but no further assumptions.\n" " -q, --quiet Do not show progress reports.\n" " -rp, --relative-paths\n" " -rp=<paths>, --relative-paths=<paths>\n" " Use relative paths in output. When given, <paths> are\n" " used as base. You can separate multiple paths by ';'.\n" " Otherwise path where source files are searched is used.\n" " We use string comparison to create relative paths, so\n" " using e.g. ~ for home folder does not work. It is\n" " currently only possible to apply the base paths to\n" " files that are on a lower level in the directory tree.\n" " --report-progress Report progress messages while checking a file.\n" #ifdef HAVE_RULES " --rule=<rule> Match regular expression.\n" " --rule-file=<file> Use given rule file. For more information, see: \n" " http://sourceforge.net/projects/cppcheck/files/Articles/\n" #endif " --std=<id> Set standard.\n" " The available options are:\n" " * posix\n" " POSIX compatible code\n" " * c89\n" " C code is C89 compatible\n" " * c99\n" " C code is C99 compatible\n" " * c11\n" " C code is C11 compatible (default)\n" " * c++03\n" " C++ code is C++03 compatible\n" " * c++11\n" " C++ code is C++11 compatible (default)\n" " More than one --std can be used:\n" " 'cppcheck --std=c99 --std=posix file.c'\n" " --suppress=<spec> Suppress warnings that match <spec>. The format of\n" " <spec> is:\n" " [error id]:[filename]:[line]\n" " The [filename] and [line] are optional. If [error id]\n" " is a wildcard '*', all error ids match.\n" " --suppressions-list=<file>\n" " Suppress warnings listed in the file. Each suppression\n" " is in the same format as <spec> above.\n" " --template='<text>' Format the error messages. E.g.\n" " '{file}:{line},{severity},{id},{message}' or\n" " '{file}({line}):({severity}) {message}' or\n" " '{callstack} {message}'\n" " Pre-defined templates: gcc, vs, edit.\n" " -v, --verbose Output more detailed error information.\n" " --version Print out version number.\n" " --xml Write results in xml format to error stream (stderr).\n" " --xml-version=<version>\n" " Select the XML file version. Currently versions 1 and\n" " 2 are available. The default version is 1." "\n" "Example usage:\n" " # Recursively check the current folder. Print the progress on the screen and\n" " # write errors to a file:\n" " cppcheck . 2> err.txt\n" "\n" " # Recursively check ../myproject/ and don't print progress:\n" " cppcheck --quiet ../myproject/\n" "\n" " # Check test.cpp, enable all checks:\n" " cppcheck --enable=all --inconclusive --std=posix test.cpp\n" "\n" " # Check f.cpp and search include files from inc1/ and inc2/:\n" " cppcheck -I inc1/ -I inc2/ f.cpp\n" "\n" "For more information:\n" " http://cppcheck.net/manual.pdf\n"; }
Nicobubu/cppcheck
cli/cmdlineparser.cpp
C++
gpl-3.0
46,169
<?php /** * Created by PhpStorm. * User: Ermin Islamagić - https://ermin.islamagic.com * Date: 22.8.2016 * Time: 09:37 */ // Check if root path is defined if (!defined("ROOT_PATH")) { // Show 403 if root path not defined header("HTTP/1.1 403 Forbidden"); exit; } /** * Class LocaleAppController */ class LocaleAppController extends Plugin { /** * LocaleAppController constructor. */ public function __construct() { $this->setLayout('ActionAdmin'); } /** * @param $const * @return null */ public static function getConst($const) { $registry = Registry::getInstance(); $store = $registry->get('Locale'); return isset($store[$const]) ? $store[$const] : NULL; } /** * @return array */ public function ActionCheckInstall() { $this->setLayout('ActionEmpty'); $result = array('status' => 'OK', 'code' => 200, 'text' => 'Operation succeeded', 'info' => array()); $folders = array(UPLOAD_PATH . 'locale'); foreach ($folders as $dir) { if (!is_writable($dir)) { $result['status'] = 'ERR'; $result['code'] = 101; $result['text'] = 'Permission requirement'; $result['info'][] = sprintf('Folder \'<span class="bold">%1$s</span>\' is not writable. You need to set write permissions (chmod 777) to directory located at \'<span class="bold">%1$s</span>\'', $dir); } } return $result; } }
clientmarketing/food-factory
source/app/plugins/Locale/controllers/LocaleAppController.controller.php
PHP
gpl-3.0
1,402
/*************************************************************************** begin : Thu Apr 24 15:54:58 CEST 2003 copyright : (C) 2003 by Giuseppe Lipari email : lipari@sssup.it ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <algorithm> #include <string> #include <simul.hpp> #include <server.hpp> #include <jtrace.hpp> #include <task.hpp> #include <task.hpp> #include <waitinstr.hpp> namespace RTSim { using namespace std; using namespace MetaSim; // Init globals JavaTrace::TRACE_ENDIANESS JavaTrace::endianess = TRACE_UNKNOWN_ENDIAN; string JavaTrace::version = "1.2"; JavaTrace::JavaTrace(const char *name, bool tof, unsigned long int limit) :Trace(name, Trace::BINARY, tof), taskList(10) { if (endianess == TRACE_UNKNOWN_ENDIAN) probeEndianess(); const char cver[] = "version 1.2"; if (toFile) _os.write(cver, sizeof(cver)); filenum = 0; fileLimit = limit; } JavaTrace::~JavaTrace() { // WARNING: the data vector is cleared but its content isn't. It // must be deleted manually (close). if (toFile) Trace::close(); else data.clear(); } void JavaTrace::probeEndianess(void) { // Used for endianess check (Big/Little!) static char const big_endian[] = { static_cast<char const>(0xff), static_cast<char const>(0), static_cast<char const>(0xff), static_cast<char const>(0)}; static int const probe = 0xff00ff00; int *probePtr = (int *)(big_endian); if (*probePtr == probe) endianess = TRACE_BIG_ENDIAN; else endianess = TRACE_LITTLE_ENDIAN; //DBGFORCE("Endianess: " << (endianess == TRACE_LITTLE_ENDIAN ? "Little\n" : "Big\n")); } void JavaTrace::close() { if (toFile) Trace::close(); else { for (unsigned int i = 0; i < data.size(); i++) delete data[i]; data.clear(); } } void JavaTrace::record(Event* e) { DBGENTER(_JTRACE_DBG_LEV); TaskEvt* ee = dynamic_cast<TaskEvt*>(e); if (ee == NULL) { DBGPRINT("The event is not a TaskEvt"); return; } Task* task = ee->getTask(); if (task != NULL) { vector<int>::const_iterator p = find(taskList.begin(), taskList.end(), task->getID()); if (p == taskList.end()) { TraceNameEvent* a = new TraceNameEvent(ee->getLastTime(), task->getID(), task->getName()); if (toFile) a->write(_os); else data.push_back(a); taskList.push_back(task->getID()); } } // at this point we have to see what kind of event it is... if (dynamic_cast<ArrEvt*>(e) != NULL) { DBGPRINT("ArrEvt"); ArrEvt* tae = dynamic_cast<ArrEvt*>(e); TraceArrEvent* a = new TraceArrEvent(e->getLastTime(), task->getID()); if (toFile) a->write(_os); else data.push_back(a); Task* rttask = dynamic_cast<Task*>(task); if (rttask) { TraceDlineSetEvent* b = new TraceDlineSetEvent(tae->getLastTime(), rttask->getID(), rttask->getDeadline()); if (toFile) b->write(_os); else data.push_back(b); } } else if (dynamic_cast<EndEvt*>(e) != NULL) { DBGPRINT("EndEvt"); EndEvt* tee = dynamic_cast<EndEvt*>(e); TraceEndEvent* a = new TraceEndEvent(tee->getLastTime(), task->getID(), tee->getCPU()); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<DeschedEvt*>(e) != NULL) { DBGPRINT("DeschedEvt"); DeschedEvt *tde = dynamic_cast<DeschedEvt *>(e); TraceDeschedEvent* a = new TraceDeschedEvent(tde->getLastTime(), task->getID(), tde->getCPU()); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<WaitEvt*>(e) != NULL) { DBGPRINT("WaitEvt"); WaitEvt* we = dynamic_cast<WaitEvt*>(e); //WaitInstr* instr = dynamic_cast<WaitInstr*>(we->getInstr()); WaitInstr* instr = we->getInstr(); string res = instr->getResource(); TraceWaitEvent* a = new TraceWaitEvent(we->getLastTime(), task->getID(), res); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<SignalEvt*>(e) != NULL) { DBGPRINT("SignalEvt"); SignalEvt* se = dynamic_cast<SignalEvt*>(e); //SignalInstr* instr = dynamic_cast<SignalInstr*>(se->getInstr()); SignalInstr* instr = se->getInstr(); string res = instr->getResource(); TraceSignalEvent* a = new TraceSignalEvent(se->getLastTime(), task->getID(), res); if (toFile) a->write(_os); else data.push_back(a); } else if (dynamic_cast<SchedEvt*>(e) != NULL) { DBGPRINT("SchedEvt"); SchedEvt* tse = dynamic_cast<SchedEvt*>(e); TraceSchedEvent* a = new TraceSchedEvent(tse->getLastTime(), task->getID(), tse->getCPU()); if (toFile) a->write(_os); else data.push_back(a); // } else if (dynamic_cast<DlinePostEvt*>(e) != NULL) { // DBGPRINT("DlinePostEvt"); // DlinePostEvt* dpe = dynamic_cast<DlinePostEvt*>(e); // TraceDlinePostEvent* a = new TraceDlinePostEvent(dpe->getLastTime(), // task->getID(), // dpe->getPrevDline(), // dpe->getPostDline()); // if (toFile) a->write(_os); // else data.push_back(a); } else if (dynamic_cast<DeadEvt*>(e) != NULL) { DBGPRINT("DlineMissEvt"); DeadEvt* de = dynamic_cast<DeadEvt*>(e); TraceDlineMissEvent* a = new TraceDlineMissEvent(de->getLastTime(), task->getID()); if (toFile) a->write(_os); else data.push_back(a); } if (toFile) _os.flush(); } }
glipari/rtlib
src/jtrace.cpp
C++
gpl-3.0
6,330
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required def centres(request): #Python练习项目管理中心Center return render(request, 'centres/centres.html') def upload(request): #文件上传 return render(request, 'centres/upload.html') def uploadfile(request): import os if request.method == "POST": # 请求方法为POST时,进行处理 myFile =request.FILES.get("myfile", None) # 获取上传的文件,如果没有文件,则默认为None if not myFile: #return HttpResponse("no files for upload!") return render(request, 'centres/upload.html',{'what':'no file for upload!'}) upfile = open(os.path.join("D:\\xHome\\data\\upload",myFile.name),'wb+') # 打开特定的文件进行二进制的写操作 for chunk in myFile.chunks(): # 分块写入文件 upfile.write(chunk) upfile.close() #return HttpResponse("upload over!") return render(request, 'centres/upload.html', {'what':'upload over!'})
xBoye/xHome
centres/views.py
Python
gpl-3.0
1,162
import cv2 import numpy as np np.set_printoptions(threshold=np.nan) import util as util import edge_detect import lineseg import drawedgelist # img = cv2.imread("img/Slide2.jpg", 0) img = cv2.imread("unsorted/Unit Tests/lambda.png", 0) im_size = img.shape returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3) cv2.imshow("newcanny", returnedCanny) skel_dst = util.morpho(returnedCanny) out = edge_detect.mask_contours(edge_detect.create_img(skel_dst)) res = [] # print(np.squeeze(out[0])) # print(out[0][0]) for i in range(len(out)): # Add the first point to the end so the shape closes current = np.squeeze(out[i]) # print('current', current) # print('first', out[i][0]) if current.shape[0] > 2: # res.append(np.concatenate((current, out[i][0]))) # print(res[-1]) res.append(current) # print(np.concatenate((np.squeeze(out[i]), out[i][0]))) res = np.array(res) util.sqz_contours(res) res = lineseg.lineseg(np.array([res[1]]), tol=5) print(res, "res") """ for x in range(len(res)): for y in range(lan ): """ drawedgelist.drawedgelist(res, img) """ seglist = [] for i in range(res.shape[0]): # print('shape', res[i].shape) if res[i].shape[0] > 2: # print(res[i]) # print(res[i][0]) seglist.append(np.concatenate((res[i], [res[i][0]]))) else: seglist.append(res[i]) seglist = np.array(seglist) """ #print(seglist, "seglist") #print(len(seglist), "seglist len") #print(seglist.shape, "seglistshape") #drawedgelist.drawedgelist(seglist) """ # ******* SECTION 2 ******* # SEGMENT AND LABEL THE CURVATURE LINES (CONVEX/CONCAVE). LineFeature, ListPoint = Lseg_to_Lfeat_v4.create_linefeatures(seglist, res, im_size) Line_new, ListPoint_new, line_merged = merge_lines_v4.merge_lines(LineFeature, ListPoint, 10, im_size) #print(Line_new, "line new") print(len(Line_new), "len line new") util.draw_lf(Line_new, blank_image) line_newC = LabelLineCurveFeature_v4.classify_curves(img, Line_new, ListPoint_new, 11)"""
Jordan-Zhu/RoboVision
scratch/testingColorImg.py
Python
gpl-3.0
2,023
"use strict"; module.exports = function registerDefaultRoutes( baseUrl, app, opts ){ var controller = opts.controller; var listRouter = app.route( baseUrl ); if( opts.all ){ listRouter = listRouter.all( opts.all ); } if( opts.list ){ listRouter.get( opts.list ); } if( opts.create ){ listRouter.post( opts.create ); } listRouter.get( controller.list ) .post( controller.create ); var resourceRouter = app.route( baseUrl + "/:_id" ); if( opts.all ){ resourceRouter.all( opts.all ); } if( opts.retrieve ){ resourceRouter.get(opts.retrieve); } if(opts.update){ resourceRouter.patch(opts.update); } if(opts.remove){ resourceRouter.delete(opts.remove); } resourceRouter.get( controller.retrieve ) .patch( controller.update ) .delete( controller.remove ); return { list: listRouter, resources: resourceRouter }; };
beni55/d-pac.cms
app/routes/api/helpers/registerDefaultRoutes.js
JavaScript
gpl-3.0
999
package it.ads.activitiesmanager.model.dao; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; //Segnala che si tratta di una classe DAO (o Repository) @Repository //Significa che tutti i metodi della classe sono definiti come @Transactional @Transactional public abstract class AbstractDao<T extends Serializable> { private Class<T> c; @PersistenceContext EntityManager em; public final void setClass(Class<T> c){ this.c = c; } public T find(Integer id) { return em.find(c,id); } public List<T> findAll(){ String SELECT = "SELECT * FROM " + c.getName(); Query query = em.createQuery(SELECT); return query.getResultList(); } public void save(T entity){ em.persist(entity); } public void update(T entity){ em.merge(entity); } public void delete(T entity){ em.remove(entity); } public void deleteById(Integer id){ T entity = find(id); delete(entity); } }
paoloap/activitiesmanager
activitiesmanager-model/src/main/java/it/ads/activitiesmanager/model/dao/AbstractDao.java
Java
gpl-3.0
1,147
#include "VRConstructionKit.h" #include "selection/VRSelector.h" #include "core/objects/geometry/VRGeometry.h" #include "core/objects/material/VRMaterial.h" #include "core/utils/toString.h" #include "core/utils/VRFunction.h" #include "core/setup/devices/VRDevice.h" #include "core/setup/devices/VRSignal.h" using namespace OSG; VRConstructionKit::VRConstructionKit() { snapping = VRSnappingEngine::create(); selector = VRSelector::create(); onSnap = VRSnappingEngine::VRSnapCb::create("on_snap_callback", bind(&VRConstructionKit::on_snap, this, placeholders::_1)); snapping->getSignalSnap()->add(onSnap); } VRConstructionKit::~VRConstructionKit() {} VRConstructionKitPtr VRConstructionKit::create() { return VRConstructionKitPtr(new VRConstructionKit()); } void VRConstructionKit::clear() { objects.clear(); selector->clear(); snapping->clear(); } VRSnappingEnginePtr VRConstructionKit::getSnappingEngine() { return snapping; } VRSelectorPtr VRConstructionKit::getSelector() { return selector; } vector<VRObjectPtr> VRConstructionKit::getObjects() { vector<VRObjectPtr> res; for (auto m : objects) res.push_back(m.second); return res; } bool VRConstructionKit::on_snap(VRSnappingEngine::EventSnapWeakPtr we) { if (!doConstruction) return true; auto e = we.lock(); if (!e) return true; if (!e->snap) { breakup(e->o1); return true; } if (!e->o1 || !e->o2) return true; VRObjectPtr p1 = e->o1->getDragParent(); VRObjectPtr p2 = e->o2->getParent(); if (p1 == 0 || p2 == 0) return true; if (p1 == p2) if (p1->hasTag("kit_group")) return true; if (p2->hasTag("kit_group")) { e->o1->rebaseDrag(p2); e->o1->setPickable(false); e->o2->setPickable(false); e->o1->setWorldMatrix(e->m); return true; } VRTransformPtr group = VRTransform::create("kit_group"); group->setPersistency(0); group->setPickable(true); group->addAttachment("kit_group", 0); p2->addChild(group); e->o1->rebaseDrag(group); Matrix4d m = e->o2->getWorldMatrix(); e->o2->switchParent(group); e->o1->setPickable(false); e->o2->setPickable(false); e->o1->setWorldMatrix(e->m); e->o2->setWorldMatrix(m); return true; } int VRConstructionKit::ID() { static int i = 0; i++; return i; } void VRConstructionKit::breakup(VRTransformPtr obj) { if (!doConstruction) return; if (obj == 0) return; auto p = obj->getParent(); if (p == 0) return; if (p->hasTag("kit_group")) { obj->switchParent( p->getParent() ); obj->setPickable(true); return; } p = obj->getDragParent(); if (p == 0) return; if (p->hasTag("kit_group")) { obj->rebaseDrag( p->getParent() ); obj->setPickable(true); } } int VRConstructionKit::addAnchorType(float size, Color3f color) { auto g = VRGeometry::create("anchor"); string bs = toString(size); g->setPrimitive("Box " + bs + " " + bs + " " + bs + " 1 1 1"); auto m = VRMaterial::create("anchor"); m->setDiffuse(color); g->setMaterial(m); int id = ID(); anchors[id] = g; return id; } void VRConstructionKit::toggleConstruction(bool active) { doConstruction = active; } void VRConstructionKit::addObject(VRTransformPtr t) { objects[t.get()] = t; snapping->addObject(t); } void VRConstructionKit::remObject(VRTransformPtr t) { objects.erase(t.get()); snapping->remObject(t); } VRGeometryPtr VRConstructionKit::addObjectAnchor(VRTransformPtr t, int a, Vec3d pos, float radius) { if (!anchors.count(a)) return 0; Vec3d d(0,1,0); Vec3d u(1,0,0); VRGeometryPtr anc = static_pointer_cast<VRGeometry>(anchors[a]->duplicate()); anc->setTransform(pos, d, u); anc->show(); anc->switchParent(t); snapping->addObjectAnchor(t, anc); snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), d, u), radius, 0, t ); //snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(Vec3d(), Vec3d(1,0,0), Vec3d(0,1,0)), radius, 0, t ); //snapping->addRule(VRSnappingEngine::POINT, VRSnappingEngine::POINT, Pose::create(), Pose::create(), radius, 0, t ); return anc; }
Victor-Haefner/polyvr
src/core/tools/VRConstructionKit.cpp
C++
gpl-3.0
4,295
/* _ /_\ _ _ ___ ___ / _ \| '_/ -_|_-< /_/ \_\_| \___/__/ */ #include "Ares.h" /* Description: Function that is called when the library is loaded, use this as an entry point. */ int __attribute__((constructor)) Ares() { SDL2::SetupSwapWindow(); return 0; }
gitaphu/Ares
Source/Ares.cpp
C++
gpl-3.0
277
#!/usr/bin/env python # setup of the grid parameters # default queue used for training training_queue = { 'queue':'q1dm', 'memfree':'16G', 'pe_opt':'pe_mth 2', 'hvmem':'8G', 'io_big':True } # the queue that is used solely for the final ISV training step isv_training_queue = { 'queue':'q1wm', 'memfree':'32G', 'pe_opt':'pe_mth 4', 'hvmem':'8G' } # number of audio files that one job should preprocess number_of_audio_files_per_job = 1000 preprocessing_queue = {} # number of features that one job should extract number_of_features_per_job = 600 extraction_queue = { 'queue':'q1d', 'memfree':'8G' } # number of features that one job should project number_of_projections_per_job = 600 projection_queue = { 'queue':'q1d', 'hvmem':'8G', 'memfree':'8G' } # number of models that one job should enroll number_of_models_per_enrol_job = 20 enrol_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } # number of models that one score job should process number_of_models_per_score_job = 20 score_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } grid_type = 'local' # on Idiap grid
guker/spear
config/grid/para_training_local.py
Python
gpl-3.0
1,092
package ca.six.tomato.util; import org.json.JSONArray; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowEnvironment; import java.io.File; import ca.six.tomato.BuildConfig; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; /** * Created by songzhw on 2016-10-03 */ @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class DataUtilsTest { @Test public void testFile() { File dstFile = ShadowEnvironment.getExternalStorageDirectory(); assertTrue(dstFile.exists()); System.out.println("szw isDirectory = " + dstFile.isDirectory()); //=> true System.out.println("szw isExisting = " + dstFile.exists()); //=> true System.out.println("szw path = " + dstFile.getPath()); //=> C:\Users\***\AppData\Local\Temp\android-tmp-robolectric7195966122073188215 } @Test public void testWriteString(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; DataUtilKt.write("abc", path); String ret = DataUtilKt.read(path, false); assertEquals("abc", ret); } @Test public void testWriteJSON(){ File dstFile = ShadowEnvironment.getExternalStorageDirectory(); String path = dstFile.getPath() +"/tmp"; String content = " {\"clock\": \"clock1\", \"work\": 40, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock2\", \"work\": 30, \"short\": 5, \"long\": 15}\n" + " {\"clock\": \"clock3\", \"work\": 45, \"short\": 5, \"long\": 15}"; DataUtilKt.write(content, path); JSONArray ret = DataUtilKt.read(path); System.out.println("szw, ret = "+ret.toString()); assertNotNull(ret); } }
SixCan/SixTomato
app/src/test/java/ca/six/tomato/util/DataUtilsTest.java
Java
gpl-3.0
2,002
/* * The basic test codes to check the AnglogIn. */ #include "mbed.h" static AnalogIn ain_x(A6); // connect joistics' x axis to A6 pin of mbed static AnalogIn ain_y(A5); // connect joistics' y axis to A5 pin of mbed static void printAnalogInput(AnalogIn *xin, AnalogIn *yin) { uint8_t point[2] = { 0 }; point[0] = (uint8_t)(xin->read()*100.0f + 0.5); point[1] = (uint8_t)(yin->read()*100.0f + 0.5); printf("x: %d, y: %d\n", point[0], point[1]); } int main() { while(1) { printAnalogInput(&ain_x, &ain_y); wait(0.2f); } }
Darkblue38/mbedTrust
MiniProjects/AnalogInOut/Joistick/TestAnalogInUsingJoistick.cpp
C++
gpl-3.0
563
/*** * Copyright (c) 2013 John Krauss. * * This file is part of Crashmapper. * * Crashmapper 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. * * Crashmapper 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 Crashmapper. If not, see <http://www.gnu.org/licenses/>. * ***/ /*jslint browser: true, nomen: true, sloppy: true*/ /*globals Backbone, Crashmapper */ /** * @param {Object} options * @constructor * @extends Backbone.View */ Crashmapper.AppView = Backbone.View.extend({ id: 'app', /** * @this {Crashmapper.AppView} */ initialize: function () { this.about = new Crashmapper.AboutView({}).render(); this.about.$el.appendTo(this.$el).hide(); this.map = new Crashmapper.MapView({}); this.map.$el.appendTo(this.$el); }, /** * @this {Crashmapper.AppView} */ render: function () { return this; } });
talos/nypd-crash-data-bandaid
map/src/views/app.js
JavaScript
gpl-3.0
1,396
/* **************************************************************************** * * Copyright Saab AB, 2005-2013 (http://safirsdkcore.com) * * Created by: Lars Hagström / stlrha * ******************************************************************************* * * This file is part of Safir SDK Core. * * Safir SDK Core is free software: you can redistribute it and/or modify * it under the terms of version 3 of the GNU General Public License as * published by the Free Software Foundation. * * Safir SDK Core 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 Safir SDK Core. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ using System; using System.Collections.Generic; using System.Text; namespace Safir.Dob.Typesystem { /// <summary> /// Base class for all Containers. /// <para/> ///This class contains common functionality for all Containers. /// Basically this amounts to the interface for nullability and /// the change flag. /// </summary> abstract public class ContainerBase { /// <summary> /// Default Constructor. /// <para/> /// Construct a container that is not changed. /// </summary> public ContainerBase() { m_bIsChanged = false; } /// <summary> /// Is the container set to null? /// </summary> /// <returns>True if the container is set to null.</returns> abstract public bool IsNull(); /// <summary> /// Set the container to null. /// </summary> abstract public void SetNull(); /// <summary> /// Is the change flag set on the container? /// <para/> /// The change flag gets updated every time the contained value changes. /// <para/> /// Note: If this is a container containing objects this call will recursively /// check change flags in the contained objects. /// </summary> /// <returns> True if the containers change flag is set.</returns> virtual public bool IsChanged() { return m_bIsChanged; } /// <summary> /// Set the containers change flag. /// <para/> /// It should be fairly unusual for an application to have to use this /// operation. There is nothing dangerous about it, but are you sure this /// is the operation you were after? /// <para/> /// The change flag is how receivers of objects can work out what the /// sender really wanted done on the object. /// <para/> /// Note: If this is a container containing one or more objects this call /// will recursively set all the change flags in the contained objects. /// </summary> /// <param name="changed">The value to set the change flag(s) to.</param> virtual public void SetChanged(bool changed) { m_bIsChanged = changed; } #region Cloning /// <summary> /// Create a copy of the Container. /// <para> /// This method is deprecated. /// </para> /// </summary> public dynamic Clone() { return this.DeepClone(); } /// <summary> /// Copy. /// </summary> /// <param name="other">Other ContainerBase.</param> virtual public void Copy(ContainerBase other) { ShallowCopy(other); } #endregion /// <summary> /// Flag accessible from subclasses. /// </summary> protected internal bool m_bIsChanged; virtual internal void ShallowCopy(ContainerBase other) { if (this.GetType() != other.GetType()) { throw new SoftwareViolationException("Invalid call to Copy, containers are not of same type"); } m_bIsChanged = other.m_bIsChanged; } } }
SafirSDK/safir-sdk-core
src/dots/dots_dotnet.ss/src/ContainerBase.cs
C#
gpl-3.0
4,296
#!/usr/bin/python2 # -*- coding: utf-8 -*- # coding=utf-8 import unittest from datetime import datetime from lib.escala import Escala import dirs dirs.DEFAULT_DIR = dirs.TestDir() class FrameTest(unittest.TestCase): def setUp(self): self.escala = Escala('fixtures/escala.xml') self.dir = dirs.TestDir() self.maxDiff = None def tearDown(self): pass def test_attributos_voo_1(self): p_voo = self.escala.escalas[0] self.assertEqual(p_voo.activity_date, datetime(2013, 3, 1, 11, 36)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, '4148') self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'GYN') self.assertEqual(p_voo.actype, 'E95') self.assertTrue(p_voo.checkin) self.assertEqual(p_voo.checkin_time, datetime(2013, 3, 1, 10, 36)) self.assertEqual(p_voo.std, datetime(2013, 3, 1, 13, 13)) self.assertEqual(p_voo.sta, datetime(2013, 3, 1, 11, 36)) self.assertEqual(p_voo.activity_info, 'AD4148') self.assertFalse(p_voo.duty_design) def test_attributos_voo_17(self): p_voo = self.escala.escalas[17] self.assertEqual(p_voo.activity_date, datetime(2013, 10, 28, 3, 0)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, None) self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'VCP') self.assertEqual(p_voo.activity_info, 'P04') self.assertEqual(p_voo.actype, None) self.assertEqual(p_voo.sta, datetime(2013, 10, 28, 3, 0)) self.assertEqual(p_voo.std, datetime(2013, 10, 28, 15, 0)) self.assertFalse(p_voo.checkin) self.assertEqual(p_voo.checkin_time, None) self.assertFalse(p_voo.duty_design) def test_attributos_voo_18(self): p_voo = self.escala.escalas[18] self.assertEqual(p_voo.activity_date, datetime(2013, 10, 29, 4, 58)) self.assertEqual(p_voo.present_location, 'VCP') self.assertEqual(p_voo.flight_no, '4050') self.assertEqual(p_voo.origin, 'VCP') self.assertEqual(p_voo.destination, 'FLN') self.assertEqual(p_voo.activity_info, 'AD4050') self.assertEqual(p_voo.actype, 'E95') self.assertEqual(p_voo.sta, datetime(2013, 10, 29, 4, 58)) self.assertEqual(p_voo.std, datetime(2013, 10, 29, 6, 15)) self.assertTrue(p_voo.checkin) self.assertEqual(p_voo.checkin_time, datetime(2013, 10, 29, 5, 8)) self.assertFalse(p_voo.duty_design) self.assertEqual(p_voo.horas_de_voo, '1:17') def test_attributos_quarto_voo(self): p_voo = self.escala.escalas[25] self.assertFalse(p_voo.checkin) self.assertEqual(p_voo.checkin_time, None) self.assertEqual(p_voo.flight_no, '2872') self.assertEqual(p_voo.activity_info, 'AD2872') def test_calculo_horas_voadas(self): s_horas = { 'h_diurno': '6:40', 'h_noturno': '6:47', 'h_total_voo': '13:27', 'h_faixa2': '0:00', 'h_sobreaviso': '40:00', 'h_reserva': '29:13' } self.assertEqual(self.escala.soma_horas(), s_horas) def test_ics(self): """ Check ICS output """ escala = Escala('fixtures/escala_ics.xml') f_result = open(self.dir.get_data_dir() + 'fixtures/escala.ics') self.assertEqual(escala.ics(), f_result.read()) f_result.close() def test_csv(self): """ Check CSV output """ f_result = open(self.dir.get_data_dir() + 'fixtures/escala.csv') self.assertEqual(self.escala.csv(), f_result.read()) f_result.close() def main(): unittest.main() if __name__ == '__main__': main()
camponez/importescala
test/test_escala.py
Python
gpl-3.0
3,876
package net.thevpc.upa.impl; import net.thevpc.upa.*; import net.thevpc.upa.impl.transform.IdentityDataTypeTransform; import net.thevpc.upa.impl.util.NamingStrategy; import net.thevpc.upa.impl.util.NamingStrategyHelper; import net.thevpc.upa.impl.util.PlatformUtils; import net.thevpc.upa.types.*; import net.thevpc.upa.exceptions.UPAException; import net.thevpc.upa.filters.FieldFilter; import net.thevpc.upa.types.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public abstract class AbstractField extends AbstractUPAObject implements Field, Comparable<Object> { protected Entity entity; protected EntityItem parent; protected DataType dataType; protected Formula persistFormula; protected int persistFormulaOrder; protected Formula updateFormula; protected int updateFormulaOrder; protected Formula queryFormula; protected Object defaultObject; protected SearchOperator searchOperator = SearchOperator.DEFAULT; protected DataTypeTransform typeTransform; protected HashMap<String, Object> properties; protected FlagSet<UserFieldModifier> userModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<UserFieldModifier> userExcludeModifiers = FlagSets.noneOf(UserFieldModifier.class); protected FlagSet<FieldModifier> effectiveModifiers = FlagSets.noneOf(FieldModifier.class); protected boolean closed; protected Object unspecifiedValue = UnspecifiedValue.DEFAULT; private AccessLevel persistAccessLevel = AccessLevel.READ_WRITE; private AccessLevel updateAccessLevel = AccessLevel.READ_WRITE; private AccessLevel readAccessLevel = AccessLevel.READ_WRITE; private ProtectionLevel persistProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel updateProtectionLevel = ProtectionLevel.PUBLIC; private ProtectionLevel readProtectionLevel = ProtectionLevel.PUBLIC; private FieldPersister fieldPersister; private PropertyAccessType accessType; private List<Relationship> manyToOneRelationships; private List<Relationship> oneToOneRelationships; private boolean _customDefaultObject = false; private Object _typeDefaultObject = false; protected AbstractField() { } @Override public String getAbsoluteName() { return (getEntity() == null ? "?" : getEntity().getName()) + "." + getName(); } public EntityItem getParent() { return parent; } public void setParent(EntityItem item) { EntityItem old = this.parent; EntityItem recent = item; beforePropertyChangeSupport.firePropertyChange("parent", old, recent); this.parent = item; afterPropertyChangeSupport.firePropertyChange("parent", old, recent); } @Override public void commitModelChanges() { manyToOneRelationships = getManyToOneRelationshipsImpl(); oneToOneRelationships = getOneToOneRelationshipsImpl(); } public boolean is(FieldFilter filter) throws UPAException { return filter.accept(this); } public boolean isId() throws UPAException { return getModifiers().contains(FieldModifier.ID); } @Override public boolean isGeneratedId() throws UPAException { if (!isId()) { return false; } Formula persistFormula = getPersistFormula(); return (persistFormula != null); } public boolean isMain() throws UPAException { return getModifiers().contains(FieldModifier.MAIN); } @Override public boolean isSystem() { return getModifiers().contains(FieldModifier.SYSTEM); } public boolean isSummary() throws UPAException { return getModifiers().contains(FieldModifier.SUMMARY); } public List<Relationship> getManyToOneRelationships() { return manyToOneRelationships; } public List<Relationship> getOneToOneRelationships() { return oneToOneRelationships; } protected List<Relationship> getManyToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } protected List<Relationship> getOneToOneRelationshipsImpl() { List<Relationship> relations = new ArrayList<Relationship>(); for (Relationship r : getPersistenceUnit().getRelationshipsBySource(getEntity())) { Field entityField = r.getSourceRole().getEntityField(); if (entityField != null && entityField.equals(this)) { relations.add(r); } else { List<Field> fields = r.getSourceRole().getFields(); for (Field field : fields) { if (field.equals(this)) { relations.add(r); } } } } return PlatformUtils.trimToSize(relations); } public void setFormula(Formula formula) { setPersistFormula(formula); setUpdateFormula(formula); } @Override public void setFormula(String formula) { setFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setPersistFormula(Formula formula) { this.persistFormula = formula; } public void setUpdateFormula(Formula formula) { this.updateFormula = formula; } @Override public void setFormulaOrder(int order) { setPersistFormulaOrder(order); setUpdateFormulaOrder(order); } public int getUpdateFormulaOrder() { return updateFormulaOrder; } @Override public void setUpdateFormulaOrder(int order) { this.updateFormulaOrder = order; } public int getPersistFormulaOrder() { return persistFormulaOrder; } @Override public void setPersistFormulaOrder(int order) { this.persistFormulaOrder = order; } public Formula getUpdateFormula() { return updateFormula; } @Override public void setUpdateFormula(String formula) { setUpdateFormula(formula == null ? null : new ExpressionFormula(formula)); } public Formula getSelectFormula() { return queryFormula; } @Override public void setSelectFormula(String formula) { setSelectFormula(formula == null ? null : new ExpressionFormula(formula)); } public void setSelectFormula(Formula queryFormula) { this.queryFormula = queryFormula; } // public boolean isRequired() throws UPAException { // return (!isReadOnlyOnPersist() || !isReadOnlyOnUpdate()) && !getDataType().isNullable(); // } public String getPath() { EntityItem parent = getParent(); return parent == null ? ("/" + getName()) : (parent.getPath() + "/" + getName()); } @Override public PersistenceUnit getPersistenceUnit() { return entity.getPersistenceUnit(); } public Formula getPersistFormula() { return persistFormula; } @Override public void setPersistFormula(String formula) { setPersistFormula(formula == null ? null : new ExpressionFormula(formula)); } public Entity getEntity() { return entity; } public void setEntity(Entity entity) { this.entity = entity; } public DataType getDataType() { return dataType; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param datatype datatype */ @Override public void setDataType(DataType datatype) { this.dataType = datatype; if (!getDataType().isNullable()) { _typeDefaultObject = getDataType().getDefaultValue(); } else { _typeDefaultObject = null; } } public Object getDefaultValue() { if (_customDefaultObject) { Object o = ((CustomDefaultObject) defaultObject).getObject(); if (o == null) { o = _typeDefaultObject; } return o; } else { Object o = defaultObject; if (o == null) { o = _typeDefaultObject; } return o; } } public Object getDefaultObject() { return defaultObject; } /** * called by PersistenceUnitFilter / Table You should not use it * * @param o default value witch may be san ObjectHandler */ public void setDefaultObject(Object o) { defaultObject = o; if (o instanceof CustomDefaultObject) { _customDefaultObject = true; } } public FlagSet<FieldModifier> getModifiers() { return effectiveModifiers; } public void setEffectiveModifiers(FlagSet<FieldModifier> effectiveModifiers) { this.effectiveModifiers = effectiveModifiers; } // public void addModifiers(long modifiers) { // setModifiers(getModifiers() | modifiers); // } // // public void removeModifiers(long modifiers) { // setModifiers(getModifiers() & ~modifiers); // } // public Expression getExpression() { // return formula == null ? null : formula.getExpression(); // } @Override public boolean equals(Object other) { return !(other == null || !(other instanceof Field)) && compareTo(other) == 0; } public int compareTo(Object other) { if (other == this) { return 0; } if (other == null) { return 1; } Field f = (Field) other; NamingStrategy comp = NamingStrategyHelper.getNamingStrategy(getEntity().getPersistenceUnit().isCaseSensitiveIdentifiers()); String s1 = entity != null ? comp.getUniformValue(entity.getName()) : ""; String s2 = f.getName() != null ? comp.getUniformValue(f.getEntity().getName()) : ""; int i = s1.compareTo(s2); if (i != 0) { return i; } else { String s3 = getName() != null ? comp.getUniformValue(getName()) : ""; String s4 = f.getName() != null ? comp.getUniformValue(f.getName()) : ""; i = s3.compareTo(s4); return i; } } @Override public FlagSet<UserFieldModifier> getUserModifiers() { return userModifiers; } // public void resetModifiers() { // modifiers = 0; // } public void setUserModifiers(FlagSet<UserFieldModifier> modifiers) { this.userModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public FlagSet<UserFieldModifier> getUserExcludeModifiers() { return userExcludeModifiers; } public void setUserExcludeModifiers(FlagSet<UserFieldModifier> modifiers) { this.userExcludeModifiers = modifiers == null ? FlagSets.noneOf(UserFieldModifier.class) : modifiers; } @Override public String toString() { return getAbsoluteName(); } @Override public void close() throws UPAException { this.closed = true; } public boolean isClosed() { return closed; } @Override public Object getUnspecifiedValue() { return unspecifiedValue; } @Override public void setUnspecifiedValue(Object o) { this.unspecifiedValue = o; } public Object getUnspecifiedValueDecoded() { final Object fuv = getUnspecifiedValue(); if (UnspecifiedValue.DEFAULT.equals(fuv)) { return getDataType().getDefaultUnspecifiedValue(); } else { return fuv; } } public boolean isUnspecifiedValue(Object value) { Object v = getUnspecifiedValueDecoded(); return (v == value || (v != null && v.equals(value))); } public AccessLevel getPersistAccessLevel() { return persistAccessLevel; } public void setPersistAccessLevel(AccessLevel persistAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, persistAccessLevel)) { persistAccessLevel = AccessLevel.READ_WRITE; } this.persistAccessLevel = persistAccessLevel; } public AccessLevel getUpdateAccessLevel() { return updateAccessLevel; } public void setUpdateAccessLevel(AccessLevel updateAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, updateAccessLevel)) { updateAccessLevel = AccessLevel.READ_WRITE; } this.updateAccessLevel = updateAccessLevel; } public AccessLevel getReadAccessLevel() { return readAccessLevel; } public void setReadAccessLevel(AccessLevel readAccessLevel) { if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, readAccessLevel)) { readAccessLevel = AccessLevel.READ_ONLY; } if (readAccessLevel == AccessLevel.READ_WRITE) { readAccessLevel = AccessLevel.READ_ONLY; } this.readAccessLevel = readAccessLevel; } public void setAccessLevel(AccessLevel accessLevel) { setPersistAccessLevel(accessLevel); setUpdateAccessLevel(accessLevel); setReadAccessLevel(accessLevel); } public ProtectionLevel getPersistProtectionLevel() { return persistProtectionLevel; } public void setPersistProtectionLevel(ProtectionLevel persistProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, persistProtectionLevel)) { persistProtectionLevel = ProtectionLevel.PUBLIC; } this.persistProtectionLevel = persistProtectionLevel; } public ProtectionLevel getUpdateProtectionLevel() { return updateProtectionLevel; } public void setUpdateProtectionLevel(ProtectionLevel updateProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, updateProtectionLevel)) { updateProtectionLevel = ProtectionLevel.PUBLIC; } this.updateProtectionLevel = updateProtectionLevel; } public ProtectionLevel getReadProtectionLevel() { return readProtectionLevel; } public void setReadProtectionLevel(ProtectionLevel readProtectionLevel) { if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, readProtectionLevel)) { readProtectionLevel = ProtectionLevel.PUBLIC; } this.readProtectionLevel = readProtectionLevel; } public void setProtectionLevel(ProtectionLevel persistLevel) { setPersistProtectionLevel(persistLevel); setUpdateProtectionLevel(persistLevel); setReadProtectionLevel(persistLevel); } public SearchOperator getSearchOperator() { return searchOperator; } public void setSearchOperator(SearchOperator searchOperator) { this.searchOperator = searchOperator; } public FieldPersister getFieldPersister() { return fieldPersister; } public void setFieldPersister(FieldPersister fieldPersister) { this.fieldPersister = fieldPersister; } public DataTypeTransform getTypeTransform() { return typeTransform; } @Override public DataTypeTransform getEffectiveTypeTransform() { DataTypeTransform t = getTypeTransform(); if (t == null) { DataType d = getDataType(); if (d != null) { t = new IdentityDataTypeTransform(d); } } return t; } public void setTypeTransform(DataTypeTransform transform) { this.typeTransform = transform; } public PropertyAccessType getPropertyAccessType() { return accessType; } public void setPropertyAccessType(PropertyAccessType accessType) { this.accessType = accessType; } @Override public Object getMainValue(Object instance) { Object v = getValue(instance); if (v != null) { Relationship manyToOneRelationship = getManyToOneRelationship(); if (manyToOneRelationship != null) { v = manyToOneRelationship.getTargetEntity().getBuilder().getMainValue(v); } } return v; } @Override public Object getValue(Object instance) { if (instance instanceof Document) { return ((Document) instance).getObject(getName()); } return getEntity().getBuilder().getProperty(instance, getName()); } @Override public void setValue(Object instance, Object value) { getEntity().getBuilder().setProperty(instance, getName(), value); } @Override public void check(Object value) { getDataType().check(value, getName(), null); } @Override public boolean isManyToOne() { return getDataType() instanceof ManyToOneType; } @Override public boolean isOneToOne() { return getDataType() instanceof OneToOneType; } @Override public ManyToOneRelationship getManyToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof ManyToOneType) { return (ManyToOneRelationship) ((ManyToOneType) dataType).getRelationship(); } return null; } @Override public OneToOneRelationship getOneToOneRelationship() { DataType dataType = getDataType(); if (dataType instanceof OneToOneType) { return (OneToOneRelationship) ((OneToOneType) dataType).getRelationship(); } return null; } protected void fillFieldInfo(FieldInfo i) { Field f = this; fillObjectInfo(i); DataTypeInfo dataType = f.getDataType() == null ? null : f.getDataType().getInfo(); if (dataType != null) { UPAI18n d = getPersistenceGroup().getI18nOrDefault(); if (f.getDataType() instanceof EnumType) { List<Object> values = ((EnumType) f.getDataType()).getValues(); StringBuilder v = new StringBuilder(); for (Object o : values) { if (v.length() > 0) { v.append(","); } v.append(d.getEnum(o)); } dataType.getProperties().put("titles", String.valueOf(v)); } } i.setDataType(dataType); i.setId(f.isId()); i.setGeneratedId(f.isGeneratedId()); i.setModifiers(f.getModifiers().toArray()); i.setPersistAccessLevel(f.getPersistAccessLevel()); i.setUpdateAccessLevel(f.getUpdateAccessLevel()); i.setReadAccessLevel(f.getReadAccessLevel()); i.setPersistProtectionLevel(f.getPersistProtectionLevel()); i.setUpdateProtectionLevel(f.getUpdateProtectionLevel()); i.setReadProtectionLevel(f.getReadProtectionLevel()); i.setEffectivePersistAccessLevel(f.getEffectivePersistAccessLevel()); i.setEffectiveUpdateAccessLevel(f.getEffectiveUpdateAccessLevel()); i.setEffectiveReadAccessLevel(f.getEffectiveReadAccessLevel()); i.setMain(f.isMain()); i.setSystem(f.getModifiers().contains(FieldModifier.SYSTEM)); i.setSummary(f.isSummary()); i.setManyToOne(f.isManyToOne()); i.setPropertyAccessType(f.getPropertyAccessType()); Relationship r = f.getManyToOneRelationship(); i.setManyToOneRelationship(r == null ? null : r.getName()); } @Override public AccessLevel getEffectiveAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getEffectiveReadAccessLevel(); case PERSIST: return getEffectivePersistAccessLevel(); case UPDATE: return getEffectiveUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public AccessLevel getAccessLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadAccessLevel(); case PERSIST: return getPersistAccessLevel(); case UPDATE: return getUpdateAccessLevel(); } } return AccessLevel.INACCESSIBLE; } @Override public ProtectionLevel getProtectionLevel(AccessMode mode) { if (!PlatformUtils.isUndefinedEnumValue(AccessMode.class, mode)) { switch (mode) { case READ: return getReadProtectionLevel(); case PERSIST: return getPersistProtectionLevel(); case UPDATE: return getUpdateProtectionLevel(); } } return ProtectionLevel.PRIVATE; } public AccessLevel getEffectivePersistAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getPersistAccessLevel(); ProtectionLevel pl = getPersistProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getPersistFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } break; } case PUBLIC: { break; } } break; } } if (al != AccessLevel.INACCESSIBLE) { if (isGeneratedId()) { al = AccessLevel.INACCESSIBLE; } if (!getModifiers().contains(FieldModifier.PERSIST_DEFAULT)) { al = AccessLevel.INACCESSIBLE; } } return al; } public AccessLevel getEffectiveUpdateAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getUpdateAccessLevel(); ProtectionLevel pl = getUpdateProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } boolean hasFormula = getUpdateFormula() != null; if (al == AccessLevel.READ_WRITE && hasFormula) { al = AccessLevel.READ_ONLY; } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } case READ_WRITE: { switch (pl) { case PRIVATE: { al = AccessLevel.READ_ONLY; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedWrite(this)) { al = AccessLevel.READ_ONLY; } if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } if (isId() && al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (getModifiers().contains(FieldModifier.UPDATE_DEFAULT)) { // } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } else if (getModifiers().contains(FieldModifier.PERSIST_FORMULA) || getModifiers().contains(FieldModifier.PERSIST_SEQUENCE)) { if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } } return al; } public AccessLevel getEffectiveReadAccessLevel() { if (isSystem()) { return AccessLevel.INACCESSIBLE; } AccessLevel al = getReadAccessLevel(); ProtectionLevel pl = getReadProtectionLevel(); if (PlatformUtils.isUndefinedEnumValue(AccessLevel.class, al)) { al = AccessLevel.READ_WRITE; } if (PlatformUtils.isUndefinedEnumValue(ProtectionLevel.class, pl)) { pl = ProtectionLevel.PUBLIC; } if (al == AccessLevel.READ_WRITE) { al = AccessLevel.READ_ONLY; } if (al == AccessLevel.READ_ONLY) { if (!getModifiers().contains(FieldModifier.SELECT)) { al = AccessLevel.INACCESSIBLE; } } switch (al) { case INACCESSIBLE: { break; } case READ_ONLY: { switch (pl) { case PRIVATE: { al = AccessLevel.INACCESSIBLE; break; } case PROTECTED: { if (!getPersistenceUnit().getSecurityManager().isAllowedRead(this)) { al = AccessLevel.INACCESSIBLE; } break; } case PUBLIC: { break; } } break; } } return al; } }
thevpc/upa
upa-impl-core/src/main/java/net/thevpc/upa/impl/AbstractField.java
Java
gpl-3.0
27,988
#include "../../VM/Handler/Opcode8030Handler.h" #include "../../VM/Script.h" namespace Falltergeist { namespace VM { namespace Handler { Opcode8030::Opcode8030(VM::Script *script, std::shared_ptr<ILogger> logger) : OpcodeHandler(script) { this->logger = std::move(logger); } void Opcode8030::_run() { logger->debug() << "[8030] [*] op_while(address, condition)" << std::endl; auto condition = _script->dataStack()->popLogical(); if (!condition) { _script->setProgramCounter(_script->dataStack()->popInteger()); } } } } }
falltergeist/falltergeist
src/VM/Handler/Opcode8030Handler.cpp
C++
gpl-3.0
731
<?php /** * Fired during plugin activation. * * This class defines all code necessary to run during the plugin's activation. * * @link https://wordpress.org/plugins/woocommerce-role-based-price/ * @package Role Based Price For WooCommerce * @subpackage Role Based Price For WooCommerce/core * @since 3.0 */ class WooCommerce_Role_Based_Price_Activator { public function __construct() { } /** * Short Description. (use period) * * Long Description. * * @since 1.0.0 */ public static function activate() { require_once( WC_RBP_INC . 'helpers/class-version-check.php' ); require_once( WC_RBP_INC . 'helpers/class-dependencies.php' ); if( WooCommerce_Role_Based_Price_Dependencies(WC_RBP_DEPEN) ) { WooCommerce_Role_Based_Price_Version_Check::activation_check('3.7'); $message = '<h3> <center> ' . __("Thank you for installing <strong>Role Based Price For WooCommerce</strong> : <strong>Version 3.0 </strong>", WC_RBP_TXT) . '</center> </h3>'; $message .= '<p>' . __("We have worked entire 1 year to improve our plugin to best of our ability and we hope you will enjoy working with it. We are always open for your sugestions and feature requests", WC_RBP_TXT) . '</p>'; $message .= '</hr>'; $message .= '<p>' . __("If you have installed <strong>WPRB</strong> for the 1st time or upgrading from <strong> Version 2.8.7</strong> then you will need to update its' settings once again or this plugin will not function properly. ", WC_RBP_TXT); $url = admin_url('admin.php?page=woocommerce-role-based-price-settings'); $message .= '<a href="' . $url . '" class="button button-primary">' . __("Click Here to update the settings", WC_RBP_TXT) . '</a> </p>'; wc_rbp_admin_update($message, 1, 'activate_message', array(), array( 'wraper' => FALSE, 'times' => 1 )); set_transient('_welcome_redirect_wcrbp', TRUE, 60); } else { if( is_plugin_active(WC_RBP_FILE) ) { deactivate_plugins(WC_RBP_FILE); } wp_die(wc_rbp_dependency_message()); } } }
technofreaky/WooCommerce-Role-Based-Price
includes/helpers/class-activator.php
PHP
gpl-3.0
2,218
<!-- jQuery --> <script src="<?php echo base_url('assets/frontend/js/jquery.js') ?>"></script> <!-- Bootstrap Core JavaScript --> <script src="<?php echo base_url('assets/frontend/js/bootstrap.min.js') ?>"></script> <!-- Contact Form JavaScript --> <!-- Do not edit these files! In order to set the email address and subject line for the contact form go to the bin/contact_me.php file. --> <script src="<?php echo base_url('assets/frontend/js/jqBootstrapValidation.js') ?>"></script> <script src="<?php echo base_url('assets/frontend/js/contact_me.js') ?>"></script> <script> $('.carousel').carousel({ interval: 5000 //changes the speed }) </script> <!-- DATA TABLE SCRIPTS --> <script src="<?php echo base_url('assets/backend/js/dataTables/jquery.dataTables.js') ?>"></script> <script src="<?php echo base_url('assets/backend/js/dataTables/dataTables.bootstrap.js') ?>"></script> <script> $(document).ready(function () { $('#dataTables-example').dataTable(); }); </script> <script type="text/javascript"> CKEDITOR.replace( 'editor1', { on: { instanceReady: function( ev ) { // Output paragraphs as <p>Text</p>. this.dataProcessor.writer.setRules( 'p', { indent: false, breakBeforeOpen: true, breakAfterOpen: false, breakBeforeClose: false, breakAfterClose: true }); } } });</script>
SisteminformasisekolahMANCibadak/Sistem-informasi-sekolah-menggunakan-framewok-codeigniter-dengan-sub-modul-akademik
aplikasi/SIA_mancib/application/views/portalv/js.php
PHP
gpl-3.0
1,548
<?php /* * bla-tinymce * Copyright (C) 2017 bestlife AG * info: oxid@bestlife.ag * * 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/> * * Marat Bedoev */ class blaTinyMceOxViewConfig extends blaTinyMceOxViewConfig_parent { public function loadTinyMce() { $cfg = oxRegistry::getConfig(); $blEnabled = in_array($this->getActiveClassName(), $cfg->getConfigParam("aTinyMCE_classes")); $blPlainCms = in_array($cfg->getActiveView()->getViewDataElement("edit")->oxcontents__oxloadid->value, $cfg->getConfigParam("aTinyMCE_plaincms")); $blFilemanager = $cfg->getConfigParam("blTinyMCE_filemanager"); if (!$blEnabled) return false; if ($blPlainCms) return oxRegistry::getLang()->translateString("BLA_TINYMCE_PLAINCMS"); // processing editor config & other stuff $sLang = oxRegistry::getLang()->getLanguageAbbr(oxRegistry::getLang()->getTplLanguage()); // array to assign shops lang abbreviations to lang file names of tinymce: shopLangAbbreviation => fileName (without .js ) $aLang = array( "cs" => "cs", "da" => "da", "de" => "de", "fr" => "fr_FR", "it" => "it", "nl" => "nl", "ru" => "ru" ); // default config $aDefaultConfig = array( 'force_br_newlines' => 'false', 'force_p_newlines' => 'false', 'forced_root_block' => '""', 'selector' => '"textarea:not(.mceNoEditor)"', 'language' => '"' . ( in_array($sLang, $aLang) ? $aLang[$sLang] : 'en' ) . '"', //'spellchecker_language' => '"' . (in_array($sLang, $aLang) ? $aLang[$sLang] : 'en') . '"', 'nowrap' => 'false', 'entity_encoding' => '"raw"', // http://www.tinymce.com/wiki.php/Configuration:entity_encoding 'height' => 300, 'menubar' => 'false', 'document_base_url' => '"' . $this->getBaseDir() . '"', // http://www.tinymce.com/wiki.php/Configuration:document_base_url 'relative_urls' => 'false', // http://www.tinymce.com/wiki.php/Configuration:relative_urls 'plugin_preview_width' => 'window.innerWidth', 'plugin_preview_height' => 'window.innerHeight-90', 'code_dialog_width' => 'window.innerWidth-50', 'code_dialog_height' => 'window.innerHeight-130', 'image_advtab' => 'true', 'imagetools_toolbar' => '"rotateleft rotateright | flipv fliph | editimage imageoptions"', 'moxiemanager_fullscreen' => 'true', 'insertdatetime_formats' => '[ "%d.%m.%Y", "%H:%M" ]', 'nonbreaking_force_tab' => 'true', // http://www.tinymce.com/wiki.php/Plugin:nonbreaking 'autoresize_max_height' => '400', 'urlconverter_callback' => '"urlconverter"', 'filemanager_access_key' => '"' . md5($_SERVER['DOCUMENT_ROOT']) . '"', 'tinymcehelper' => '"' . $this->getSelfActionLink() . 'renderPartial=1"' ); if ($blFilemanager) { $aDefaultConfig['external_filemanager_path'] = '"../modules/bla/bla-tinymce/fileman/"'; $aDefaultConfig['filemanager_access_key'] = '"' . md5($_SERVER['HTTP_HOST']) . '"'; $oUS = oxRegistry::get("oxUtilsServer"); $oUS->setOxCookie("filemanagerkey", md5($_SERVER['DOCUMENT_ROOT'] . $oUS->getOxCookie("admin_sid"))); } //merging with onfig override $aConfig = ( $aOverrideConfig = $this->_getTinyCustConfig() ) ? array_merge($aDefaultConfig, $aOverrideConfig) : $aDefaultConfig; // default plugins and their buttons $aDefaultPlugins = array( 'advlist' => '', // '' = plugin has no buttons 'anchor' => 'anchor', 'autolink' => '', 'autoresize' => '', 'charmap' => 'charmap', 'code' => 'code', 'colorpicker' => '', 'hr' => 'hr', 'image' => 'image', 'imagetools' => '', 'insertdatetime' => 'insertdatetime', 'link' => 'link unlink', 'lists' => '', 'media' => 'media', 'nonbreaking' => 'nonbreaking', 'pagebreak' => 'pagebreak', 'paste' => 'pastetext', 'preview' => 'preview', 'searchreplace' => 'searchreplace', 'table' => 'table', 'textcolor' => 'forecolor backcolor', 'visualblocks' => '', //'visualchars' => 'visualchars', 'wordcount' => '', 'oxfullscreen' => 'fullscreen', //custom fullscreen plugin //'oxwidget' => 'widget' //'oxgetseourl' => 'yolo' //custom seo url plugin // wip ); // plugins for newsletter emails if ($this->getActiveClassName() == "newsletter_main") { $aDefaultPlugins["legacyoutput"] = "false"; $aDefaultPlugins["fullpage"] = "fullpage"; } // override for active plugins $aOverridePlugins = $cfg->getConfigParam("aTinyMCE_plugins"); $aPlugins = ( empty( $aOverridePlugins ) || !is_array($aOverridePlugins) ) ? $aDefaultPlugins : array_merge($aDefaultPlugins, $aOverridePlugins); $aPlugins = array_filter($aPlugins, function ( $value ) { return $value !== "false"; }); // array keys von $aPlugins enthalten aktive plugins $aConfig['plugins'] = '"' . implode(' ', array_keys($aPlugins)) . '"'; // external plugins $aConfig['external_plugins'] = '{ "oxfullscreen":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxfullscreen/plugin.js') . '" '; //$aConfig['external_plugins'] .= ', "oxwidget":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxwidget/plugin.js') . '" '; if ($blFilemanager) $aConfig['external_plugins'] .= ',"roxy":"' . $this->getModuleUrl('bla-tinymce', 'plugins/roxy/plugin.js') . '" '; //$aConfig['external_plugins'] .= ',"oxgetseourl":"' . $this->getModuleUrl('bla-tinymce', 'plugins/oxgetseourl/plugin.js') . '" '; if ($aExtPlugins = $this->_getTinyExtPlugins()) { foreach ($aExtPlugins AS $plugin => $file) { $aConfig['external_plugins'] .= ', "' . $plugin . '": "' . $file . '" '; } } $aConfig['external_plugins'] .= ' }'; // default toolbar buttons $aDefaultButtons = array( "undo redo", "cut copy paste", "bold italic underline strikethrough", "alignleft aligncenter alignright alignjustify", "bullist numlist", "outdent indent", "blockquote", "subscript", "superscript", "formatselect", "removeformat", "fontselect", "fontsizeselect" ); $aOverrideButtons = oxRegistry::getConfig()->getConfigParam("aTinyMCE_buttons"); $aButtons = ( empty( $aOverrideButtons ) || !is_array($aOverrideButtons) ) ? $aDefaultButtons : $aOverrideButtons; // plugin buttons $aPluginButtons = array_filter($aPlugins); // zusätzliche buttons $aCustomButtons = $this->_getTinyToolbarControls(); $aButtons = array_merge(array_filter($aButtons), array_filter($aPluginButtons), array_filter($aCustomButtons)); $aConfig['toolbar'] = '"' . implode(" | ", $aButtons) . '"'; // compile the whole config stuff $sConfig = ''; foreach ($aConfig AS $param => $value) { $sConfig .= "$param: $value, "; } // add init script $sInit = 'tinymce.init({ ' . $sConfig . ' });'; $sCopyLongDescFromTinyMCE = 'function copyLongDescFromTinyMCE(sIdent) { var editor = tinymce.get("editor_"+sIdent); var content = (editor && !editor.isHidden()) ? editor.getContent() : document.getElementById("editor_"+sIdent).value; document.getElementsByName("editval[" + sIdent + "]").item(0).value = content.replace(/\[{([^\]]*?)}\]/g, function(m) { return m.replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&") }); return true; } var origCopyLongDesc = copyLongDesc; copyLongDesc = function(sIdent) { if ( copyLongDescFromTinyMCE( sIdent ) ) return; console.log("tinymce disabled, copy content from regular textarea"); origCopyLongDesc( sIdent ); }'; $sUrlConverter = 'function urlconverter(url, node, on_save) { console.log(tinyMCE.activeEditor); if(url.indexOf("[{") == 0) return url; return (tinyMCE.activeEditor.settings.relative_urls) ? tinyMCE.activeEditor.documentBaseURI.toRelative(url) : tinyMCE.activeEditor.documentBaseURI.toAbsolute(url); }'; // adding scripts to template $smarty = oxRegistry::get("oxUtilsView")->getSmarty(); $sSufix = ( $smarty->_tpl_vars["__oxid_include_dynamic"] ) ? '_dynamic' : ''; $aScript = (array)$cfg->getGlobalParameter('scripts' . $sSufix); $aScript[] = $sCopyLongDescFromTinyMCE; $aScript[] = $sUrlConverter; $aScript[] = $sInit; $cfg->setGlobalParameter('scripts' . $sSufix, $aScript); $aInclude = (array)$cfg->getGlobalParameter('includes' . $sSufix); $aExtjs = $cfg->getConfigParam('aTinyMCE_extjs'); if (!empty( $aExtjs ) && is_array($aExtjs)) foreach ($aExtjs as $key => $js) $aInclude[3][] = $js; $aInclude[3][] = $this->getModuleUrl('bla-tinymce', 'tinymce/tinymce.min.js'); $cfg->setGlobalParameter('includes' . $sSufix, $aInclude); return '<li style="margin-left: 50px;"><button style="border: 1px solid #0089EE; color: #0089EE;padding: 3px 10px; margin-top: -10px; background: white;" ' . 'onclick="tinymce.each(tinymce.editors, function(editor) { if(editor.isHidden()) { editor.show(); } else { editor.hide(); } });"><span>' . oxRegistry::getLang()->translateString('BLA_TINYMCE_TOGGLE') . '</span></button></li>'; // javascript:tinymce.execCommand(\'mceToggleEditor\',false,\'editor1\'); } protected function _getTinyToolbarControls() { $aControls = ( method_exists(get_parent_class(__CLASS__), __FUNCTION__) ) ? parent::_getTinyToolbarControls() : array(); return $aControls; } protected function _getTinyExtPlugins() { $aPlugins = oxRegistry::getConfig()->getConfigParam("aTinyMCE_external_plugins"); if (method_exists(get_parent_class(__CLASS__), __FUNCTION__)) { $aPlugins = array_merge(parent::_getTinyExtPlugins(), $aPlugins); } return $aPlugins; } protected function _getTinyCustConfig() { $aConfig = oxRegistry::getConfig()->getConfigParam("aTinyMCE_config"); if (method_exists(get_parent_class(__CLASS__), __FUNCTION__)) { $aConfig = array_merge(parent::_getTinyCustConfig(), $aConfig); } return $aConfig; } }
vanilla-thunder/bla-tinymce
copy_this/modules/bla/bla-tinymce/application/core/blatinymceoxviewconfig.php
PHP
gpl-3.0
11,435
/* * Copyright (C) 2016 Stuart Howarth <showarth@marxoft.co.uk> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 "independentfeedrequest.h" #include "independentarticlerequest.h" #include <QNetworkAccessManager> #include <QNetworkReply> #ifdef INDEPENDENT_DEBUG #include <QDebug> #endif const int IndependentFeedRequest::MAX_REDIRECTS = 8; const QString IndependentFeedRequest::BASE_URL("http://www.independent.co.uk"); const QString IndependentFeedRequest::ICON_URL("http://www.independent.co.uk/sites/all/themes/ines_themes/independent_theme/img/apple-icon-72x72.png"); const QByteArray IndependentFeedRequest::USER_AGENT("Wget/1.13.4 (linux-gnu)"); IndependentFeedRequest::IndependentFeedRequest(QObject *parent) : FeedRequest(parent), m_request(0), m_nam(0), m_status(Idle), m_results(0), m_redirects(0) { } QString IndependentFeedRequest::errorString() const { return m_errorString; } void IndependentFeedRequest::setErrorString(const QString &e) { m_errorString = e; #ifdef INDEPENDENT_DEBUG if (!e.isEmpty()) { qDebug() << "IndependentFeedRequest::error." << e; } #endif } QByteArray IndependentFeedRequest::result() const { return m_buffer.data(); } void IndependentFeedRequest::setResult(const QByteArray &r) { m_buffer.open(QBuffer::WriteOnly); m_buffer.write(r); m_buffer.close(); } FeedRequest::Status IndependentFeedRequest::status() const { return m_status; } void IndependentFeedRequest::setStatus(FeedRequest::Status s) { if (s != status()) { m_status = s; emit statusChanged(s); } } bool IndependentFeedRequest::cancel() { if (status() == Active) { if ((m_request) && (m_request->status() == ArticleRequest::Active)) { m_request->cancel(); } else { setStatus(Canceled); emit finished(this); } } return true; } bool IndependentFeedRequest::getFeed(const QVariantMap &settings) { if (status() == Active) { return false; } setStatus(Active); setResult(QByteArray()); setErrorString(QString()); m_settings = settings; m_results = 0; m_redirects = 0; QString url(BASE_URL); const QString section = m_settings.value("section").toString(); if (!section.isEmpty()) { url.append("/"); url.append(section); } url.append("/rss"); #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::getFeed(). URL:" << url; #endif QNetworkRequest request(url); request.setRawHeader("User-Agent", USER_AGENT); QNetworkReply *reply = networkAccessManager()->get(request); connect(reply, SIGNAL(finished()), this, SLOT(checkFeed())); connect(this, SIGNAL(finished(FeedRequest*)), reply, SLOT(deleteLater())); return true; } void IndependentFeedRequest::checkFeed() { QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); if (!reply) { setErrorString(tr("Network error")); setStatus(Error); emit finished(this); return; } const QString redirect = getRedirect(reply); if (!redirect.isEmpty()) { if (m_redirects < MAX_REDIRECTS) { reply->deleteLater(); followRedirect(redirect, SLOT(checkFeed())); } else { setErrorString(tr("Maximum redirects reached")); setStatus(Error); emit finished(this); } return; } switch (reply->error()) { case QNetworkReply::NoError: break; case QNetworkReply::OperationCanceledError: setStatus(Canceled); emit finished(this); return; default: setErrorString(reply->errorString()); setStatus(Error); emit finished(this); return; } m_parser.setContent(reply->readAll()); if (m_parser.readChannel()) { writeStartFeed(); writeFeedTitle(m_parser.title()); writeFeedUrl(m_parser.url()); const bool fetchFullArticle = m_settings.value("fetchFullArticle", true).toBool(); const QDateTime lastUpdated = m_settings.value("lastUpdated").toDateTime(); if (fetchFullArticle) { if (m_parser.readNextArticle()) { if (m_parser.date() > lastUpdated) { reply->deleteLater(); getArticle(m_parser.url()); } else { writeEndFeed(); setStatus(Ready); emit finished(this); } return; } writeEndFeed(); } else { const int max = m_settings.value("maxResults", 20).toInt(); while((m_results < max) && (m_parser.readNextArticle()) && (m_parser.date() > lastUpdated)) { ++m_results; writeStartItem(); writeItemAuthor(m_parser.author()); writeItemBody(m_parser.description()); writeItemCategories(m_parser.categories()); writeItemDate(m_parser.date()); writeItemEnclosures(m_parser.enclosures()); writeItemTitle(m_parser.title()); writeItemUrl(m_parser.url()); writeEndItem(); } writeEndFeed(); setStatus(Ready); emit finished(this); return; } } setErrorString(m_parser.errorString()); setStatus(Error); emit finished(this); } void IndependentFeedRequest::getArticle(const QString &url) { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::getArticle(). URL:" << url; #endif articleRequest()->getArticle(url, m_settings); } void IndependentFeedRequest::checkArticle(ArticleRequest *request) { if (request->status() == ArticleRequest::Canceled) { setStatus(Canceled); emit finished(this); return; } ++m_results; if (request->status() == ArticleRequest::Ready) { const ArticleResult article = request->result(); writeStartItem(); writeItemAuthor(article.author.isEmpty() ? m_parser.author() : article.author); writeItemBody(article.body.isEmpty() ? m_parser.description() : article.body); writeItemCategories(article.categories.isEmpty() ? m_parser.categories() : article.categories); writeItemDate(article.date.isNull() ? m_parser.date() : article.date); writeItemEnclosures(article.enclosures.isEmpty() ? m_parser.enclosures() : article.enclosures); writeItemTitle(article.title.isEmpty() ? m_parser.title() : article.title); writeItemUrl(article.url.isEmpty() ? m_parser.url() : article.url); writeEndItem(); } #ifdef INDEPENDENT_DEBUG else { qDebug() << "IndependentFeedRequest::checkArticle(). Error:" << request->errorString(); } #endif if ((m_results < m_settings.value("maxResults", 20).toInt()) && (m_parser.readNextArticle()) && (m_parser.date() > m_settings.value("lastUpdated").toDateTime())) { getArticle(m_parser.url()); return; } #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::checkArticle(). No more new articles"; #endif writeEndFeed(); setStatus(Ready); emit finished(this); } void IndependentFeedRequest::followRedirect(const QString &url, const char *slot) { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::followRedirect(). URL:" << url; #endif ++m_redirects; QNetworkRequest request(url); request.setRawHeader("User-Agent", USER_AGENT); QNetworkReply *reply = networkAccessManager()->get(request); connect(reply, SIGNAL(finished()), this, slot); connect(this, SIGNAL(finished(FeedRequest*)), reply, SLOT(deleteLater())); } QString IndependentFeedRequest::getRedirect(const QNetworkReply *reply) { QString redirect = QString::fromUtf8(reply->rawHeader("Location")); if ((!redirect.isEmpty()) && (!redirect.startsWith("http"))) { const QUrl url = reply->url(); if (redirect.startsWith("/")) { redirect.prepend(url.scheme() + "://" + url.authority()); } else { redirect.prepend(url.scheme() + "://" + url.authority() + "/"); } } return redirect; } void IndependentFeedRequest::writeStartFeed() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeStartFeed()"; #endif m_buffer.open(QBuffer::WriteOnly); m_writer.setDevice(&m_buffer); m_writer.writeStartDocument(); m_writer.writeStartElement("rss"); m_writer.writeAttribute("version", "2.0"); m_writer.writeAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/"); m_writer.writeAttribute("xmlns:content", "http://purl.org/rss/1.0/modules/content/"); m_writer.writeStartElement("channel"); m_writer.writeTextElement("description", tr("News articles from The Independent")); m_writer.writeStartElement("image"); m_writer.writeTextElement("url", ICON_URL); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeEndFeed() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeEndFeed()"; #endif m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeEndElement(); m_writer.writeEndElement(); m_writer.writeEndDocument(); m_buffer.close(); } void IndependentFeedRequest::writeFeedTitle(const QString &title) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("title"); m_writer.writeCDATA(title); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeFeedUrl(const QString &url) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("link", url); m_buffer.close(); } void IndependentFeedRequest::writeStartItem() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeStartItem(). Item" << m_results << "of" << m_settings.value("maxResults", 20).toInt(); #endif m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("item"); m_buffer.close(); } void IndependentFeedRequest::writeEndItem() { #ifdef INDEPENDENT_DEBUG qDebug() << "IndependentFeedRequest::writeEndItem(). Item" << m_results << "of" << m_settings.value("maxResults", 20).toInt(); #endif m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeItemAuthor(const QString &author) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("dc:creator", author); m_buffer.close(); } void IndependentFeedRequest::writeItemBody(const QString &body) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("content:encoded"); m_writer.writeCDATA(body); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeItemCategories(const QStringList &categories) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); foreach (const QString &category, categories) { m_writer.writeTextElement("category", category); } m_buffer.close(); } void IndependentFeedRequest::writeItemDate(const QDateTime &date) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("dc:date", date.toString(Qt::ISODate)); m_buffer.close(); } void IndependentFeedRequest::writeItemEnclosures(const QVariantList &enclosures) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); foreach (const QVariant &e, enclosures) { const QVariantMap enclosure = e.toMap(); m_writer.writeStartElement("enclosure"); m_writer.writeAttribute("url", enclosure.value("url").toString()); m_writer.writeAttribute("type", enclosure.value("type").toString()); m_writer.writeEndElement(); } m_buffer.close(); } void IndependentFeedRequest::writeItemTitle(const QString &title) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeStartElement("title"); m_writer.writeCDATA(title); m_writer.writeEndElement(); m_buffer.close(); } void IndependentFeedRequest::writeItemUrl(const QString &url) { m_buffer.open(QBuffer::WriteOnly | QBuffer::Append); m_writer.writeTextElement("link", url); m_buffer.close(); } IndependentArticleRequest* IndependentFeedRequest::articleRequest() { if (!m_request) { m_request = new IndependentArticleRequest(this); connect(m_request, SIGNAL(finished(ArticleRequest*)), this, SLOT(checkArticle(ArticleRequest*))); } return m_request; } QNetworkAccessManager* IndependentFeedRequest::networkAccessManager() { if (!m_nam) { m_nam = new QNetworkAccessManager(this); } return m_nam; }
marxoft/cutenews
plugins/independent/independentfeedrequest.cpp
C++
gpl-3.0
13,483
package com.dmtools.webapp.config; import com.dmtools.webapp.config.locale.AngularCookieLocaleResolver; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class LocaleConfiguration extends WebMvcConfigurerAdapter implements EnvironmentAware { @SuppressWarnings("unused") private RelaxedPropertyResolver propertyResolver; @Override public void setEnvironment(Environment environment) { this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.messages."); } @Bean(name = "localeResolver") public LocaleResolver localeResolver() { AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); return cookieLocaleResolver; } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("language"); registry.addInterceptor(localeChangeInterceptor); } }
jero-rodriguez/dmtools
src/main/java/com/dmtools/webapp/config/LocaleConfiguration.java
Java
gpl-3.0
1,616
/** * This class is generated by jOOQ */ package com.aviafix.db.generated.tables.pojos; import java.io.Serializable; import java.time.LocalDate; import javax.annotation.Generated; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class PAYBYCREDITCARDPROJECTION implements Serializable { private static final long serialVersionUID = 1444342293; private Integer ETID; private Integer CREDITCARDNUM; private LocalDate EXPDATE; private Integer CODE; private String CARDHOLDERNAME; private Double AMOUNT; public PAYBYCREDITCARDPROJECTION() {} public PAYBYCREDITCARDPROJECTION(PAYBYCREDITCARDPROJECTION value) { this.ETID = value.ETID; this.CREDITCARDNUM = value.CREDITCARDNUM; this.EXPDATE = value.EXPDATE; this.CODE = value.CODE; this.CARDHOLDERNAME = value.CARDHOLDERNAME; this.AMOUNT = value.AMOUNT; } public PAYBYCREDITCARDPROJECTION( Integer ETID, Integer CREDITCARDNUM, LocalDate EXPDATE, Integer CODE, String CARDHOLDERNAME, Double AMOUNT ) { this.ETID = ETID; this.CREDITCARDNUM = CREDITCARDNUM; this.EXPDATE = EXPDATE; this.CODE = CODE; this.CARDHOLDERNAME = CARDHOLDERNAME; this.AMOUNT = AMOUNT; } public Integer ETID() { return this.ETID; } public void ETID(Integer ETID) { this.ETID = ETID; } public Integer CREDITCARDNUM() { return this.CREDITCARDNUM; } public void CREDITCARDNUM(Integer CREDITCARDNUM) { this.CREDITCARDNUM = CREDITCARDNUM; } public LocalDate EXPDATE() { return this.EXPDATE; } public void EXPDATE(LocalDate EXPDATE) { this.EXPDATE = EXPDATE; } public Integer CODE() { return this.CODE; } public void CODE(Integer CODE) { this.CODE = CODE; } public String CARDHOLDERNAME() { return this.CARDHOLDERNAME; } public void CARDHOLDERNAME(String CARDHOLDERNAME) { this.CARDHOLDERNAME = CARDHOLDERNAME; } public Double AMOUNT() { return this.AMOUNT; } public void AMOUNT(Double AMOUNT) { this.AMOUNT = AMOUNT; } @Override public String toString() { StringBuilder sb = new StringBuilder("PAYBYCREDITCARDPROJECTION ("); sb.append(ETID); sb.append(", ").append(CREDITCARDNUM); sb.append(", ").append(EXPDATE); sb.append(", ").append(CODE); sb.append(", ").append(CARDHOLDERNAME); sb.append(", ").append(AMOUNT); sb.append(")"); return sb.toString(); } }
purple-sky/avia-fixers
app/src/main/java/com/aviafix/db/generated/tables/pojos/PAYBYCREDITCARDPROJECTION.java
Java
gpl-3.0
2,891
from test_support import * # this test calls a prover which is correctly configured but whose execution # gives an error (here: the prover executable doesn't exist). The intent is to # test the output of gnatprove in this specific case prove_all(prover=["plop"], opt=["--why3-conf=test.conf"])
ptroja/spark2014
testsuite/gnatprove/tests/N804-036__bad_prover/test.py
Python
gpl-3.0
296
import altConnect from 'higher-order-components/altConnect'; import { STATUS_OK } from 'app-constants'; import ItemStore from 'stores/ItemStore'; import ProgressBar from '../components/ProgressBar'; const mapStateToProps = ({ itemState }) => ({ progress: itemState.readingPercentage, hidden: itemState.status !== STATUS_OK, }); mapStateToProps.stores = { ItemStore }; export default altConnect(mapStateToProps)(ProgressBar); // WEBPACK FOOTER // // ./src/js/app/modules/item/containers/ProgressBarContainer.js
BramscoChill/BlendleParser
information/blendle-frontend-react-source/app/modules/item/containers/ProgressBarContainer.js
JavaScript
gpl-3.0
518
/* * Author: Bob Limnor (info@limnor.com) * Project: Limnor Studio * Item: Visual Programming Language Implement * License: GNU General Public License v3.0 */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using VPL; namespace LimnorDesigner { /// <summary> /// load primary types and Type into the treeview for selection for creating Attribute /// </summary> public partial class TypeSelector : UserControl { public Type SelectedType; IWindowsFormsEditorService _svc; public TypeSelector() { InitializeComponent(); } public void LoadAttributeParameterTypes(IWindowsFormsEditorService service, EnumWebRunAt runAt, Type initSelection) { _svc = service; treeView1.LoadAttributeParameterTypes(runAt, initSelection); treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect); treeView1.Click += new EventHandler(treeView1_Click); treeView1.KeyPress += new KeyPressEventHandler(treeView1_KeyPress); } void treeView1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)13) { if (_svc != null) { _svc.CloseDropDown(); } } } void treeView1_Click(object sender, EventArgs e) { if (_svc != null) { _svc.CloseDropDown(); } } void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { TreeNodeClassType tnct = e.Node as TreeNodeClassType; if (tnct != null) { SelectedType = tnct.OwnerDataType; } } public static Bitmap GetTypeImageByName(string name) { if (string.CompareOrdinal("Number", name) == 0) { return Resources._decimal; } if (string.CompareOrdinal("String", name) == 0) { return Resources.abc; } if (string.CompareOrdinal("Array", name) == 0) { return Resources._array.ToBitmap(); } if (string.CompareOrdinal("DateTime", name) == 0) { return Resources.date; } if (string.CompareOrdinal("TimeSpan", name) == 0) { return Resources.date; } return Resources._decimal; } public static TypeSelector GetAttributeParameterDialogue(IWindowsFormsEditorService service, EnumWebRunAt runAt, Type initSelection) { TypeSelector dlg = new TypeSelector(); dlg.LoadAttributeParameterTypes(service, runAt, initSelection); return dlg; } } }
Limnor/Limnor-Studio-Source-Code
Source/LimnorDesigner/TypeSelector.cs
C#
gpl-3.0
2,549
/* ComJail - A jail plugin for Minecraft servers Copyright (C) 2015 comdude2 (Matt Armer) 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/>. Contact: admin@mcviral.net */ package net.mcviral.dev.plugins.comjail.events; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.plugin.Plugin; import net.mcviral.dev.plugins.comjail.main.JailController; public class TeleportEvent implements Listener{ @SuppressWarnings("unused") private Plugin plugin; private JailController jailcontroller; public TeleportEvent(Plugin mplugin, JailController mjailcontroller){ plugin = mplugin; jailcontroller = mjailcontroller; } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerTeleport(PlayerTeleportEvent event){ if (jailcontroller.isJailed(event.getPlayer().getUniqueId())){ if (!event.getPlayer().hasPermission("jail.override")){ event.setCancelled(true); event.getPlayer().sendMessage("[" + ChatColor.BLUE + "GUARD" + ChatColor.WHITE + "] " + ChatColor.RED + "You are jailed, you may not teleport."); } } } }
comdude2/ComJail
src/net/mcviral/dev/plugins/comjail/events/TeleportEvent.java
Java
gpl-3.0
1,828
package se.solit.timeit.resources; import java.net.URI; import java.net.URISyntaxException; import javax.servlet.http.HttpSession; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; public class BaseResource { protected WebApplicationException redirect(String destination) throws URISyntaxException { URI uri = new URI(destination); Response response = Response.seeOther(uri).build(); return new WebApplicationException(response); } /** * Set message to show the message in the next shown View. * * @param session * @param message */ protected void setMessage(HttpSession session, String message) { session.setAttribute("message", message); } }
Hoglet/TimeIT-Server
src/main/java/se/solit/timeit/resources/BaseResource.java
Java
gpl-3.0
703
/* * This file is part of rasdaman community. * * Rasdaman community 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. * * Rasdaman community 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 rasdaman community. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2003 - 2010 Peter Baumann / rasdaman GmbH. * * For more information please see <http://www.rasdaman.org> * or contact Peter Baumann via <baumann@rasdaman.com>. */ package petascope.wcs2.handlers; import static petascope.wcs2.extensions.FormatExtension.MIME_XML; /** * Bean holding the response from executing a request operation. * * @author <a href="mailto:d.misev@jacobs-university.de">Dimitar Misev</a> */ public class Response { private final byte[] data; private final String xml; private final String mimeType; private final int exit_code; private static final int DEFAULT_CODE = 200; // constructrs public Response(byte[] data) { this(data, null, null, DEFAULT_CODE); } public Response(byte[] data, int code) { this(data, null, null, code); } public Response(String xml) { this(null, xml, null); //FormatExtension.MIME_GML); } public Response(String xml, int code) { this(null, xml, MIME_XML, code); } public Response(byte[] data, String xml, String mimeType) { this(data, xml, mimeType, DEFAULT_CODE); } public Response(byte[] data, String xml, String mimeType, int code) { this.data = data; this.xml = xml; this.mimeType = mimeType; this.exit_code = code; } // interface public byte[] getData() { return data; } public String getMimeType() { return mimeType; } public String getXml() { return xml; } public int getExitCode() { return exit_code; } }
miracee/rasdaman
applications/petascope/src/main/java/petascope/wcs2/handlers/Response.java
Java
gpl-3.0
2,322
function createCategorySlider(selector) { $(document).ready(function(){ var checkforloadedcats = []; var firstImage = $(selector).find('img').filter(':first'); if(firstImage.length > 0){ checkforloadedcats[selector] = setInterval(function() { var image = firstImage.get(0); if (image.complete || image.readyState == 'complete' || image.readyState == 4) { clearInterval(checkforloadedcats[selector]); $(selector).flexslider({ namespace: "", animation: "slide", easing: "easeInQuart", slideshow: false, animationLoop: false, animationSpeed: 700, pauseOnHover: true, controlNav: false, itemWidth: 238, minItems: flexmin, maxItems: flexmax, move: 0 }); } }, 20); } $(window).resize(function() { try { $(selector).flexslider(0); if($('#center_column').width()<=280){ $(selector).data('flexslider').setOpts({minItems: 1, maxItems: 1}); } else if($('#center_column').width()<=440){ $(selector).data('flexslider').setOpts({minItems: grid_size_ms, maxItems: grid_size_ms});} else if($('#center_column').width()<963){ $(selector).data('flexslider').setOpts({minItems: grid_size_sm, maxItems: grid_size_sm});} else if($('#center_column').width()>=1240){ $(selector).data('flexslider').setOpts({minItems: grid_size_lg, maxItems: grid_size_lg});} else if($('#center_column').width()>=963){ $(selector).data('flexslider').setOpts({minItems: grid_size_md, maxItems: grid_size_md});} } catch(e) { // handle all your exceptions here } }); }); }
desarrollosimagos/puroextremo.com.ve
modules/categoryslider/categoryslider.js
JavaScript
gpl-3.0
1,648
<?php /** * Skeleton subclass for performing query and update operations on the 'transaction' table. * * * * This class was autogenerated by Propel 1.4.2 on: * * Sun Jul 17 20:02:37 2011 * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package lib.model.basic */ class TransactionPeer extends BaseTransactionPeer { } // TransactionPeer
joseortega/finance
lib/model/basic/TransactionPeer.php
PHP
gpl-3.0
505
from itertools import combinations def is_good(n): return 1 + ((int(n) - 1) % 9) == 9 def generate_subsequences(n): subsequences = [] combinations_list = [] index = 4 #Generate all combinations while index > 0: combinations_list.append(list(combinations(str(n), index))) index -= 1 #Formatting combinations for index in combinations_list: for combination in index: subsequences.append(''.join(combination)) return subsequences if __name__ == '__main__': #The modulo modulo = ((10 ** 9) + 7) #Get number of cases cases = int(raw_input()) while cases > 0: value = raw_input() good_subsequences = 0 for sub in generate_subsequences(value): if is_good(sub): good_subsequences += 1 print (good_subsequences % modulo)-1 cases -= 1
Dawny33/Code
HackerEarth/BeCoder 2/nine.py
Python
gpl-3.0
882
package com.hacks.collegebarter.fragments; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hacks.collegebarter.R; import com.hacks.collegebarter.navdrawer.MainAppActivity; public class TradeboardFragment extends Fragment{ public static final String ARG_SECTION_NUMBER = "section_number"; // Following constructor public TradeboardFragment() { Bundle bundle = new Bundle(); bundle.putInt(ARG_SECTION_NUMBER, 0); this.setArguments(bundle); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.tradeboard_fragment, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainAppActivity) activity).onSectionAttached(getArguments().getInt( ARG_SECTION_NUMBER)); } }
ReggieSackey/CollegeBarter
CollegeBarter/src/com/hacks/collegebarter/fragments/TradeboardFragment.java
Java
gpl-3.0
1,009
# -*- coding: utf-8 -*- from pyload.plugin.internal.DeadCrypter import DeadCrypter class FiredriveCom(DeadCrypter): __name = "FiredriveCom" __type = "crypter" __version = "0.03" __pattern = r'https?://(?:www\.)?(firedrive|putlocker)\.com/share/.+' __config = [] #@TODO: Remove in 0.4.10 __description = """Firedrive.com folder decrypter plugin""" __license = "GPLv3" __authors = [("Walter Purcaro", "vuolter@gmail.com")]
ardi69/pyload-0.4.10
pyload/plugin/crypter/FiredriveCom.py
Python
gpl-3.0
474
package visualk.gallery.db; import java.awt.Color; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import visualk.db.MysqlLayer; import visualk.gallery.objects.Artist; import visualk.gallery.objects.Work; public class DbGallery extends MysqlLayer{ public DbGallery(String user, String pass, String db) { super(user, pass, db); } public void addObra(Work obra, Artist author) { if (this != null) { try { /*mySQL.executeDB("insert into hrzns (" + "nameHrz," + "dt," + "topHrz," + "topHrzColor," + "bottomHrzColor," + "canvasWidth," + "canvasHeigth," + "authorHrz," + "xPal," + "yPal," + "hPalx," + "hPaly," + "alcada," + "colPal," + "horizontal," + "aureaProp," + "superX," + "superY," + "textura," + "version) values ('" + hrz.getNameHrz() + "', " + "NOW()" + ", '" + hrz.getTopHrz() + "', '" + hrz.getTopHrzColor().getRGB() + "', '" + hrz.getBottomHrzColor().getRGB() + "', '" + hrz.getCanvasWidth() + "', '" + hrz.getCanvasHeigth() + "', '" + authorName + "', '" + hrz.getxPal() + "', '" + hrz.getyPal() + "', '" + hrz.gethPalx() + "', '" + hrz.gethPaly() + "', '" + hrz.getAlçada() + "', '" + hrz.getColPal().getRGB() + "', '" + hrz.isHorizontal() + "', '" + hrz.isAureaProp() + "', '" + hrz.getSuperX() + "', '" + hrz.getSuperY() + "', '" + hrz.isTextura() + "', '" + hrz.getVersion() + "')");*/ } catch (Exception e) { } finally { disconnect(); } } } public ResultSet listHrzns() { ResultSet myResult = null; try { myResult = queryDB("SELECT * FROM hrzns WHERE namehrz<>'wellcome' order by dt desc;"); } catch (SQLException ex) { Logger.getLogger(DbGallery.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(DbGallery.class.getName()).log(Level.SEVERE, null, ex); } return (myResult); } /* public Horizon getHrznBD(String name) { Horizon temp = new Horizon(name); ResultSet myResult; myResult = mySQL.queryDB("SELECT * FROM hrzns where nameHrz='" + name + "'"); temp.makeRandom(100, 300); if (myResult != null) { try { while (myResult.next()) { String nameHrz = ""; String topHrz = ""; String topHrzColor = ""; String bottomHrzColor = ""; String canvasWidth = ""; String canvasHeigth = ""; String authorHrz = ""; String xPal = ""; String yPal = ""; String hPalx = ""; String hPaly = ""; String alcada = ""; String horizontal = ""; String aureaProp = ""; String colPal = ""; String superX = ""; String superY = ""; String textura = ""; String version = ""; try { nameHrz = myResult.getString("nameHrz"); topHrz = myResult.getString("topHrz"); topHrzColor = myResult.getString("topHrzColor"); bottomHrzColor = myResult.getString("bottomHrzColor"); canvasWidth = myResult.getString("canvasWidth"); canvasHeigth = myResult.getString("canvasHeigth"); authorHrz = myResult.getString("authorHrz"); xPal = myResult.getString("xPal"); yPal = myResult.getString("yPal"); hPalx = myResult.getString("hPalx"); hPaly = myResult.getString("hPaly"); alcada = myResult.getString("alcada"); colPal = myResult.getString("colPal"); horizontal = myResult.getString("horizontal"); aureaProp = myResult.getString("aureaProp"); superX = myResult.getString("superX"); superY = myResult.getString("superY"); textura = myResult.getString("textura"); version = myResult.getString("version"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } temp.setNameHrz(nameHrz); temp.setTopHrz(Integer.parseInt(topHrz)); temp.setTopHrzColor(new Color(Integer.parseInt(topHrzColor))); temp.setBottomHrzColor(new Color(Integer.parseInt(bottomHrzColor))); temp.setCanvasWidth(Integer.parseInt(canvasWidth)); temp.setCanvasHeigth(Integer.parseInt(canvasHeigth)); temp.setAuthorHrz(authorHrz); temp.setxPal(Integer.parseInt(xPal)); temp.setyPal(Integer.parseInt(yPal)); temp.sethPalx(Integer.parseInt(hPalx)); temp.sethPaly(Integer.parseInt(hPaly)); temp.setAlcada(Integer.parseInt(alcada)); temp.setColPal(new Color(Integer.parseInt(colPal))); temp.setHorizontal(horizontal.equals("true")); temp.setAureaProp(aureaProp.equals("true")); temp.setSuperX(Integer.parseInt(superX)); temp.setSuperY(Integer.parseInt(superY)); temp.setTextura(textura.equals("true")); temp.setVersion(version); } myResult.close(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return (temp); } */ }
lamaken/visualk
src/java/visualk/gallery/db/DbGallery.java
Java
gpl-3.0
7,208
/** * Java Settlers - An online multiplayer version of the game Settlers of Catan * Copyright (C) 2003 Robert S. Thomas <thomas@infolab.northwestern.edu> * Portions of this file Copyright (C) 2014,2017,2020 Jeremy D Monin <jeremy@nand.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/>. * * The maintainer of this program can be reached at jsettlers@nand.net **/ package soc.message; /** * This reply from server means this client currently isn't allowed to connect. * * @author Robert S Thomas */ public class SOCRejectConnection extends SOCMessage { private static final long serialVersionUID = 100L; // last structural change v1.0.0 or earlier /** * Text message */ private String text; /** * Create a RejectConnection message. * * @param message the text message */ public SOCRejectConnection(String message) { messageType = REJECTCONNECTION; text = message; } /** * @return the text message */ public String getText() { return text; } /** * REJECTCONNECTION sep text * * @return the command String */ public String toCmd() { return toCmd(text); } /** * REJECTCONNECTION sep text * * @param tm the text message * @return the command string */ public static String toCmd(String tm) { return REJECTCONNECTION + sep + tm; } /** * Parse the command String into a RejectConnection message * * @param s the String to parse; will be directly used as {@link #getText()} without any parsing * @return a RejectConnection message */ public static SOCRejectConnection parseDataStr(String s) { return new SOCRejectConnection(s); } /** * @return a human readable form of the message */ public String toString() { return "SOCRejectConnection:" + text; } }
jdmonin/JSettlers2
src/main/java/soc/message/SOCRejectConnection.java
Java
gpl-3.0
2,564
(function (angular) { 'use strict'; var config = { githubApiUrl: 'https://api.github.com/', }; angular.module('myGithubApp').constant('config', config); })(angular);
PetrusStarken/MyGit
app/scripts/app-config.js
JavaScript
gpl-3.0
180
/* Copyright 2013-2017 Matt Tytel * * helm 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. * * helm 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 helm. If not, see <http://www.gnu.org/licenses/>. */ #include "fonts.h" Fonts::Fonts() { proportional_regular_ = Font(Typeface::createSystemTypefaceFor( BinaryData::RobotoRegular_ttf, BinaryData::RobotoRegular_ttfSize)); proportional_light_ = Font(Typeface::createSystemTypefaceFor( BinaryData::RobotoLight_ttf, BinaryData::RobotoLight_ttfSize)); monospace_ = Font(Typeface::createSystemTypefaceFor( BinaryData::DroidSansMono_ttf, BinaryData::DroidSansMono_ttfSize)); }
mtytel/helm
src/look_and_feel/fonts.cpp
C++
gpl-3.0
1,106
package org.codefx.jwos.file; import org.codefx.jwos.analysis.AnalysisPersistence; import org.codefx.jwos.artifact.AnalyzedArtifact; import org.codefx.jwos.artifact.CompletedArtifact; import org.codefx.jwos.artifact.DownloadedArtifact; import org.codefx.jwos.artifact.FailedArtifact; import org.codefx.jwos.artifact.FailedProject; import org.codefx.jwos.artifact.IdentifiesArtifact; import org.codefx.jwos.artifact.IdentifiesProject; import org.codefx.jwos.artifact.ProjectCoordinates; import org.codefx.jwos.artifact.ResolvedArtifact; import org.codefx.jwos.artifact.ResolvedProject; import org.codefx.jwos.file.persistence.PersistentAnalysis; import org.codefx.jwos.file.persistence.PersistentAnalyzedArtifact; import org.codefx.jwos.file.persistence.PersistentCompletedArtifact; import org.codefx.jwos.file.persistence.PersistentDownloadedArtifact; import org.codefx.jwos.file.persistence.PersistentFailedArtifact; import org.codefx.jwos.file.persistence.PersistentFailedProject; import org.codefx.jwos.file.persistence.PersistentProjectCoordinates; import org.codefx.jwos.file.persistence.PersistentResolvedArtifact; import org.codefx.jwos.file.persistence.PersistentResolvedProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Collection; import java.util.SortedSet; import java.util.concurrent.ConcurrentSkipListSet; import java.util.function.Function; import static java.util.Collections.unmodifiableSet; import static org.codefx.jwos.Util.transformToList; /** * An {@link AnalysisPersistence} that uses YAML to store results. * <p> * This implementation is not thread-safe. */ public class YamlAnalysisPersistence implements AnalysisPersistence { private static final Logger LOGGER = LoggerFactory.getLogger("Persistence"); private static final YamlPersister PERSISTER = new YamlPersister(); private final SortedSet<ProjectCoordinates> projects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<ResolvedProject> resolvedProjects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<FailedProject> resolutionFailedProjects = new ConcurrentSkipListSet<>(IdentifiesProject.alphabeticalOrder()); private final SortedSet<DownloadedArtifact> downloadedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> downloadFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<AnalyzedArtifact> analyzedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> analysisFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<ResolvedArtifact> resolvedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<FailedArtifact> resolutionFailedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); private final SortedSet<CompletedArtifact> completedArtifacts = new ConcurrentSkipListSet<>(IdentifiesArtifact.alphabeticalOrder()); // CREATION & PERSISTENCE private YamlAnalysisPersistence() { // private constructor to enforce use of static factory methods } public static YamlAnalysisPersistence empty() { return new YamlAnalysisPersistence(); } public static YamlAnalysisPersistence fromString(String yamlString) { if (yamlString.isEmpty()) return empty(); PersistentAnalysis persistent = PERSISTER.read(yamlString, PersistentAnalysis.class); return from(persistent); } public static YamlAnalysisPersistence fromStream(InputStream yamlStream) { LOGGER.debug("Parsing result file..."); PersistentAnalysis persistent = PERSISTER.read(yamlStream, PersistentAnalysis.class); if (persistent == null) return new YamlAnalysisPersistence(); else return from(persistent); } private static YamlAnalysisPersistence from(PersistentAnalysis persistent) { YamlAnalysisPersistence yaml = new YamlAnalysisPersistence(); addTo(persistent.step_1_projects, PersistentProjectCoordinates::toProject, yaml.projects); addTo(persistent.step_2_resolvedProjects, PersistentResolvedProject::toProject, yaml.resolvedProjects); addTo(persistent.step_2_resolutionFailedProjects, PersistentFailedProject::toProject, yaml.resolutionFailedProjects); addTo(persistent.step_3_downloadedArtifacts, PersistentDownloadedArtifact::toArtifact, yaml.downloadedArtifacts); addTo(persistent.step_3_downloadFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.downloadFailedArtifacts); addTo(persistent.step_4_analyzedArtifacts, PersistentAnalyzedArtifact::toArtifact, yaml.analyzedArtifacts); addTo(persistent.step_4_analysisFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.analysisFailedArtifacts); addTo(persistent.step_5_resolvedArtifacts, PersistentResolvedArtifact::toArtifact, yaml.resolvedArtifacts); addTo(persistent.step_5_resolutionFailedArtifacts, PersistentFailedArtifact::toArtifact, yaml.resolutionFailedArtifacts); PersistentCompletedArtifact .toArtifacts(persistent.step_6_completedArtifacts.stream()) .forEach(yaml.completedArtifacts::add); return yaml; } private static <P, T> void addTo(Collection<P> source, Function<P, T> transform, Collection<T> target) { source.stream() .map(transform) .forEach(target::add); } public String toYaml() { PersistentAnalysis persistent = toPersistentAnalysis(); return PERSISTER.write(persistent); } private PersistentAnalysis toPersistentAnalysis() { PersistentAnalysis persistent = new PersistentAnalysis(); persistent.step_1_projects = transformToList(projects, PersistentProjectCoordinates::from); persistent.step_2_resolvedProjects = transformToList(resolvedProjects, PersistentResolvedProject::from); persistent.step_2_resolutionFailedProjects = transformToList(resolutionFailedProjects, PersistentFailedProject::from); persistent.step_3_downloadedArtifacts = transformToList(downloadedArtifacts, PersistentDownloadedArtifact::from); persistent.step_3_downloadFailedArtifacts = transformToList(downloadFailedArtifacts, PersistentFailedArtifact::from); persistent.step_4_analyzedArtifacts = transformToList(analyzedArtifacts, PersistentAnalyzedArtifact::from); persistent.step_4_analysisFailedArtifacts = transformToList(analysisFailedArtifacts, PersistentFailedArtifact::from); persistent.step_5_resolvedArtifacts = transformToList(resolvedArtifacts, PersistentResolvedArtifact::from); persistent.step_5_resolutionFailedArtifacts = transformToList(resolutionFailedArtifacts, PersistentFailedArtifact::from); persistent.step_6_completedArtifacts = transformToList(completedArtifacts, PersistentCompletedArtifact::from); return persistent; } // IMPLEMENTATION OF 'AnalysisPersistence' @Override public Collection<ProjectCoordinates> projectsUnmodifiable() { return unmodifiableSet(projects); } @Override public Collection<ResolvedProject> resolvedProjectsUnmodifiable() { return unmodifiableSet(resolvedProjects); } @Override public Collection<FailedProject> projectResolutionErrorsUnmodifiable() { return unmodifiableSet(resolutionFailedProjects); } @Override public Collection<DownloadedArtifact> downloadedArtifactsUnmodifiable() { return unmodifiableSet(downloadedArtifacts); } @Override public Collection<FailedArtifact> artifactDownloadErrorsUnmodifiable() { return unmodifiableSet(downloadFailedArtifacts); } @Override public Collection<AnalyzedArtifact> analyzedArtifactsUnmodifiable() { return unmodifiableSet(analyzedArtifacts); } @Override public Collection<FailedArtifact> artifactAnalysisErrorsUnmodifiable() { return unmodifiableSet(analysisFailedArtifacts); } @Override public Collection<ResolvedArtifact> resolvedArtifactsUnmodifiable() { return unmodifiableSet(resolvedArtifacts); } @Override public Collection<FailedArtifact> artifactResolutionErrorsUnmodifiable() { return unmodifiableSet(resolutionFailedArtifacts); } @Override public void addProject(ProjectCoordinates project) { projects.add(project); } @Override public void addResolvedProject(ResolvedProject project) { resolvedProjects.add(project); } @Override public void addProjectResolutionError(FailedProject project) { resolutionFailedProjects.add(project); } @Override public void addDownloadedArtifact(DownloadedArtifact artifact) { downloadedArtifacts.add(artifact); } @Override public void addDownloadError(FailedArtifact artifact) { downloadFailedArtifacts.add(artifact); } @Override public void addAnalyzedArtifact(AnalyzedArtifact artifact) { analyzedArtifacts.add(artifact); } @Override public void addAnalysisError(FailedArtifact artifact) { analysisFailedArtifacts.add(artifact); } @Override public void addResolvedArtifact(ResolvedArtifact artifact) { resolvedArtifacts.add(artifact); } @Override public void addArtifactResolutionError(FailedArtifact artifact) { resolutionFailedArtifacts.add(artifact); } @Override public void addResult(CompletedArtifact artifact) { completedArtifacts.add(artifact); } }
CodeFX-org/jdeps-wall-of-shame
src/main/java/org/codefx/jwos/file/YamlAnalysisPersistence.java
Java
gpl-3.0
9,278
package Calibradores; import java.io.File; import Metricas.MultiescalaConBorde; import Modelo.UrbanizandoFrenos; public class TanteadorTopilejo extends Tanteador { UrbanizandoFrenos CA; public TanteadorTopilejo() { // int[] unConjuntoDeParametros = {1, 1, 1, 333, 333, 333, 1, 1, 444, 400, 400, 555}; // puntoDeTanteo = new PuntoDeBusqueda(unConjuntoDeParametros); // puntoDelRecuerdo = new PuntoDeBusqueda(unConjuntoDeParametros); CA = new UrbanizandoFrenos(72, 56, 11, 4); CA.setInitialGrid(new File ("Topilejo/topi1995.txt")); CA.setBosque(new File ("Topilejo/bosqueb.txt")); CA.setDistVias(new File ("Topilejo/distancia1.txt")); CA.setPendiente(new File ("Topilejo/pendiente.txt")); CA.setGoalGrid(new File ("Topilejo/topi1999.txt")); infoADN = CA.infoADN; MultiescalaConBorde metrica = new MultiescalaConBorde(CA.gridMeta, CA.numeroDeCeldasX, CA.numeroDeCeldasY ); metrica.normalizateConEste(new File ("Topilejo/topi1995.txt")); CA.setMetric(metrica); CA.setIteraciones(4); puntoDeTanteo = new PuntoDeBusqueda(infoADN.size); puntoDelRecuerdo = new PuntoDeBusqueda(infoADN.size); vuelo = new PuntoDeBusqueda(infoADN.size); bajando = new Ventana("Guardar Acercamiento", "Caminante Siego Estocastico"); bajando.setVisible(true); bajando.graf.setLocation(850, 715); bajando.setQueTantoLocation(865, 650); //solo para correr los 3 calibradores al mismo tiempo // ventana = new Ventana("Guardar Todo", "Todos"); // ventana.setVisible(true); pintaGrid1 = new PintaGrid(new File("Topilejo/topi1999.txt"), "Grrid Meta", 4); pintaGrid2 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Mejor Aproximacion", 5); pintaGrid3 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Grid de Salida", 4); pintaGrid2.setLocation(865, 370); } public double mide(int[] parametros) { return CA.mide(parametros, 100); } public static void main(String[] args) { TanteadorTopilejo topo = new TanteadorTopilejo(); topo.busca(); } @Override public int[][] unOutputPara(int[] parametros) { // TODO Auto-generated method stub return CA.unOutputPara(parametros); } }
sostenibilidad-unam/crecimiento-urbano
Calibradores/TanteadorTopilejo.java
Java
gpl-3.0
2,250
/* * Copyright (C) 2017 phantombot.tv * * 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 me.mast3rplan.phantombot.event.ytplayer; import me.mast3rplan.phantombot.twitchwsirc.Channel; import me.mast3rplan.phantombot.ytplayer.YTPlayerState; public class YTPlayerStateEvent extends YTPlayerEvent { private final YTPlayerState state; public YTPlayerStateEvent(YTPlayerState state) { this.state = state; } public YTPlayerStateEvent(YTPlayerState state, Channel channel) { super(channel); this.state = state; } public YTPlayerState getState() { return state; } public int getStateId() { return state.i; } }
MrAdder/PhantomBot
source/me/mast3rplan/phantombot/event/ytplayer/YTPlayerStateEvent.java
Java
gpl-3.0
1,295
package com.plasmablazer.tutorialmod.proxy; public interface IProxy { }
PlasmaBlazer/TutorialMod
src/main/java/com/plasmablazer/tutorialmod/proxy/IProxy.java
Java
gpl-3.0
74
using System; namespace org.btg.Star.Rhapsody { public struct SkeletalPoint { public int x { get; set; } public int y { get; set; } public int z { get; set; } public SkeletalPointType type { get; set; } } }
chrisatkin/star
Rhapsody/SkeletalPoint.cs
C#
gpl-3.0
447
package org.thoughtcrime.securesms.jobs; import androidx.annotation.NonNull; import org.thoughtcrime.securesms.dependencies.ApplicationDependencies; import org.thoughtcrime.securesms.jobmanager.Data; import org.thoughtcrime.securesms.jobmanager.Job; import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint; import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.crypto.UnidentifiedAccessUtil; import org.thoughtcrime.securesms.database.IdentityDatabase.VerifiedStatus; import org.thoughtcrime.securesms.recipients.RecipientId; import org.thoughtcrime.securesms.recipients.RecipientUtil; import org.thoughtcrime.securesms.util.Base64; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.libsignal.IdentityKey; import org.whispersystems.libsignal.InvalidKeyException; import org.whispersystems.signalservice.api.SignalServiceMessageSender; import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException; import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage; import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage; import org.whispersystems.signalservice.api.push.SignalServiceAddress; import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException; import java.io.IOException; import java.util.concurrent.TimeUnit; public class MultiDeviceVerifiedUpdateJob extends BaseJob { public static final String KEY = "MultiDeviceVerifiedUpdateJob"; private static final String TAG = MultiDeviceVerifiedUpdateJob.class.getSimpleName(); private static final String KEY_DESTINATION = "destination"; private static final String KEY_IDENTITY_KEY = "identity_key"; private static final String KEY_VERIFIED_STATUS = "verified_status"; private static final String KEY_TIMESTAMP = "timestamp"; private RecipientId destination; private byte[] identityKey; private VerifiedStatus verifiedStatus; private long timestamp; public MultiDeviceVerifiedUpdateJob(@NonNull RecipientId destination, IdentityKey identityKey, VerifiedStatus verifiedStatus) { this(new Job.Parameters.Builder() .addConstraint(NetworkConstraint.KEY) .setQueue("__MULTI_DEVICE_VERIFIED_UPDATE__") .setLifespan(TimeUnit.DAYS.toMillis(1)) .setMaxAttempts(Parameters.UNLIMITED) .build(), destination, identityKey.serialize(), verifiedStatus, System.currentTimeMillis()); } private MultiDeviceVerifiedUpdateJob(@NonNull Job.Parameters parameters, @NonNull RecipientId destination, @NonNull byte[] identityKey, @NonNull VerifiedStatus verifiedStatus, long timestamp) { super(parameters); this.destination = destination; this.identityKey = identityKey; this.verifiedStatus = verifiedStatus; this.timestamp = timestamp; } @Override public @NonNull Data serialize() { return new Data.Builder().putString(KEY_DESTINATION, destination.serialize()) .putString(KEY_IDENTITY_KEY, Base64.encodeBytes(identityKey)) .putInt(KEY_VERIFIED_STATUS, verifiedStatus.toInt()) .putLong(KEY_TIMESTAMP, timestamp) .build(); } @Override public @NonNull String getFactoryKey() { return KEY; } @Override public void onRun() throws IOException, UntrustedIdentityException { try { if (!TextSecurePreferences.isMultiDevice(context)) { Log.i(TAG, "Not multi device..."); return; } if (destination == null) { Log.w(TAG, "No destination..."); return; } SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender(); Recipient recipient = Recipient.resolved(destination); VerifiedMessage.VerifiedState verifiedState = getVerifiedState(verifiedStatus); SignalServiceAddress verifiedAddress = RecipientUtil.toSignalServiceAddress(context, recipient); VerifiedMessage verifiedMessage = new VerifiedMessage(verifiedAddress, new IdentityKey(identityKey, 0), verifiedState, timestamp); messageSender.sendMessage(SignalServiceSyncMessage.forVerified(verifiedMessage), UnidentifiedAccessUtil.getAccessFor(context, recipient)); } catch (InvalidKeyException e) { throw new IOException(e); } } private VerifiedMessage.VerifiedState getVerifiedState(VerifiedStatus status) { VerifiedMessage.VerifiedState verifiedState; switch (status) { case DEFAULT: verifiedState = VerifiedMessage.VerifiedState.DEFAULT; break; case VERIFIED: verifiedState = VerifiedMessage.VerifiedState.VERIFIED; break; case UNVERIFIED: verifiedState = VerifiedMessage.VerifiedState.UNVERIFIED; break; default: throw new AssertionError("Unknown status: " + verifiedStatus); } return verifiedState; } @Override public boolean onShouldRetry(@NonNull Exception exception) { return exception instanceof PushNetworkException; } @Override public void onFailure() { } public static final class Factory implements Job.Factory<MultiDeviceVerifiedUpdateJob> { @Override public @NonNull MultiDeviceVerifiedUpdateJob create(@NonNull Parameters parameters, @NonNull Data data) { try { RecipientId destination = RecipientId.from(data.getString(KEY_DESTINATION)); VerifiedStatus verifiedStatus = VerifiedStatus.forState(data.getInt(KEY_VERIFIED_STATUS)); long timestamp = data.getLong(KEY_TIMESTAMP); byte[] identityKey = Base64.decode(data.getString(KEY_IDENTITY_KEY)); return new MultiDeviceVerifiedUpdateJob(parameters, destination, identityKey, verifiedStatus, timestamp); } catch (IOException e) { throw new AssertionError(e); } } } }
WhisperSystems/TextSecure
app/src/main/java/org/thoughtcrime/securesms/jobs/MultiDeviceVerifiedUpdateJob.java
Java
gpl-3.0
6,361
require_relative '../../spec_helper' describe TypedRb::TypeSignature::Parser do it 'parses a unit type' do result = described_class.parse('unit') expect(result).to eq(:unit) end it 'parses an atomic type' do result = described_class.parse('Bool') expect(result).to eq('Bool') end it 'parses a generic type' do result = described_class.parse('Array[Bool]') expect(result).to eq({:type => 'Array', :parameters => [{:type => 'Bool', :kind => :type_var}], :kind => :generic_type}) end it 'parses a nested generic type' do result = described_class.parse('Array[Array[Integer]]') expect(result).to eq({:type=>'Array', :parameters => [ {:type=>'Array', :parameters => [{ :type => 'Integer', :kind => :type_var }], :kind => :generic_type } ], :kind => :generic_type}) end it 'parses a nested generic type with multiple type arguments' do result = described_class.parse('Array[Hash[Symbol][String]]') expect(result).to eq({:type=>'Array', :parameters => [ {:type=>'Hash', :parameters => [{ :type => 'Symbol', :kind => :type_var }, { :type => 'String', :kind => :type_var }], :kind => :generic_type } ], :kind => :generic_type}) end it 'parses an atomic rest type' do result = described_class.parse('Bool...') expect(result).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) end it 'parses a type var rest type' do result = described_class.parse('[T]...') expect(result).to eq({:type => 'Array', :parameters => [{:type=>"T", :kind => :type_var}], :kind => :rest}) end it 'parses a function type' do result = described_class.parse('Bool -> Int') expect(result).to eq(['Bool', 'Int']) end it 'parses applied type parameters in signatures' do result = described_class.parse('Bool... -> Array[Bool]') expect(result[0]).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) expect(result[1]).to eq({:type => 'Array', :parameters => [{:type=>"Bool", :kind=>:type_var}], :kind => :generic_type}) end it 'parses applied type parameters in signatures' do result = described_class.parse('Bool... -> Array[T < Bool]') expect(result[0]).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) expect(result[1]).to eq({:type => 'Array', :parameters => [{:type =>"T", :kind =>:type_var, :bound => 'Bool', :binding => '<'}], :kind => :generic_type}) end it 'parses applied type parameters in signatures' do result = described_class.parse('Bool... -> Array[T > Bool]') expect(result[0]).to eq({:type => 'Array', :parameters => ['Bool'], :kind => :rest}) expect(result[1]).to eq({:type => 'Array', :parameters => [{:type =>"T", :kind =>:type_var, :bound => 'Bool', :binding => '>'}], :kind => :generic_type}) end it 'parses a complex type' do result = described_class.parse('Bool -> Int -> Bool') expect(result).to eq(['Bool', 'Int', 'Bool']) end it 'parses a complex type using unit' do result = described_class.parse('Bool -> Int -> unit') expect(result).to eq(['Bool', 'Int', :unit]) end it 'parses a types with parentheses' do result = described_class.parse('(Bool -> Int) -> Bool') expect(result).to eq([['Bool', 'Int'], 'Bool']) end it 'parses a types with parentheses in the return type' do result = described_class.parse('Bool -> (Int -> Bool)') expect(result).to eq(['Bool', ['Int', 'Bool']]) end it 'parses a types with parentheses in the complex return type' do result = described_class.parse('Bool -> (Int -> (Bool -> Int))') expect(result).to eq(['Bool', ['Int', ['Bool', 'Int']]]) end it 'parses a types with complex parentheses' do result = described_class.parse('(Bool -> Bool) -> (Bool -> Int)') expect(result).to eq([['Bool', 'Bool'], ['Bool', 'Int']]) end it 'parses a types with complex parentheses' do result = described_class.parse('(Bool -> Bool) -> (Bool -> Int) -> (Int -> Int)') expect(result).to eq([['Bool', 'Bool'], ['Bool', 'Int'], ['Int', 'Int']]) end it 'parses a types with complex compound parentheses' do result = described_class.parse('((Bool -> Bool) -> (Bool -> Int)) -> (Bool -> Int)') expect(result).to eq([[['Bool','Bool'], ['Bool', 'Int']], ['Bool', 'Int']]) end it 'parses unbalanced type expressions' do result = described_class.parse('Bool -> Int -> (Bool -> Int) -> Int') expect(result).to eq(['Bool','Int', ['Bool','Int'], 'Int']) end it 'parses unbalanced type expressions with just return types' do result = described_class.parse('Bool -> Int -> (-> Int) -> Int') expect(result).to eq(['Bool','Int', ['Int'], 'Int']) end it 'parses expressions with only return type' do result = described_class.parse(' -> Int') expect(result).to eq(['Int']) end it 'parses type variables' do result = described_class.parse('[X]') expect(result).to eq({:type => 'X', :kind => :type_var }) end it 'parses type variables with lower binding' do result = described_class.parse('[X < Numeric]') expect(result).to eq({:type => 'X', :kind => :type_var, :bound => 'Numeric', :binding => '<' }) end it 'parses type variables with lower binding' do result = described_class.parse('[X > Numeric]') expect(result).to eq({:type => 'X', :kind => :type_var, :bound => 'Numeric', :binding => '>' }) end it 'parses return type variables' do result = described_class.parse(' -> [X]') expect(result).to eq([{:type => 'X', :kind => :type_var }]) end it 'parses type variables in both sides' do result = described_class.parse('[X<String] -> [Y]') expect(result).to eq([{:type => 'X', :bound => 'String', :kind => :type_var, :binding => '<' }, {:type => 'Y', :kind => :type_var }]) end it 'parses type variables in complex expressions' do result = described_class.parse('[X] -> ([Y] -> Integer)') expect(result).to eq([{:type => 'X', :kind => :type_var }, [{:type => 'Y', :kind => :type_var }, 'Integer']]) end it 'parses a block' do result = described_class.parse('Int -> unit -> &(String -> Integer)') expect(result).to eq(['Int', :unit, {:block => ['String', 'Integer'], :kind => :block_arg}]) end it 'parses parametric types' do result = described_class.parse('Array[X] -> [X]') expect(result).to eq([{:type => "Array", :parameters => [{:type => "X", :kind => :type_var}], :kind => :generic_type}, {:type => "X", :kind => :type_var}]) end it 'parses parametric types with multiple var types' do result = described_class.parse('Int -> (Bool -> Array[X][Y][Z])') expect(result).to eq(["Int", ["Bool", {:type => "Array", :parameters => [{:type => "X", :kind => :type_var}, {:type => "Y", :kind => :type_var}, {:type => "Z", :kind => :type_var}], :kind => :generic_type}]]) end it 'parses parametric types with bounds' do result = described_class.parse('Array[X<Int] -> Hash[T<String][U<Object]') expect(result).to eq([{:type => "Array", :parameters => [{:type => "X", :bound => "Int", :binding => '<', :kind => :type_var}], :kind => :generic_type}, {:type => "Hash", :parameters => [{:type => "T", :bound => "String", :binding => '<', :kind => :type_var}, {:type => "U", :bound => "Object", :binding => '<', :kind => :type_var}], :kind => :generic_type}]) end it 'parses parametric rest arguments' do result = described_class.parse('Array[X]... -> String') expect(result).to eq([{:kind=>:rest, :type=>"Array", :parameters=>[{:type=>"Array", :parameters=>[{:type=>"X", :kind=>:type_var}], :kind=>:generic_type}]}, "String"]) end it 'parses multiple type variables in sequence' do result = described_class.parse('[X][Y][Z]') expect(result).to eq([{:type=>"X", :kind=>:type_var}, {:type=>"Y", :kind=>:type_var}, {:type=>"Z", :kind=>:type_var}]) end end
antoniogarrote/typed.rb
spec/lib/type_signature/parser_spec.rb
Ruby
gpl-3.0
9,936
import queue import logging import platform import threading import datetime as dt import serial import serial.threaded import serial_device from .or_event import OrEvent logger = logging.getLogger(__name__) # Flag to indicate whether queues should be polled. # XXX Note that polling performance may vary by platform. POLL_QUEUES = (platform.system() == 'Windows') class EventProtocol(serial.threaded.Protocol): def __init__(self): self.transport = None self.connected = threading.Event() self.disconnected = threading.Event() self.port = None def connection_made(self, transport): """Called when reader thread is started""" self.port = transport.serial.port logger.debug('connection_made: `%s` `%s`', self.port, transport) self.transport = transport self.connected.set() self.disconnected.clear() def data_received(self, data): """Called with snippets received from the serial port""" raise NotImplementedError def connection_lost(self, exception): """\ Called when the serial port is closed or the reader loop terminated otherwise. """ if isinstance(exception, Exception): logger.debug('Connection to port `%s` lost: %s', self.port, exception) else: logger.debug('Connection to port `%s` closed', self.port) self.connected.clear() self.disconnected.set() class KeepAliveReader(threading.Thread): ''' Keep a serial connection alive (as much as possible). Parameters ---------- state : dict State dictionary to share ``protocol`` object reference. comport : str Name of com port to connect to. default_timeout_s : float, optional Default time to wait for serial operation (e.g., connect). By default, block (i.e., no time out). **kwargs Keyword arguments passed to ``serial_for_url`` function, e.g., ``baudrate``, etc. ''' def __init__(self, protocol_class, comport, **kwargs): super(KeepAliveReader, self).__init__() self.daemon = True self.protocol_class = protocol_class self.comport = comport self.kwargs = kwargs self.protocol = None self.default_timeout_s = kwargs.pop('default_timeout_s', None) # Event to indicate serial connection has been established. self.connected = threading.Event() # Event to request a break from the run loop. self.close_request = threading.Event() # Event to indicate thread has been closed. self.closed = threading.Event() # Event to indicate an exception has occurred. self.error = threading.Event() # Event to indicate that the thread has connected to the specified port # **at least once**. self.has_connected = threading.Event() @property def alive(self): return not self.closed.is_set() def run(self): # Verify requested serial port is available. try: if self.comport not in (serial_device .comports(only_available=True).index): raise NameError('Port `%s` not available. Available ports: ' '`%s`' % (self.comport, ', '.join(serial_device.comports() .index))) except NameError as exception: self.error.exception = exception self.error.set() self.closed.set() return while True: # Wait for requested serial port to become available. while self.comport not in (serial_device .comports(only_available=True).index): # Assume serial port was disconnected temporarily. Wait and # periodically check again. self.close_request.wait(2) if self.close_request.is_set(): # No connection is open, so nothing to close. Just quit. self.closed.set() return try: # Try to open serial device and monitor connection status. logger.debug('Open `%s` and monitor connection status', self.comport) device = serial.serial_for_url(self.comport, **self.kwargs) except serial.SerialException as exception: self.error.exception = exception self.error.set() self.closed.set() return except Exception as exception: self.error.exception = exception self.error.set() self.closed.set() return else: with serial.threaded.ReaderThread(device, self .protocol_class) as protocol: self.protocol = protocol connected_event = OrEvent(protocol.connected, self.close_request) disconnected_event = OrEvent(protocol.disconnected, self.close_request) # Wait for connection. connected_event.wait(None if self.has_connected.is_set() else self.default_timeout_s) if self.close_request.is_set(): # Quit run loop. Serial connection will be closed by # `ReaderThread` context manager. self.closed.set() return self.connected.set() self.has_connected.set() # Wait for disconnection. disconnected_event.wait() if self.close_request.is_set(): # Quit run loop. self.closed.set() return self.connected.clear() # Loop to try to reconnect to serial device. def write(self, data, timeout_s=None): ''' Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum number of seconds to wait for serial connection to be established. By default, block until serial connection is ready. ''' self.connected.wait(timeout_s) self.protocol.transport.write(data) def request(self, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait (in seconds) for response. By default, block until response is ready. poll : bool, optional If ``True``, poll response queue in a busy loop until response is ready (or timeout occurs). Polling is much more processor intensive, but (at least on Windows) results in faster response processing. On Windows, polling is enabled by default. ''' self.connected.wait(timeout_s) return request(self, response_queue, payload, timeout_s=timeout_s, poll=poll) def close(self): self.close_request.set() # - - context manager, returns protocol def __enter__(self): """\ Enter context handler. May raise RuntimeError in case the connection could not be created. """ self.start() # Wait for protocol to connect. event = OrEvent(self.connected, self.closed) event.wait(self.default_timeout_s) return self def __exit__(self, *args): """Leave context: close port""" self.close() self.closed.wait() def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send payload to serial device and wait for response. Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait (in seconds) for response. By default, block until response is ready. poll : bool, optional If ``True``, poll response queue in a busy loop until response is ready (or timeout occurs). Polling is much more processor intensive, but (at least on Windows) results in faster response processing. On Windows, polling is enabled by default. ''' device.write(payload) if poll: # Polling enabled. Wait for response in busy loop. start = dt.datetime.now() while not response_queue.qsize(): if (dt.datetime.now() - start).total_seconds() > timeout_s: raise queue.Empty('No response received.') return response_queue.get() else: # Polling disabled. Use blocking `Queue.get()` method to wait for # response. return response_queue.get(timeout=timeout_s)
wheeler-microfluidics/serial_device
serial_device/threaded.py
Python
gpl-3.0
9,719
__author__ = "Harish Narayanan" __copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__ __license__ = "GNU GPL Version 3 or any later version" from cbc.twist import * from sys import argv """ DEMO - Twisting of a hyperelastic cube """ class Twist(StaticHyperelasticity): """ Definition of the hyperelastic problem """ def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression(("0.0", "0.0", "0.0")) twist = Expression(("0.0", "y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]", "z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]"), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = "x[0] == 0.0" right = "x[0] == 1.0" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression("x[0]*5.8 + (1 - x[0])*5.7") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): return "A hyperelastic cube twisted by 30 degrees solved by " + self.method # Setup the problem twist = Twist() twist.name_method("DISPLACEMENT BASED FORMULATION") # Solve the problem print twist twist.solve()
hnarayanan/twist
demo/static/twist.py
Python
gpl-3.0
2,606
#include "house2.h" int House2::objCount = 0; GImage *House2::image = nullptr; House2::House2(int x, int y) { posx = x; posy = y; width = 336; height = 366; if(!objCount) image = new GImage("./assets/house-a.gif",width,height,GImage::IS_TRANSPARENT,0); objCount++; if(Debug::debug_enable()) std::cout << "House2 " << objCount-1 << " created" << std::endl; } House2::~House2() { objCount--; if(!objCount) delete image; if(Debug::debug_enable()) std::cout << "House2 " << objCount << " destroyed" << std::endl; } bool House2::show(int x) { if(posx-x+width >= 0 && posx-x <= 800) { image->show(posx-x,posy); return 1; } return 0; }
Tai-Min/Projekt-Inf2-AiR
game elements/tiles/house2.cpp
C++
gpl-3.0
730
package com.silvermatch.advancedMod.block; import com.silvermatch.advancedMod.init.ModBlocks; import com.silvermatch.advancedMod.reference.Reference; import com.silvermatch.advancedMod.utility.Names; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.world.World; public class BlockFrenchFlag extends BlockAdvancedMod{ public BlockFrenchFlag() { setBlockName(Names.Blocks.FRENCH_FLAG); setBlockTextureName(Reference.MOD_ID_LOWER + ":" + Names.Blocks.FRENCH_FLAG); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ) { if (world.isAirBlock(x, y+1, z)){ world.setBlock(x, y+1, z, ModBlocks.frenchFlag); } return true; } }
SilverMatch/TutoMineMaarten
src/main/java/com/silvermatch/advancedMod/block/BlockFrenchFlag.java
Java
gpl-3.0
901
using System; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using EloBuddy; using LeagueSharp.Common; namespace ezEvade.SpecialSpells { class Darius : ChampionPlugin { static Darius() { // todo: fix for multiple darius' on same team (one for all) } public void LoadSpecialSpell(SpellData spellData) { if (spellData.spellName == "DariusCleave") { Game.OnUpdate += Game_OnUpdate; SpellDetector.OnProcessSpecialSpell += SpellDetector_OnProcessSpecialSpell; } } private void Game_OnUpdate(EventArgs args) { var darius = HeroManager.Enemies.FirstOrDefault(x => x.ChampionName == "Darius"); if (darius != null) { foreach (var spell in SpellDetector.detectedSpells.Where(x => x.Value.heroID == darius.NetworkId)) { spell.Value.startPos = darius.ServerPosition.To2D(); spell.Value.endPos = darius.ServerPosition.To2D() + spell.Value.direction * spell.Value.info.range; } } } private void SpellDetector_OnProcessSpecialSpell(Obj_AI_Base hero, GameObjectProcessSpellCastEventArgs args, SpellData spellData, SpecialSpellEventArgs specialSpellArgs) { if (spellData.spellName == "DariusCleave") { //SpellDetector.CreateSpellData(hero, start.To3D(), end.To3D(), spellData); } } } }
eliteironlix/portaio2
Core/Utility Ports/EzEvade/SpecialSpells/Darius.cs
C#
gpl-3.0
1,570
// Copyright (C) 1999-2021 // Smithsonian Astrophysical Observatory, Cambridge, MA, USA // For conditions of distribution and use, see copyright notice in "copyright" #include "basepolygon.h" #include "fitsimage.h" BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b) : Marker(p, ctr, 0) { } BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, ctr, 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { } BasePolygon::BasePolygon(Base* p, const List<Vertex>& v, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, Vector(0,0), 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { // Vertex list is in ref coords angle = 0; vertex = v; // find center center = Vector(0,0); vertex.head(); do center += vertex.current()->vector; while (vertex.next()); center /= vertex.count(); // vertices are relative vertex.head(); do vertex.current()->vector *= Translate(-center) * FlipY(); // no rotation while (vertex.next()); updateBBox(); } BasePolygon::BasePolygon(const BasePolygon& a) : Marker(a) { vertex = a.vertex; } void BasePolygon::createVertex(int which, const Vector& v) { // which segment (1 to n) // v is in ref coords Matrix mm = bckMatrix(); int seg = which-1; if (seg>=0 && seg<vertex.count()) { Vertex* n = new Vertex(v * mm); vertex.insert(seg,n); recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::deleteVertex(int h) { if (h>4) { int hh = h-4-1; if (vertex.count() > 3) { Vertex* v = vertex[hh]; if (v) { vertex.extractNext(v); delete v; recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } } void BasePolygon::edit(const Vector& v, int h) { if (h < 5) { Vector s1 = v * bckMatrix(); Vector s2 = bckMap(handle[h-1],Coord::CANVAS); if (s1[0] != 0 && s1[1] != 0 && s2[0] != 0 && s2[1] != 0) { double a = fabs(s1[0]/s2[0]); double b = fabs(s1[1]/s2[1]); double s = a > b ? a : b; vertex.head(); do vertex.current()->vector *= Scale(s); while (vertex.next()); } updateBBox(); doCallBack(CallBack::EDITCB); } else { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::moveVertex(const Vector& v, int h) { Matrix mm = bckMatrix(); if (vertex[h-5]) vertex.current()->vector = v * mm; recalcCenter(); } void BasePolygon::recalcCenter() { // recalculate center Vector nc; vertex.head(); do nc += vertex.current()->vector * Rotate(angle) * FlipY(); while (vertex.next()); nc /= vertex.count(); center += nc; // update all vertices vertex.head(); do vertex.current()->vector -= nc * FlipY() * Rotate(-angle); while (vertex.next()); } void BasePolygon::rotate(const Vector& v, int h) { if (h < 5) Marker::rotate(v,h); else { // we need to check this here, because we are really rotating if (canEdit()) { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } void BasePolygon::updateHandles() { // generate handles numHandle = 4 + vertex.count(); if (handle) delete [] handle; handle = new Vector[numHandle]; // the first four are our control handles BBox bb; vertex.head(); do bb.bound(vertex.current()->vector); while (vertex.next()); Vector zz = parent->zoom(); float r = 10/zz.length(); bb.expand(r); // give us more room handle[0] = fwdMap(bb.ll,Coord::CANVAS); handle[1] = fwdMap(bb.lr(),Coord::CANVAS); handle[2] = fwdMap(bb.ur,Coord::CANVAS); handle[3] = fwdMap(bb.ul(),Coord::CANVAS); // and the rest are vertices int i=4; vertex.head(); do handle[i++] = fwdMap(vertex.current()->vector,Coord::CANVAS); while (vertex.next()); } void BasePolygon::updateCoords(const Matrix& mx) { Scale s(mx); vertex.head(); do vertex.current()->vector *= s; while (vertex.next()); Marker::updateCoords(mx); } void BasePolygon::listBase(FitsImage* ptr, ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format) { Matrix mm = fwdMatrix(); str << type_ << '('; int first=1; vertex.head(); do { if (!first) str << ','; first=0; ptr->listFromRef(str,vertex.current()->vector*mm,sys,sky,format); } while (vertex.next()); str << ')'; }
SAOImageDS9/SAOImageDS9
tksao/frame/basepolygon.C
C++
gpl-3.0
4,927
package pg.autyzm.friendly_plans.manager_app.view.task_create; import android.app.FragmentTransaction; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import database.repository.StepTemplateRepository; import javax.inject.Inject; import database.entities.Asset; import database.entities.TaskTemplate; import database.repository.TaskTemplateRepository; import pg.autyzm.friendly_plans.ActivityProperties; import pg.autyzm.friendly_plans.App; import pg.autyzm.friendly_plans.AppComponent; import pg.autyzm.friendly_plans.R; import pg.autyzm.friendly_plans.asset.AssetType; import pg.autyzm.friendly_plans.databinding.FragmentTaskCreateBinding; import pg.autyzm.friendly_plans.manager_app.validation.TaskValidation; import pg.autyzm.friendly_plans.manager_app.validation.Utils; import pg.autyzm.friendly_plans.manager_app.validation.ValidationResult; import pg.autyzm.friendly_plans.manager_app.view.components.SoundComponent; import pg.autyzm.friendly_plans.manager_app.view.main_screen.MainActivity; import pg.autyzm.friendly_plans.manager_app.view.step_list.StepListFragment; import pg.autyzm.friendly_plans.manager_app.view.task_type_enum.TaskType; import pg.autyzm.friendly_plans.manager_app.view.view_fragment.CreateFragment; public class TaskCreateFragment extends CreateFragment implements TaskCreateActivityEvents { private static final String REGEX_TRIM_NAME = "_([\\d]*)(?=\\.)"; @Inject TaskValidation taskValidation; @Inject TaskTemplateRepository taskTemplateRepository; @Inject StepTemplateRepository stepTemplateRepository; private TextView labelTaskName; private EditText taskName; private EditText taskDurationTime; private Long taskId; private Integer typeId; private Button steps; private RadioGroup types; private TaskType taskType = TaskType.TASK; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FragmentTaskCreateBinding binding = DataBindingUtil.inflate( inflater, R.layout.fragment_task_create, container, false); binding.setEvents(this); View view = binding.getRoot(); ImageButton playSoundIcon = (ImageButton) view.findViewById(R.id.id_btn_play_sound); AppComponent appComponent = ((App) getActivity().getApplication()).getAppComponent(); soundComponent = SoundComponent.getSoundComponent( soundId, playSoundIcon, getActivity().getApplicationContext(), appComponent); appComponent.inject(this); binding.setSoundComponent(soundComponent); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { registerViews(view); view.post(new Runnable() { // Set assets only when the layout is completely built @Override public void run() { Bundle arguments = getArguments(); if (arguments != null) { Long taskId = (Long) arguments.get(ActivityProperties.TASK_ID); if (taskId != null) { initTaskForm(taskId); } } } }); } private void registerViews(View view) { labelTaskName = (TextView) view.findViewById(R.id.id_tv_task_name_label); Utils.markFieldMandatory(labelTaskName); taskName = (EditText) view.findViewById(R.id.id_et_task_name); pictureFileName = (EditText) view.findViewById(R.id.id_et_task_picture); soundFileName = (EditText) view.findViewById(R.id.id_et_task_sound); taskDurationTime = (EditText) view.findViewById(R.id.id_et_task_duration_time); picturePreview = (ImageView) view.findViewById(R.id.iv_picture_preview); clearSound = (ImageButton) view.findViewById(R.id.id_ib_clear_sound_btn); clearPicture = (ImageButton) view.findViewById(R.id.id_ib_clear_img_btn); steps = (Button) view.findViewById(R.id.id_btn_steps); types = (RadioGroup) view.findViewById(R.id.id_rg_types); RadioButton typeTask = (RadioButton) view.findViewById(R.id.id_rb_type_task); typeTask.setChecked(true); taskType = TaskType.TASK; } private Long saveOrUpdate() { soundComponent.stopActions(); try { if (taskId != null) { if (validateName(taskId, taskName) && validateDuration(taskDurationTime)) { typeId = taskType.getId(); Integer duration = getDuration(); clearSteps(typeId, taskId); taskTemplateRepository.update(taskId, taskName.getText().toString(), duration, pictureId, soundId, typeId); showToastMessage(R.string.task_saved_message); return taskId; } } else { if (validateName(taskName) && validateDuration(taskDurationTime)) { Integer duration = getDuration(); typeId = taskType.getId(); long taskId = taskTemplateRepository.create(taskName.getText().toString(), duration, pictureId, soundId, typeId); showToastMessage(R.string.task_saved_message); return taskId; } } } catch (RuntimeException exception) { Log.e("Task Create View", "Error saving task", exception); showToastMessage(R.string.save_task_error_message); } return null; } private void clearSteps(Integer typeId, Long taskId) { if (typeId != 1) { stepTemplateRepository.deleteAllStepsForTask(taskId); } } private boolean validateName(Long taskId, EditText taskName) { ValidationResult validationResult = taskValidation .isUpdateNameValid(taskId, taskName.getText().toString()); return handleInvalidResult(taskName, validationResult); } private boolean validateName(EditText taskName) { ValidationResult validationResult = taskValidation .isNewNameValid(taskName.getText().toString()); return handleInvalidResult(taskName, validationResult); } private boolean validateDuration(EditText duration) { ValidationResult validationResult = taskValidation .isDurationValid(duration.getText().toString()); return handleInvalidResult(duration, validationResult); } private void initTaskForm(long taskId) { this.taskId = taskId; TaskTemplate task = taskTemplateRepository.get(taskId); taskName.setText(task.getName()); if (task.getDurationTime() != null) { taskDurationTime.setText(String.valueOf(task.getDurationTime())); } Asset picture = task.getPicture(); Asset sound = task.getSound(); if (picture != null) { setAssetValue(AssetType.PICTURE, picture.getFilename(), picture.getId()); } if (sound != null) { setAssetValue(AssetType.SOUND, sound.getFilename(), sound.getId()); } typeId = task.getTypeId(); ((RadioButton) types.getChildAt(typeId - 1)).setChecked(true); setVisibilityStepButton(Integer.valueOf(task.getTypeId().toString())); } private void setVisibilityStepButton(int typeIdValue) { if (typeIdValue == 1) { steps.setVisibility(View.VISIBLE); } else { steps.setVisibility(View.INVISIBLE); } } private void showStepsList(final long taskId) { StepListFragment fragment = new StepListFragment(); Bundle args = new Bundle(); args.putLong(ActivityProperties.TASK_ID, taskId); fragment.setArguments(args); FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.replace(R.id.task_container, fragment); transaction.addToBackStack(null); transaction.commit(); } private void showMainMenu() { Intent intent = new Intent(getActivity(), MainActivity.class); startActivity(intent); } @Override protected void setAssetValue(AssetType assetType, String assetName, Long assetId) { String assetNameTrimmed = assetName.replaceAll(REGEX_TRIM_NAME, ""); if (assetType.equals(AssetType.PICTURE)) { pictureFileName.setText(assetNameTrimmed); clearPicture.setVisibility(View.VISIBLE); pictureId = assetId; showPreview(pictureId, picturePreview); } else { soundFileName.setText(assetNameTrimmed); clearSound.setVisibility(View.VISIBLE); soundId = assetId; soundComponent.setSoundId(soundId); } } private Integer getDuration() { if (!taskDurationTime.getText().toString().isEmpty() && !taskDurationTime.getText().toString().equals("0")) { return Integer.valueOf(taskDurationTime.getText().toString()); } return null; } @Override public void eventListStep(View view) { taskId = saveOrUpdate(); if (taskId != null) { showStepsList(taskId); } } @Override public void eventSelectPicture(View view) { filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.PICTURE); } @Override public void eventSelectSound(View view) { filePickerProxy.openFilePicker(TaskCreateFragment.this, AssetType.SOUND); } @Override public void eventClearPicture(View view) { clearPicture(); } @Override public void eventClearSound(View view) { clearSound(); } @Override public void eventClickPreviewPicture(View view) { showPicture(pictureId); } @Override public void eventChangeButtonStepsVisibility(View view, int id) { if (id == R.id.id_rb_type_task) { steps.setVisibility(View.VISIBLE); taskType = TaskType.TASK; } else { steps.setVisibility(View.INVISIBLE); if (id == R.id.id_rb_type_interaction) { taskType = TaskType.INTERACTION; } else { taskType = TaskType.PRIZE; } } } @Override public void eventSaveAndFinish(View view) { Long taskId = saveOrUpdate(); if (taskId != null) { showMainMenu(); } } }
autyzm-pg/friendly-plans
Friendly-plans/app/src/main/java/pg/autyzm/friendly_plans/manager_app/view/task_create/TaskCreateFragment.java
Java
gpl-3.0
11,189
/** Copyright 2010 Christian Kästner This file is part of CIDE. CIDE is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. CIDE 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 CIDE. If not, see <http://www.gnu.org/licenses/>. See http://www.fosd.de/cide/ for further information. */ package de.ovgu.cide.export.virtual.internal; import java.util.Set; import org.eclipse.jdt.core.dom.CompilationUnit; import de.ovgu.cide.export.CopiedNaiveASTFlattener; import de.ovgu.cide.export.useroptions.IUserOptionProvider; import de.ovgu.cide.features.IFeature; import de.ovgu.cide.features.source.ColoredSourceFile; /** * how to print annotations? note: we assume ifdef semantics, i.e. annotations * may be nested, but always close in the reverse order * * * @author ckaestne * */ public interface IPPExportOptions extends IUserOptionProvider { /** * should the start and end instructions be printed in a new line? (i.e. * should a line break be enforced before?) * * the instruction is responsible for the linebreak at the end itself * * @return */ boolean inNewLine(); /** * get the code statement(s) to begin an annotation block * * @param f * set of features annotated for the current element * @return */ String getStartInstruction(Set<IFeature> f); /** * get the code statement(s) to end an annotation block * * @param f * set of features annotated for the current element * @return */ String getEndInstruction(Set<IFeature> f); CopiedNaiveASTFlattener getPrettyPrinter(ColoredSourceFile sourceFile); /** * allows the developer to change the AST before printing it. can be used * for some refactorings. returns the modified AST * * @param root * @param sourceFile * @return */ CompilationUnit refactorAST(CompilationUnit root, ColoredSourceFile sourceFile); }
ckaestne/CIDE
CIDE_Export_Virtual/src/de/ovgu/cide/export/virtual/internal/IPPExportOptions.java
Java
gpl-3.0
2,375
class HomeController < ApplicationController def index @movies = Movie.all.sort_by{|movie| movie.rank}.reverse.first(7) @books = Book.all.sort_by{|book| book.rank}.reverse.first(7) @albums = Album.all.sort_by{|album| album.rank}.reverse.first(7) end end
ricarora/media-ranker
app/controllers/home_controller.rb
Ruby
gpl-3.0
270
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::HttpClient def initialize(info = {}) super(update_info(info, 'Name' => 'Solarwinds Orion AccountManagement.asmx GetAccounts Admin Creation', 'Description' => %q{ This module exploits a stacked SQL injection in order to add an administrator user to the SolarWinds Orion database. }, 'License' => MSF_LICENSE, 'Author' => [ 'Brandon Perry' #discovery/metasploit module ], 'References' => [ ['CVE', '2014-9566'] ], 'DisclosureDate' => 'Feb 24 2015' )) register_options( [ Opt::RPORT(8787), OptString.new('TARGETURI', [ true, "Base Orion directory path", '/']), OptString.new('USERNAME', [true, 'The username to authenticate as', 'Guest']), OptString.new('PASSWORD', [false, 'The password to authenticate with', '']) ], self.class) end def login (username,password) res = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'Orion', 'Login.aspx') }) viewstate = $1 if res.body =~ /id="__VIEWSTATE" value="(.*)" \/>/ cookie = res.get_cookies res = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'Orion', 'Login.aspx'), 'method' => 'POST', 'vars_post' => { '__EVENTTARGET' => '', '__EVENTARGUMENT' => '', '__VIEWSTATE' => viewstate, 'ctl00$BodyContent$Username' => username, 'ctl00$BodyContent$Password' => password }, 'cookie' => cookie }) if res.nil? fail_with(Failure::UnexpectedReply, "Server didn't respond in an expected way") end if res.code == 200 fail_with(Failure::NoAccess, "Authentication failed with username #{username}") end return cookie + ';' + res.get_cookies end def run cookie = login(datastore['USERNAME'], datastore['PASSWORD']) username = Rex::Text.rand_text_alpha(8) print_status("Logged in as #{datastore['USERNAME']}, sending payload to create #{username} admin user.") send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'Orion', 'Services', 'AccountManagement.asmx' '/GetAccounts'), 'method' => 'POST', 'vars_get' => { 'sort' => 'Accounts.AccountID', #also vulnerable 'dir' => "ASC;insert into accounts values ('#{username}', '127-510823478-74417-8', '/+PA4Zck3arkLA7iwWIugnAEoq4ocRsYjF7lzgQWvJc+pepPz2a5z/L1Pz3c366Y/CasJIa7enKFDPJCWNiKRg==', 'Feb 1 2100 12:00AM', 'Y', '#{username}', 1, '', '', 1, -1, 8, -1, 4, 0, 0, 0, 0, 0, 0, 'Y', 'Y', 'Y', 'Y', 'Y', '', '', 0, 0, 0, 'N', 'Y', '', 1, '', 0, '');" }, 'data' => '{"accountId":""}', 'cookie' => cookie, 'ctype' => 'application/json' }) login(username, '') print_good("The injection worked, log in with #{username} and a blank password") end end
cSploit/android.MSF
modules/auxiliary/gather/solarwinds_orion_sqli.rb
Ruby
gpl-3.0
3,119
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.14 at 05:14:09 PM CDT // @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.opengis.net/kml/2.2", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package hortonworks.hdp.refapp.trucking.simulator.impl.domain.transport.route.jaxb;
abeym/incubator
Trials/hdp/reference-apps/iot-trucking-app/trucking-data-simulator/src/main/java/hortonworks/hdp/refapp/trucking/simulator/impl/domain/transport/route/jaxb/package-info.java
Java
gpl-3.0
584
<?php /** * Mahara: Electronic portfolio, weblog, resume builder and social networking * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see: * http://wiki.mahara.org/Contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package mahara * @subpackage artefact-resume * @author Catalyst IT Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU GPL * @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz * */ define('INTERNAL', 1); define('JSON', 1); if (isset($_POST['view'])) { define('PUBLIC', 1); } require(dirname(dirname(dirname(__FILE__))) . '/init.php'); safe_require('artefact', 'resume'); $limit = param_integer('limit', null); $offset = param_integer('offset', 0); $type = param_alpha('type'); $view = param_integer('view', 0); $data = array(); $count = 0; $othertable = 'artefact_resume_' . $type; $owner = $USER->get('id'); $sql = 'SELECT ar.*, a.owner FROM {artefact} a JOIN {' . $othertable . '} ar ON ar.artefact = a.id WHERE a.owner = ? AND a.artefacttype = ? ORDER BY ar.displayorder'; if (!empty($view)) { if (!can_view_view($view)) { throw new AccessDeniedException(); } require_once('view.php'); $v = new View($view); $owner = $v->get('owner'); } if (!$data = get_records_sql_array($sql, array($owner, $type))) { $data = array(); } $count = count_records('artefact', 'owner', $owner, 'artefacttype', $type); echo json_encode(array( 'data' => $data, 'limit' => $limit, 'offset' => $offset, 'count' => $count, 'type' => $type)); ?>
richardmansfield/richardms-mahara
htdocs/artefact/resume/composite.json.php
PHP
gpl-3.0
2,211
<?php $client = ClientData::getById($_GET["id"]); $client->del(); $_SESSION['message'] = L::messages_del_with_success; $_SESSION['alert_type'] = 'success'; Core::redir("./index.php?view=clients"); ?>
CTA-IFRS/Sistema-bibliotecario
core/modules/index/action/delclient/action-default.php
PHP
gpl-3.0
201
/** * @addtogroup OutputTranslator * @{ * @file OutputTranslator/Scala.hh * @author Massimiliano Pagani * @version 1.0 * @date 2016-10-18 * */ #if !defined( OUTPUTTRANSLATOR_SCALA_HH ) #define OUTPUTTRANSLATOR_SCALA_HH #include "OutputTranslator/Base.hh" #include "Tydal/Grammar/BaseType.hh" #include "Tydal/Grammar/VariantType.hh" namespace OutputTranslator { class Scala : public Base { private: virtual void translateRecord( std::string const& name, std::shared_ptr<Tydal::Grammar::RecordType const> recordType, std::ostream& out ) override; virtual void translateEnum( std::string const& name, std::shared_ptr<Tydal::Grammar::EnumType const> enumType, std::ostream& out ) override; virtual void translateString( std::string const& name, std::shared_ptr<Tydal::Grammar::StringType const> stringType, std::ostream& out ) override; virtual void translateSimpleType( std::string const& name, std::shared_ptr<Tydal::Grammar::SimpleType const> simpleType, std::ostream& out ) override; virtual void translateArray( std::string const& name, std::shared_ptr<Tydal::Grammar::ArrayType const> arrayType, std::ostream& out ) override; void translateVariantBranch( std::string const& name, std::shared_ptr<Tydal::Grammar::VariantType const> variant, std::shared_ptr<Tydal::Grammar::VariantCaseEntry const> branch, std::ostream& out ); void translateRecordVariant( std::string const& name, std::shared_ptr<Tydal::Grammar::RecordType const> recordType, std::ostream& out ); void translateFields( std::string const& name, std::shared_ptr<Tydal::Grammar::RecordType const> recordType, std::ostream& out ); void translateVariantBranches( std::string const& name, std::shared_ptr<Tydal::Grammar::RecordType const> recordType, std::ostream& out ); void translateSimpleRecord( std::string const& name, std::shared_ptr<Tydal::Grammar::RecordType const> recordType, std::ostream& out ); void translateSubRecords( std::string const& name, std::shared_ptr<Tydal::Grammar::RecordType const> recordType, std::ostream& out ); void printField( std::ostream& out, Tydal::Grammar::RecordType::ConstIterator::value_type const& field ); void tydalTypeToScala( std::shared_ptr<Tydal::Grammar::BaseType const> type, std::string const& fieldName, std::ostream& out ); void pushEnclosingRecordName( std::string const& recordName ); void popEnclosingRecordName(); std::vector<std::string> const& getEnclosingRecordNames() const; std::string getRecordNames() const; std::vector<std::string> m_enclosingRecordNames; }; } // end of namespace OutputTranslator #endif ///@}
maxpagani/tydal
Sources/OutputTranslator/Scala.hh
C++
gpl-3.0
3,843
'use strict'; angular.module('aurea') .directive('d3Bars', function ($window, $timeout, d3Service) { return { restrict: 'EA', scope: { data: '=', onClick: '&' }, link: function (scope, ele, attrs) { d3Service.d3().then(function (d3) { var margin = parseInt(attrs.margin) || 20, barHeight = parseInt(attrs.barHeight) || 20, barPadding = parseInt(attrs.barPadding) || 5; var svg = d3.select(ele[0]) .append('svg') .style('width', '100%'); // Browser onresize event window.onresize = function () { scope.$apply(); }; // Watch for resize event scope.$watch(function () { return angular.element($window)[0].innerWidth; }, function () { scope.render(scope.data); }); scope.$watch('data', function (newData) { scope.render(newData); }, true); scope.render = function (data) { // remove all previous items before render svg.selectAll('*').remove(); // If we don't pass any data, return out of the element if (!data) return; // setup variables var width = d3.select(ele[0]).node().offsetWidth - margin, // calculate the height height = scope.data.length * (barHeight + barPadding), // Use the category20() scale function for multicolor support color = d3.scale.category20(), // our xScale xScale = d3.scale.linear() .domain([0, 31]) .range([0, width]); // set the height based on the calculations above svg.attr('height', height); //create the rectangles for the bar chart svg.selectAll('rect') .data(data).enter() .append('rect') .attr('height', barHeight) .attr('width', 140) .attr('x', 110) .attr('y', function (d, i) { return i * (barHeight + barPadding); }) .attr('fill', function (d) { return color(d.value); }) .attr('width', function (d) { return xScale(d.value); }); var baseSelection = svg.selectAll('text'); baseSelection .data(data) .enter() .append('text') .attr('font-family', 'monospace') .attr('fill', '#000') .attr('y', function (d, i) { return i * (barHeight + barPadding) + 15; }) .attr('x', 15) .text(function (d) { return d.name; }); baseSelection .data(data) .enter() .append('text') .attr('font-family', 'monospace') .attr('fill', '#fff') .attr('y', function (d, i) { return i * (barHeight + barPadding) + 15; }) .attr('x', 114) .text(function (d) { return d.value > 0 ? d.value : ''; }); }; }); } }; });
apuliasoft/aurea
public/js/directives/d3.js
JavaScript
gpl-3.0
4,457
package com.softech.ls360.lms.api.proxy.service; import com.softech.vu360.lms.webservice.message.lmsapi.serviceoperations.user.AddUserResponse; import com.softech.vu360.lms.webservice.message.lmsapi.serviceoperations.user.UpdateUserResponse; import com.softech.vu360.lms.webservice.message.lmsapi.types.user.UpdateableUser; import com.softech.vu360.lms.webservice.message.lmsapi.types.user.User; public interface LmsApiUserService { AddUserResponse createUser(User user, Long customerId, String customerCode, String apiKey) throws Exception; UpdateUserResponse updateUser(UpdateableUser updateableUser, Long customerId, String customerCode, String apiKey) throws Exception; }
haider78github/apiProxy
LmsApiProxy/src/main/java/com/softech/ls360/lms/api/proxy/service/LmsApiUserService.java
Java
gpl-3.0
685
<!-- <div class="jumbotron"> <h1>Welcome!</h1> <?php echo $content->getHtml(); ?> </div> --> <div class="row" style="padding: 15px;"> <?php $bgcolors = array('blue','green','orange','grey'); $i=0; foreach($content->children as $child){ $mod = $i % count($bgcolors); $color = $bgcolors[$mod]; echo '<div class="col-md-4 tile '.$color.'">'; echo '<a href="'.$child->getUrl().'">'.$child->title.'</a>'; echo '<p>'.$child->shortText.'</p>'; echo '</div>'; $i++; } ?> </div>
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.3/modules/manualsite/views/site/manualsite/home.php
PHP
gpl-3.0
514
package cz.cuni.lf1.lge.ThunderSTORM.estimators; import cz.cuni.lf1.lge.ThunderSTORM.detectors.CentroidOfConnectedComponentsDetector; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.EllipticGaussianPSF; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.EllipticGaussianWAnglePSF; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.Molecule; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.SymmetricGaussianPSF; import cz.cuni.lf1.lge.ThunderSTORM.filters.CompoundWaveletFilter; import cz.cuni.lf1.lge.ThunderSTORM.FormulaParser.FormulaParserException; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.IntegratedSymmetricGaussianPSF; import cz.cuni.lf1.lge.ThunderSTORM.estimators.PSF.PSFModel.Params; import cz.cuni.lf1.lge.ThunderSTORM.util.CSV; import static cz.cuni.lf1.lge.ThunderSTORM.util.MathProxy.sqr; import cz.cuni.lf1.lge.ThunderSTORM.util.Point; import ij.IJ; import ij.process.FloatProcessor; import java.util.List; import java.util.Vector; import org.junit.Test; import static org.junit.Assert.*; public class EstimatorsTest { @Test public void testRadialSymmetry() { testEstimator(new MultipleLocationsImageFitting(5, new RadialSymmetryFitter())); } @Test public void testLSQSym() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new SymmetricGaussianPSF(1), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new SymmetricGaussianPSF(1), true, Params.BACKGROUND))); } @Test public void testLSQIntSym() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new IntegratedSymmetricGaussianPSF(1), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new IntegratedSymmetricGaussianPSF(1), true, Params.BACKGROUND))); } @Test public void testMLEIntSym() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new IntegratedSymmetricGaussianPSF(1), Params.BACKGROUND))); } @Test public void testMLESym() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new SymmetricGaussianPSF(1), Params.BACKGROUND))); } @Test public void testLSQEllipticAngle() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianWAnglePSF(1, 0), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianWAnglePSF(1, 0), true, Params.BACKGROUND))); } @Test public void testMLEEllipticAngle() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new EllipticGaussianWAnglePSF(1, 0), Params.BACKGROUND))); } @Test public void testLSQElliptic() { testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianPSF(1, 45), false, Params.BACKGROUND))); testEstimator(new MultipleLocationsImageFitting(5, new LSQFitter(new EllipticGaussianPSF(1, 45), true, Params.BACKGROUND))); } @Test public void testMLEElliptic() { testEstimator(new MultipleLocationsImageFitting(5, new MLEFitter(new EllipticGaussianPSF(1, 45), Params.BACKGROUND))); } private void testEstimator(IEstimator estimator) throws FormulaParserException { String basePath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); FloatProcessor image = (FloatProcessor) IJ.openImage(basePath + "tubulins1_00020.tif").getProcessor().convertToFloat(); FloatProcessor filtered = (new CompoundWaveletFilter()).filterImage(image); Vector<Point> detections = (new CentroidOfConnectedComponentsDetector("16", true)).detectMoleculeCandidates(filtered); List<Molecule> fits = estimator.estimateParameters(image, detections); for(Molecule fit : fits) { convertXYToNanoMeters(fit, 150.0); } Vector<Molecule> ground_truth = null; try { ground_truth = CSV.csv2psf(basePath + "tubulins1_00020.csv", 1, 2); } catch(Exception ex) { fail(ex.getMessage()); } Vector<Pair> pairs = pairFitsAndDetections2GroundTruths(detections, fits, ground_truth); for(Pair pair : pairs) { assertFalse("Result from the estimator should be better than guess from the detector.", dist2(pair.fit, pair.ground_truth) > dist2(pair.detection, pair.ground_truth)); } // // Note: better test would be to compare these results to the results from Matlab...but I don't have them at the moment // } static void convertXYToNanoMeters(Molecule fit, double px2nm) { fit.setX(fit.getX() * px2nm); fit.setY(fit.getY() * px2nm); } static class Pair { Point detection; Molecule fit; Molecule ground_truth; public Pair(Point detection, Molecule fit, Molecule ground_truth) { this.detection = detection; this.fit = fit; this.ground_truth = ground_truth; } } static Vector<Pair> pairFitsAndDetections2GroundTruths(Vector<Point> detections, List<Molecule> fits, Vector<Molecule> ground_truth) { assertNotNull(fits); assertNotNull(detections); assertNotNull(ground_truth); assertFalse(fits.isEmpty()); assertFalse(detections.isEmpty()); assertFalse(ground_truth.isEmpty()); assertEquals("Number of detections should be the same as number of fits!", detections.size(), fits.size()); Vector<Pair> pairs = new Vector<Pair>(); int best_fit; double best_dist2, dist2; for(int i = 0, im = fits.size(); i < im; i++) { best_fit = 0; best_dist2 = dist2(fits.get(i), ground_truth.elementAt(best_fit)); for(int j = 1, jm = ground_truth.size(); j < jm; j++) { dist2 = dist2(fits.get(i), ground_truth.elementAt(j)); if(dist2 < best_dist2) { best_dist2 = dist2; best_fit = j; } } pairs.add(new Pair(detections.elementAt(i), fits.get(i), ground_truth.elementAt(best_fit))); } return pairs; } static double dist2(Point detection, Molecule ground_truth) { return sqr(detection.x.doubleValue() - ground_truth.getX()) + sqr(detection.y.doubleValue() - ground_truth.getY()); } static double dist2(Molecule fit, Molecule ground_truth) { return sqr(fit.getX() - ground_truth.getY()) + sqr(fit.getX() - ground_truth.getY()); } }
imunro/thunderstorm
src/test/java/cz/cuni/lf1/lge/ThunderSTORM/estimators/EstimatorsTest.java
Java
gpl-3.0
6,620
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # dépendances import requests import xml.dom.minidom import sys import signal import os import getopt from queue import Queue from threading import Thread import time class SetQueue(Queue): def _init(self, maxsize): Queue._init(self, maxsize) self.all_items = set() def _put(self, item): if item not in self.all_items: Queue._put(self, item) self.all_items.add(item) def signal_handler(signal, frame): print('You pressed Ctrl+C!') sys.exit(0) def usage(): """usage de la ligne de commande""" print ("usage : " + sys.argv[0] + "-h --help -s --server someurl.com -u --user login -p --password password") def getAtomFeed(url, login, pwd): # var MAX_TRY = 10 essai = 0 # get atom document while essai < MAX_TRY: try: r = requests.get('http://' + url, auth=(login,pwd), timeout=10) except: essai += 1 continue break else: raise ('Erreur lors de la requête') # parse atom document try: dom = xml.dom.minidom.parseString(r.text) except: raise ('Erreur lors du parsing du document Atom') return dom def getManagerInfo(atomFeed): try: entries = atomFeed.getElementsByTagName('entry')[1] except: return None try: managerId = entries.getElementsByTagName('snx:userid')[0] return managerId.firstChild.data except: return None def buildUrlSearchList(server, login, pwd, q): # var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] #alphabet = ['a'] for i in alphabet: url = server + '/profiles/atom/search.do?search=' + i + '*&ps=250' dom = getAtomFeed(url, login, pwd) totalResult = dom.getElementsByTagName('opensearch:totalResults')[0] totalResult = int(totalResult.firstChild.data) if totalResult > 250: nbPage = int(float(totalResult) / 250) + 1 for n in range(1,nbPage,1): item = url + "&page=" + str(n) q.put(item) else: nbPage = 1 q.put(url) def getUserIdsWorker(login, pwd, qin, qout): while True: url = qin.get() if url == None: break qin.task_done() try: dom = getAtomFeed(url, login, pwd) except: continue userIds = dom.getElementsByTagName('snx:userid') for index, item, in enumerate(userIds): qout.put(item.firstChild.data) def getRelationsWorker(server, login, pwd, qin, qout, getManager, qmgmt): while True: userid = qin.get() if userid == None: break qin.task_done() url = server + '/profiles/atom/connections.do?userid=' + userid + '&connectionType=colleague&ps=250' try: dom = getAtomFeed(url, login, pwd) except: continue feed = dom.firstChild entries = feed.getElementsByTagName('entry') for entry in entries: # get date dateRelation = entry.getElementsByTagName('updated')[0] dateRelation = dateRelation.firstChild.data dateRelation = dateRelation[:10] # get author user id author = entry.getElementsByTagName('author')[0] try: authorName = author.getElementsByTagName('name')[0] authorName = authorName.firstChild.data except: authorName = "" try: authorEMail = author.getElementsByTagName('email')[0] authorEMail = authorEMail.firstChild.data except: authorEMail = "" authorUserId = author.getElementsByTagName('snx:userid')[0] authorUserId = authorUserId.firstChild.data # get contributor user id contributor = entry.getElementsByTagName('contributor')[0] try: contribName = contributor.getElementsByTagName('name')[0] contribName = contribName.firstChild.data except: contribName = "" try: contribEMail = contributor.getElementsByTagName('email')[0] contribEMail = contribEMail.firstChild.data except: contribEMail = "" contribUserId = contributor.getElementsByTagName('snx:userid')[0] contribUserId = contribUserId.firstChild.data # build dict authorInfo = { "userid" : authorUserId, "name" : authorName, "email" : authorEMail } contribInfo = { "userid" : contribUserId, "name" : contribName, "email" : contribEMail } relation = "\"" + authorUserId + "\",\"" + contribUserId + "\",\"<(" + str(dateRelation) + ",Infinity)>\"" qout.put(authorInfo) qout.put(contribInfo) qout.put(relation) # get manager if getManager == True: url = server + "/profiles/atom/reportingChain.do?userid=" + userid rc = getAtomFeed(url, login, pwd) managerId = getManagerInfo(rc) if managerId is not None: reportingChain = str(userid) + "," + str(managerId) qmgmt.put(reportingChain) def printStatusThread(q0, q1, q2, q3): strtime = time.time() while True: sys.stdout.write('\r\x1b[K') sys.stdout.write("urls:" + str(q0.qsize()) + " | ") sys.stdout.write("userids:" + str(q1.qsize()) + " | ") sys.stdout.write("user infos:" + str(q2.qsize()) + " | ") sys.stdout.write("manager infos:" + str(q3.qsize())) sys.stdout.flush() time.sleep(1) def writeFileThread(usersFilename, relationsFilename, qin): # file for user details u = open(usersFilename + ".csv", "w") u.write("Id,Label,eMail\n") # file for relations r = open(relationsFilename + ".csv", "w") r.write("Source,Target,Time Interval\n") doneUsers = [] while True: data = qin.get() if data == None: u.flush() r.flush() u.close() r.close() break # write data if type(data) is dict: string = str(data["userid"]) + ',' + str(data["name"]) + ',' + str(data["email"]) if string not in doneUsers: u.write(string + "\n") doneUsers.append(string) elif type(data) is str: r.write(str(data) + "\n") qin.task_done() def writeManagerFileThread(managerFilename, qin): m = open(managerFilename + ".csv", "w") m.write("Source,Target\n") while True: data = qin.get() if data == None: break m.write(str(data) + "\n") qin.task_done() def main(argv): # global serverUrl = "" login = "" pwd = "" getManager = False urlQueue = SetQueue(maxsize=5000) userIdsQueue = SetQueue(maxsize=5000) userInfosQueue = Queue(maxsize=5000) userManagerQueue = Queue(maxsize=5000) # signal handler signal.signal(signal.SIGINT, signal_handler) # retrive arguments try: opts, args = getopt.getopt(argv, "hs:u:p:m", ["help", "server=", "user=", "password=", "manager"]) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-s", "--server"): serverUrl = arg elif opt in ("-u", "--user"): login = arg elif opt in ("-p", "--password"): pwd = arg elif opt in ("-m", "--manager"): getManager = True except: usage() sys.exit() # threading get userinfo worker userIdWorker = [] for i in range(10): w1 = Thread(target=getUserIdsWorker, args=(login, pwd, urlQueue, userIdsQueue,)) w1.setDaemon(True) w1.start() userIdWorker.append(w1) # threading get relations worker userInfoWorker = [] for i in range(20): w2 = Thread(target=getRelationsWorker, args=(serverUrl, login, pwd, userIdsQueue, userInfosQueue, getManager, userManagerQueue,)) w2.setDaemon(True) w2.start() userInfoWorker.append(w2) # thread to print size of queue w3 = Thread(target=printStatusThread, args=(urlQueue, userIdsQueue, userInfosQueue, userManagerQueue,)) w3.setDaemon(True) w3.start() # thread to write files w4 = Thread(target=writeFileThread, args=("users", "relations", userInfosQueue,)) w4.setDaemon(True) w4.start() if getManager == True: w5 = Thread(target=writeManagerFileThread, args=("manager", userManagerQueue,)) w5.setDaemon(True) w5.start() # build Queue url list MAX_TRY = 10 essai = 0 while essai < MAX_TRY: try: buildUrlSearchList(serverUrl, login, pwd, urlQueue) except KeyboardInterrupt: break except: essai += 1 continue break while not (urlQueue.empty() and userIdsQueue.empty() and userInfosQueue.empty()): pass print ("end threads") urlQueue.put(None) userIdsQueue.put(None) userInfosQueue.put(None) # end of workers for i in userIdWorker: i.join() for i in userInfoWorker: i.join() time.sleep(5) sys.exit(0) if __name__ == '__main__': main(sys.argv[1:])
adalmieres/scriptsIBMConnections
IBMConnectionsSocialGraph.py
Python
gpl-3.0
8,111
package org.renjin.invoke.codegen; import com.google.common.collect.Lists; import com.sun.codemodel.*; import org.apache.commons.math.complex.Complex; import org.renjin.invoke.annotations.PreserveAttributeStyle; import org.renjin.invoke.model.JvmMethod; import org.renjin.invoke.model.PrimitiveModel; import org.renjin.primitives.vector.DeferredComputation; import org.renjin.sexp.*; import java.util.List; import static com.sun.codemodel.JExpr.lit; public class DeferredVectorBuilder { public static final int LENGTH_THRESHOLD = 100; private final JExpression contextArgument; private JCodeModel codeModel; private PrimitiveModel primitive; private JvmMethod overload; private int arity; private JDefinedClass vectorClass; private VectorType type; private List<DeferredArgument> arguments = Lists.newArrayList(); private JFieldVar lengthField; public DeferredVectorBuilder(JCodeModel codeModel, JExpression contextArgument, PrimitiveModel primitive, JvmMethod overload) { this.codeModel = codeModel; this.primitive = primitive; this.overload = overload; this.arity = overload.getPositionalFormals().size(); this.contextArgument = contextArgument; if(overload.getReturnType().equals(double.class)) { type = VectorType.DOUBLE; } else if(overload.getReturnType().equals(boolean.class)) { type = VectorType.LOGICAL; } else if(overload.getReturnType().equals(Logical.class)) { type = VectorType.LOGICAL; } else if(overload.getReturnType().equals(int.class)) { type = VectorType.INTEGER; } else if(overload.getReturnType().equals(Complex.class)) { type = VectorType.COMPLEX; } else if(overload.getReturnType().equals(byte.class)) { type = VectorType.RAW; } else { throw new UnsupportedOperationException(overload.getReturnType().toString()); } } public void buildClass() { try { vectorClass = codeModel._class( WrapperGenerator2.toFullJavaName(primitive.getName()) + "$deferred_" + typeSuffix() ); } catch (JClassAlreadyExistsException e) { throw new RuntimeException(e); } vectorClass._extends(type.baseClass); vectorClass._implements(DeferredComputation.class); for(int i=0;i!=arity;++i) { arguments.add(new DeferredArgument(overload.getPositionalFormals().get(i), i)); } this.lengthField = vectorClass.field(JMod.PRIVATE, codeModel._ref(int.class), "length"); writeConstructor(); implementAccessor(); implementLength(); implementAttributeSetter(); implementGetOperands(); implementGetComputationName(); implementStaticApply(); implementIsConstantAccess(); implementGetComputationDepth(); if(overload.isPassNA() && overload.getReturnType().equals(boolean.class)) { overrideIsNaWithConstantValue(); } } private void implementIsConstantAccess() { JMethod method = vectorClass.method(JMod.PUBLIC, boolean.class, "isConstantAccessTime"); JExpression condition = null; for(DeferredArgument arg : arguments) { JExpression operandIsConstant = arg.valueField.invoke("isConstantAccessTime"); if(condition == null) { condition = operandIsConstant; } else { condition = condition.cand(operandIsConstant); } } method.body()._return(condition); } private void implementGetComputationDepth() { JMethod method = vectorClass.method(JMod.PUBLIC, int.class, "getComputationDepth"); JVar depth = method.body().decl(codeModel._ref(int.class), "depth", arguments.get(0).valueField.invoke("getComputationDepth")); for(int i=1;i<arguments.size();++i) { method.body().assign(depth, codeModel.ref(Math.class).staticInvoke("max") .arg(depth) .arg(arguments.get(1).valueField.invoke("getComputationDepth"))); } method.body()._return(depth.plus(JExpr.lit(1))); } private void implementGetOperands() { JMethod method = vectorClass.method(JMod.PUBLIC, Vector[].class, "getOperands"); JArray array = JExpr.newArray(codeModel.ref(Vector.class)); for(DeferredArgument arg : arguments) { array.add(arg.valueField); } method.body()._return(array); } private void implementGetComputationName() { JMethod method = vectorClass.method(JMod.PUBLIC, String.class, "getComputationName"); method.body()._return(lit(primitive.getName())); } private String typeSuffix() { StringBuilder suffix = new StringBuilder(); for(JvmMethod.Argument formal : overload.getPositionalFormals()) { suffix.append(abbrev(formal.getClazz())); } return suffix.toString(); } private String abbrev(Class clazz) { if(clazz.equals(double.class)) { return "d"; } else if(clazz.equals(boolean.class)) { return "b"; } else if(clazz.equals(String.class)) { return "s"; } else if(clazz.equals(int.class)) { return "i"; } else if(clazz.equals(Complex.class)) { return "z"; } else if(clazz.equals(byte.class)) { return "r"; } else { throw new UnsupportedOperationException(clazz.toString()); } } public void maybeReturn(JBlock parent, JExpression cycleCount, List<JExpression> arguments) { JExpression condition = cycleCount.gt(lit(LENGTH_THRESHOLD)); for(JExpression arg : arguments) { condition = condition.cor(arg._instanceof(codeModel.ref(DeferredComputation.class))); } JBlock ifBig = parent._if(condition)._then(); JExpression attributes = copyAttributes(arguments); JInvocation newInvocation = JExpr._new(vectorClass); for(JExpression arg : arguments) { newInvocation.arg(arg); } newInvocation.arg(attributes); ifBig._return(contextArgument.invoke("simplify").arg(newInvocation)); } private JExpression copyAttributes(List<JExpression> arguments) { if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.NONE) { return codeModel.ref(AttributeMap.class).staticRef("EMPTY"); } else { if(arity == 1) { return copyAttributes(arguments.get(0)); } else if(arity == 2) { return copyAttributes(arguments.get(0), arguments.get(1)); } else { throw new UnsupportedOperationException("arity = " + arity); } } } private JExpression copyAttributes(JExpression arg0, JExpression arg1) { String combineMethod; switch(overload.getPreserveAttributesStyle()) { case ALL: combineMethod = "combineAttributes"; break; case SPECIAL: combineMethod = "combineStructuralAttributes"; break; default: throw new UnsupportedOperationException(); } return codeModel.ref(AttributeMap.class).staticInvoke(combineMethod) .arg(arg0) .arg(arg1); } private JExpression copyAttributes(JExpression arg) { if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.ALL) { return arg.invoke("getAttributes"); } else if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.SPECIAL) { return arg.invoke("getAttributes").invoke("copyStructural"); } else { throw new UnsupportedOperationException(); } } private void writeConstructor() { // public DoubleBinaryFnVector(Vector arg0, Vector arg1, AttributeMap attributes) { // super(attributes); // this.x = x; // this.y = y; // this.fn = fn; // this.xLength = x.length(); // this.yLength = y.length(); // this.length = Math.max(xLength, yLength); // } JMethod ctor = vectorClass.constructor(JMod.PUBLIC); List<JVar> argParams = Lists.newArrayList(); for(int i=0;i!=arity;++i) { argParams.add(ctor.param(Vector.class, "arg" + i)); } ctor.param(AttributeMap.class, "attributes"); ctor.body().directStatement("super(attributes);"); ctor.body().assign(lengthField, lit(0)); for(int i=0;i!=arity;++i) { ctor.body().assign(JExpr._this().ref(arg(i).valueField), argParams.get(i)); ctor.body().assign(arg(i).lengthField, arg(i).valueField.invoke("length")); } if(arity == 1) { ctor.body().assign(lengthField, arg(0).lengthField); } else if(arity == 2) { ctor.body().assign(lengthField, codeModel.ref(Math.class).staticInvoke("max") .arg(arg(0).lengthField) .arg(arg(1).lengthField)); } } private DeferredArgument arg(int i) { return arguments.get(i); } private void implementLength() { JMethod method = vectorClass.method(JMod.PUBLIC, int.class, "length"); method.body()._return(lengthField); } private void implementStaticApply() { JMethod method = vectorClass.method(JMod.PUBLIC | JMod.STATIC, type.accessorType, "compute"); List<JExpression> params = Lists.newArrayList(); for(DeferredArgument argument : arguments) { JVar param = method.param(argument.accessorType(), "p" + argument.index); params.add(argument.convert(param)); } returnValue(method.body(), buildInvocation(params)); } private void implementAccessor() { JMethod method = vectorClass.method(JMod.PUBLIC, type.accessorType, type.accessorName); JVar index = method.param(int.class, "index"); // extract the arguments to the function from the given vectors List<JExpression> argValues = Lists.newArrayList(); for(DeferredArgument arg : arguments) { JExpression elementIndex; if(arity == 1) { elementIndex = index; } else { // avoid using modulus if we can JVar indexVar = method.body().decl(codeModel._ref(int.class), "i" + arg.index); JConditional ifLessThan = method.body()._if(index.lt(arg.lengthField)); ifLessThan._then().assign(indexVar, index); ifLessThan._else().assign(indexVar, index.mod(arg.lengthField)); elementIndex = indexVar; } JVar argValue = method.body().decl(arg.accessorType(), "arg" + arg.index + "_i", arg.invokeAccessor(elementIndex)); argValues.add(arg.convert(argValue)); if(!overload.isPassNA() && arg.type != ArgumentType.BYTE) { method.body()._if(arg.isNA(argValue))._then()._return(na()); } } // invoke the underlying function returnValue(method.body(), buildInvocation(argValues)); } private JInvocation buildInvocation(List<JExpression> argValues) { JInvocation invocation = codeModel .ref(overload.getDeclaringClass()) .staticInvoke(overload.getName()); for(JExpression argValue : argValues) { invocation.arg(argValue); } return invocation; } private JExpression na() { switch (type) { case DOUBLE: return codeModel.ref(DoubleVector.class).staticRef("NA"); case LOGICAL: case INTEGER: return codeModel.ref(IntVector.class).staticRef("NA"); case COMPLEX: return codeModel.ref(ComplexArrayVector.class).staticRef("NA"); } throw new UnsupportedOperationException(type.toString()); } private void returnValue(JBlock parent, JExpression retVal) { if(overload.getReturnType().equals(boolean.class)) { JConditional ifTrue = parent._if(retVal); ifTrue._then()._return(lit(1)); ifTrue._else()._return(lit(0)); } else if(overload.getReturnType().equals(Logical.class)) { parent._return(retVal.invoke("getInternalValue")); } else { parent._return(retVal); } } public void overrideIsNaWithConstantValue() { JMethod method = vectorClass.method(JMod.PUBLIC, boolean.class, "isElementNA"); method.param(int.class, "index"); method.body()._return(JExpr.FALSE); } private void implementAttributeSetter() { // @Override // protected SEXP cloneWithNewAttributes(AttributeMap attributes) { // return new DoubleBinaryFnVector(fn, x, y, attributes); // } JMethod method = vectorClass.method(JMod.PUBLIC, SEXP.class, "cloneWithNewAttributes"); JVar attributes = method.param(AttributeMap.class, "attributes"); JInvocation newInvocation = JExpr._new(vectorClass); for(DeferredArgument arg : arguments) { newInvocation.arg(arg.valueField); } newInvocation.arg(attributes); method.body()._return(newInvocation); } private class DeferredArgument { private JvmMethod.Argument model; private int index; private JFieldVar valueField; private JFieldVar lengthField; private ArgumentType type; private DeferredArgument(JvmMethod.Argument model, int index) { this.model = model; this.index = index; this.valueField = vectorClass.field(JMod.PRIVATE | JMod.FINAL, Vector.class, "arg" + index); this.lengthField = vectorClass.field(JMod.PRIVATE | JMod.FINAL, int.class, "argLength" + index); if(model.getClazz().equals(double.class)) { this.type = ArgumentType.DOUBLE; } else if(model.getClazz().equals(boolean.class)) { this.type = ArgumentType.BOOLEAN; } else if(model.getClazz().equals(int.class)) { this.type = ArgumentType.INTEGER; } else if(model.getClazz().equals(String.class)) { this.type = ArgumentType.STRING; } else if(model.getClazz().equals(Complex.class)) { this.type = ArgumentType.COMPLEX; } else if(model.getClazz().equals(byte.class)) { this.type = ArgumentType.BYTE; } else { throw new UnsupportedOperationException(model.getClazz().toString()); } } public JType type() { return codeModel._ref(model.getClazz()); } public JExpression invokeAccessor(JExpression elementIndex) { return valueField.invoke(type.accessorName).arg(elementIndex); } public JType accessorType() { return codeModel._ref(type.accessorType()); } public JExpression isNA(JExpression expr) { return type.isNa(codeModel, expr); } public JExpression convert(JExpression argValue) { return type.convertToArg(argValue); } } private enum VectorType { DOUBLE(DoubleVector.class, "getElementAsDouble", double.class), LOGICAL(LogicalVector.class, "getElementAsRawLogical", int.class), INTEGER(IntVector.class, "getElementAsInt", int.class), COMPLEX(ComplexVector.class, "getElementAsComplex", Complex.class), RAW(RawVector.class, "getElementAsByte", byte.class); private Class baseClass; private String accessorName; private Class accessorType; private VectorType(Class baseClass, String accessorName, Class accessorType) { this.baseClass = baseClass; this.accessorName = accessorName; this.accessorType = accessorType; } } private enum ArgumentType { DOUBLE(double.class, "getElementAsDouble") { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(DoubleVector.class).staticInvoke("isNA").arg(expr); } }, INTEGER(int.class, "getElementAsInt") { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(IntVector.class).staticInvoke("isNA").arg(expr); } }, BOOLEAN(boolean.class, "getElementAsRawLogical") { @Override public JExpression convertToArg(JExpression expr) { return expr.ne(lit(0)); } @Override public Class accessorType() { return int.class; } @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(IntVector.class).staticInvoke("isNA").arg(expr); } }, STRING(String.class, "getElementAsString") { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(StringVector.class).staticInvoke("isNA").arg(expr); } }, COMPLEX(Complex.class, "getElementAsComplex" ) { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return codeModel.ref(ComplexVector.class).staticInvoke("isNA").arg(expr); } }, BYTE(byte.class, "getElementAsByte" ) { @Override public JExpression isNa(JCodeModel codeModel, JExpression expr) { return JExpr.lit(false); } }; private Class clazz; private String accessorName; private ArgumentType(Class clazz, String accessorName) { this.clazz = clazz; this.accessorName = accessorName; } public JExpression convertToArg(JExpression expr) { return expr; } public Class accessorType() { return clazz; } public abstract JExpression isNa(JCodeModel codeModel, JExpression expr); } }
hlin09/renjin
core/src/main/java/org/renjin/invoke/codegen/DeferredVectorBuilder.java
Java
gpl-3.0
16,612
/* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2016 HydroloGIS (www.hydrologis.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.geopaparazzi.core.preferences; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.Spinner; import eu.geopaparazzi.core.R; import eu.geopaparazzi.library.locale.LocaleUtils; /** * A custom preference to force a particular locale, even if the OS is on another. * * @author Andrea Antonello (www.hydrologis.com) */ public class ForceLocalePreference extends DialogPreference { public static final String PREFS_KEY_FORCELOCALE = "PREFS_KEY_FORCELOCALE";//NON-NLS private Context context; private Spinner localesSpinner; /** * @param ctxt the context to use. * @param attrs attributes. */ public ForceLocalePreference(Context ctxt, AttributeSet attrs) { super(ctxt, attrs); this.context = ctxt; setPositiveButtonText(ctxt.getString(android.R.string.ok)); setNegativeButtonText(ctxt.getString(android.R.string.cancel)); } @Override protected View onCreateDialogView() { LinearLayout mainLayout = new LinearLayout(context); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mainLayout.setLayoutParams(layoutParams); mainLayout.setOrientation(LinearLayout.VERTICAL); mainLayout.setPadding(25, 25, 25, 25); localesSpinner = new Spinner(context); localesSpinner.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); localesSpinner.setPadding(15, 5, 15, 5); final String[] localesArray = context.getResources().getStringArray(R.array.locales); ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, localesArray); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); localesSpinner.setAdapter(adapter); final String currentLocale = LocaleUtils.getCurrentLocale(context); if (currentLocale != null) { for (int i = 0; i < localesArray.length; i++) { if (localesArray[i].equals(currentLocale.trim())) { localesSpinner.setSelection(i); break; } } } mainLayout.addView(localesSpinner); return mainLayout; } @Override protected void onBindDialogView(View v) { super.onBindDialogView(v); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { String selectedLocale = localesSpinner.getSelectedItem().toString(); LocaleUtils.changeLang(context, selectedLocale); } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return (a.getString(index)); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { } }
geopaparazzi/geopaparazzi
geopaparazzi_core/src/main/java/eu/geopaparazzi/core/preferences/ForceLocalePreference.java
Java
gpl-3.0
4,020
/* * Author: patiphat mana-u-krid (dew) * E-Mail: dewtx29@gmail.com * facebook: https://www.facebook.com/dewddminecraft */ package dewddgetaway; import java.util.Random; import java.util.Stack; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.plugin.java.JavaPlugin; public class dewgetaway2 implements Listener { class chatx implements Runnable { Player p = null; String message = ""; public void run() { String m[] = message.split("\\s+"); if (m[0].equalsIgnoreCase("/dewgetawayrun")) { staticarea.dslb.loaddewsetlistblockfile(); isruntick = !isruntick; dprint.r.printAll("isruntick = " + Boolean.toString(isruntick)); getawayticktock time = new getawayticktock(); time.setName("getaway"); time.start(); return; } if (m[0].equalsIgnoreCase("/dewgetaway")) { if (m.length == 1) { // it's mean toggle your self if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } int getid = getfreeselect(p.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } else if (m.length == 2) { // it's mean have player name if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } if (m[1].equalsIgnoreCase(p.getName()) == false) { if (p.hasPermission(pgetawayother) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } } if (m[1].equalsIgnoreCase("@a") == true) { // it's mean toggle everyone for (Player p2 : Bukkit.getOnlinePlayers()) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } } else { // find that player for (Player p2 : Bukkit.getOnlinePlayers()) { if (p2.getName().toLowerCase() .indexOf(m[1].toLowerCase()) > -1) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = !nn.isrun[getid]; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); break; } } return; } } else if (m.length == 3) { // it's mean player 0|1 if (p.hasPermission(pgetaway) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } if (m[1].equalsIgnoreCase(p.getName()) == false) { if (p.hasPermission(pgetawayother) == false) { p.sendMessage("you don't have permission " + pgetaway); return; } } if (m[2].equalsIgnoreCase("0") == false && m[2].equalsIgnoreCase("1") == false) { p.sendMessage("argument 3 must be 0 or 1"); return; } boolean togglemode = false; if (m[2].equalsIgnoreCase("1") == true) togglemode = true; if (m[1].equalsIgnoreCase("@a") == true) { // it's mean toggle everyone for (Player p2 : Bukkit.getOnlinePlayers()) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = togglemode; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); } return; } else { // find that player for (Player p2 : Bukkit.getOnlinePlayers()) { if (p2.getName().toLowerCase() .indexOf(m[1].toLowerCase()) > -1) { int getid = getfreeselect(p2.getName()); nn.isrun[getid] = togglemode; p.sendMessage(nn.playername[getid] + " getaway mode = " + Boolean.toString(nn.isrun[getid])); break; } } return; } } } } } class ddata { public String playername[]; public boolean isrun[]; } class getawaytick2 implements Runnable { public void run() { long starttime = System.currentTimeMillis(); long endtime = 0; // loop everyone // printAll("tick"); for (int i = 0; i < ddatamax; i++) { if (nn.isrun[i] == true) { // printAll("found nn = true at " + i); if (nn.playername[i].equalsIgnoreCase("") == false) { // printAll(" nn name empty == false at " + i); // search that player Player p2 = null; for (Player p3 : Bukkit.getOnlinePlayers()) { if (p3.getName().equalsIgnoreCase(nn.playername[i])) { p2 = p3; break; } } if (p2 == null) { // printAll("p2 = null " + i); continue; } // printAll("foundn p2"); double td = 0; Block b = null; Block b2 = null; for (int x = -ra; x <= ra; x++) { for (int y = -ra; y <= ra; y++) { for (int z = -ra; z <= ra; z++) { endtime = System.currentTimeMillis(); if (endtime - starttime > 250) return; if (dewddtps.tps.getTPS() < 18) { return; } b = p2.getLocation().getBlock() .getRelative(x, y, z); // b2 is looking td = distance3d(b.getX(), b.getY(), b.getZ(), p2.getLocation().getBlockX(), p2 .getLocation().getBlockY(), p2.getLocation().getBlockZ()); // printAll("radi td " + td); if (td > ra) { continue; } // check this block // b = // p2.getLocation().getBlock().getRelative(x,y,z); boolean bll = blockdewset(b.getTypeId()); if (bll == false) { continue; } // check sign for (int nx = -1; nx <= 1; nx++) { for (int ny = -1; ny <= 1; ny++) { for (int nz = -1; nz <= 1; nz++) { if (b.getRelative(nx, ny, nz) .getTypeId() == 0) { continue; } if (b.getRelative(nx, ny, nz) .getTypeId() == 63 || b.getRelative(nx, ny, nz) .getTypeId() == 68 || b.getRelative(nx, ny, nz) .getType() .isBlock() == false || blockdewset(b .getRelative( nx, ny, nz) .getTypeId()) == false) { bll = false; if (bll == false) { break; } } if (bll == false) { break; } } } if (bll == false) { break; } } if (bll == false) { continue; } // printAll("adding " + b.getX() + "," + // b.getY() + "," + b.getZ()); // move it b2 = getran(b, 1); saveb xx = new saveb(); xx.b1id = b.getTypeId(); xx.b1data = b.getData(); xx.b1x = b.getX(); xx.b1y = b.getY(); xx.b1z = b.getZ(); xx.b2id = b2.getTypeId(); xx.b2data = b2.getData(); xx.b2x = b2.getX(); xx.b2y = b2.getY(); xx.b2z = b2.getZ(); xx.w = b.getWorld().getName(); bd.push(xx); // added queue // switch that block b.setTypeId(xx.b2id); b.setData(xx.b2data); b2.setTypeId(xx.b1id); b2.setData(xx.b1data); } } } // if found player // search neary block at player it's sholud be move // or not // if yes add to queue // and loop again to should it's roll back or not // We should't use quere // We should use array } } } // after add quere dprint.r.printC("bd size = " + bd.size()); for (int gx = 0; gx <= 300; gx++) { // this is rollback block if (bd.size() == 0) { bd.trimToSize(); return; } endtime = System.currentTimeMillis(); if (endtime - starttime > 250) return; if (dewddtps.tps.getTPS() < 18) { return; } // printC("before peek " + bd.size()); saveb ttt = bd.peek(); // printC("after peek " + bd.size()); Block b3 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b1x, ttt.b1y, ttt.b1z); Block b4 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b2x, ttt.b2y, ttt.b2z); boolean isp = false; isp = isplayernearblock(b3, ra) || isplayernearblock(b4, ra); if (isp == true) { return; } ttt = bd.pop(); b3 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b1x, ttt.b1y, ttt.b1z); b4 = Bukkit.getWorld(ttt.w).getBlockAt(ttt.b2x, ttt.b2y, ttt.b2z); b4.setTypeId(ttt.b2id); b4.setData(ttt.b2data); b3.setTypeId(ttt.b1id); b3.setData(ttt.b1data); } // if not player near rollback // check // is't there have player near that block ? } } class getawayticktock extends Thread { public void run() { while (isruntick == true) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } getawaytick2 eee = new getawaytick2(); Bukkit.getScheduler().scheduleSyncDelayedTask(ac, eee); } } } class saveb { public int b1id = 0; public byte b1data = 0; public int b1x = 0; public int b1y = 0; public int b1z = 0; public int b2id = 0; public byte b2data = 0; public int b2x = 0; public int b2y = 0; public int b2z = 0; public String w = ""; } boolean isruntick = false; JavaPlugin ac = null; int ra = 5; int ddatamax = 29; ddata nn = new ddata(); String pgetaway = "dewdd.getaway.use"; String pgetawayother = "dewdd.getaway.use.other"; Stack<saveb> bd = new Stack<saveb>(); // Queue<saveb> bd= new LinkedList<saveb>(); Random rnd = new Random(); public dewgetaway2() { nn.playername = new String[ddatamax]; nn.isrun = new boolean[ddatamax]; for (int i = 0; i < ddatamax; i++) { nn.playername[i] = ""; nn.isrun[i] = false; } } public boolean blockdewset(int blockid) { return staticarea.dslb.isdewset(blockid) && staticarea.dslb.isdewinventoryblock(blockid) == false && blockid != 0 && blockid != 8 && blockid != 9 && blockid != 10 && blockid != 11; } public int distance2d(int x1, int z1, int x2, int z2) { double t1 = Math.pow(x1 - x2, 2); double t2 = Math.pow(z1 - z2, 2); double t3 = Math.pow(t1 + t2, 0.5); int t4 = (int) t3; return t4; } public double distance3d(int x1, int y1, int z1, int x2, int y2, int z2) { double t1 = Math.pow(x1 - x2, 2); double t2 = Math.pow(z1 - z2, 2); double t3 = Math.pow(y1 - y2, 2); double t5 = Math.pow(t1 + t2 + t3, 0.5); return t5; } @EventHandler public void eventja(PlayerCommandPreprocessEvent event) { chatx a = new chatx(); a.p = event.getPlayer(); a.message = event.getMessage(); Bukkit.getScheduler().scheduleSyncDelayedTask(ac, a); } public int getfreeselect(String sname) { // clean exited player boolean foundx = false; for (int i = 0; i < ddatamax; i++) { foundx = false; for (Player pr : Bukkit.getOnlinePlayers()) { if (nn.playername[i].equalsIgnoreCase(pr.getName())) { foundx = true; break; } } if (foundx == false) { nn.playername[i] = ""; nn.isrun[i] = false; } } // clean for (int i = 0; i < ddatamax; i++) { if (nn.playername[i].equalsIgnoreCase(sname)) { return i; } } for (int i = 0; i < ddatamax; i++) { if (nn.playername[i].equalsIgnoreCase("")) { nn.playername[i] = sname; return i; } } return -1; } public Block getran(Block b, int ra) { Block b2 = b; int tx = 0; int ty = 0; int tz = 0; int counttry = 0; do { counttry++; tx = rnd.nextInt(ra * 2) - (ra * 1); ty = rnd.nextInt(ra * 2) - (ra * 1); tz = rnd.nextInt(ra * 2) - (ra * 1); if (ty < 1) ty = 1; if (ty > 254) ty = 254; b2 = b.getRelative(tx, ty, tz); if (counttry >= 100) { counttry = 0; ra = ra + 1; } } while (b2.getLocation().distance(b.getLocation()) < ra || b2 == b || b2.getTypeId() != 0); return b2; } public boolean isplayernearblock(Block bh, int ra) { for (Player uu : bh.getWorld().getPlayers()) { if (nn.isrun[getfreeselect(uu.getName())] == false) continue; if (uu.getLocation().distance(bh.getLocation()) <= ra) { return true; } } return false; } } // class
dewtx29/dewdd_minecraft_plugins
old/dewdd_getaway/src/dewddgetaway/dewgetaway2.java
Java
gpl-3.0
13,351
#! /usr/bin/env python # -*- coding: utf-8 -*- # # pkpgcounter : a generic Page Description Language parser # # (c) 2003-2009 Jerome Alet <alet@librelogiciel.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # $Id$ # # import sys import glob import os import shutil try : from distutils.core import setup except ImportError as msg : sys.stderr.write("%s\n" % msg) sys.stderr.write("You need the DistUtils Python module.\nunder Debian, you may have to install the python-dev package.\nOf course, YMMV.\n") sys.exit(-1) try : from PIL import Image except ImportError : sys.stderr.write("You need the Python Imaging Library (aka PIL).\nYou can grab it from http://www.pythonware.com\n") sys.exit(-1) sys.path.insert(0, "pkpgpdls") from pkpgpdls.version import __version__, __doc__ data_files = [] mofiles = glob.glob(os.sep.join(["po", "*", "*.mo"])) for mofile in mofiles : lang = mofile.split(os.sep)[1] directory = os.sep.join(["share", "locale", lang, "LC_MESSAGES"]) data_files.append((directory, [ mofile ])) docdir = "share/doc/pkpgcounter" docfiles = ["README", "COPYING", "BUGS", "CREDITS", "AUTHORS", "TODO"] data_files.append((docdir, docfiles)) if os.path.exists("ChangeLog") : data_files.append((docdir, ["ChangeLog"])) directory = os.sep.join(["share", "man", "man1"]) manpages = glob.glob(os.sep.join(["man", "*.1"])) data_files.append((directory, manpages)) setup(name = "pkpgcounter", version = __version__, license = "GNU GPL", description = __doc__, author = "Jerome Alet", author_email = "alet@librelogiciel.com", url = "http://www.pykota.com/software/pkpgcounter/", packages = [ "pkpgpdls" ], scripts = [ "bin/pkpgcounter" ], data_files = data_files)
lynxis/pkpgcounter
setup.py
Python
gpl-3.0
2,361
const actions = { // Video ended ended({dispatch,commit}, video) { video.isPlaying = false; dispatch('next', video); commit('PLAYING',video); }, // Add video to queue addToQueue({state, dispatch, commit }, obj) { var index = _.findIndex(state.queue, function(o) { return o.videoId == obj.videoId; }); if (index == -1) commit('ADD_TO_QUEUE', obj); }, // Play a video playVideo({ state, dispatch, commit }, video) { if (!state.playing || state.playing.videoId != video.videoId) { state.player.loadVideoById({ videoId: video.videoId, suggestedQuality: 'small' }); } else { state.player.playVideo(); } video.isPlaying = true; commit('PLAYING',video); dispatch('addToQueue', video); }, // Puase a video pauseVideo({ state, dispatch, commit }, video) { video.isPlaying = false; state.player.pauseVideo(); commit('PLAYING',video); }, // Play next song next({ state, dispatch, commit }) { if (state.queue && state.playing) { var index = _.findIndex(state.queue, function(o) { return o.videoId == state.playing.videoId; }); if (index != -1 && state.queue[index + 1]) { dispatch('playVideo', state.queue[index + 1]); } } }, // Play previous song previous({ state, dispatch, commit }) { if (state.queue && state.playing) { var index = _.findIndex(state.queue, function(o) { return o.videoId == state.playing.videoId; }); if (index && state.queue[index - 1]) { dispatch('playVideo', state.queue[index - 1]); } } }, addToFav({state,commit},video){ var index = _.findIndex(state.favs,function(o){ return o.videoId == video.videoId; }); // Add to favs if not exists if(index == -1) { commit('ADD_TO_FAVS',video); state.localStorage.setItem("favs", state.favs); } else if(index >= 0) { commit('REMOVE_FROM_FAVS',index); state.localStorage.setItem("favs", state.favs); } }, // Add localforge to state and load data from localStorage loadLocalStorage({state,commit},localStorage){ commit('LOAD_LOCAL_STORAGE',localStorage); state.localStorage.getItem('favs').then(function(list) { if(list) commit('ADD_TO_FAVS',list); }).catch(function(err) { console.log(err); }); } } export default actions;
iamspal/playtube
src/store/actions.js
JavaScript
gpl-3.0
2,955
// core import React from 'react'; import PropTypes from 'react'; // components import Loading from '../../components/loading/Loading'; // styles var style = require('./_index.scss'); // data var Timeline = require('react-twitter-widgets').Timeline; var Twitter = React.createClass({ getInitialState: function(){ return { isLoading: true } }, componentWillMount: function(){ this.setState({ isLoading: true }) }, componentDidMount: function(){ this.setState({ isLoading: false }) }, render: function(){ if(this.state.isLoading === true){ return ( <Loading /> ) } else { return ( <div className='twitter-container'> <Timeline className='twitter-component' dataSource={{ sourceType: 'widget', widgetId: '844245316706566144' }} /> </div> ) } } }); export default Twitter;
JoeDahle/fic
app/components/twitter/Twitter.js
JavaScript
gpl-3.0
946
/* =========================================================================== Copyright (c) 2010-2014 Darkstar Dev Teams 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/ This file is part of DarkStar-server source code. =========================================================================== */ #include <string.h> #include "../entities/charentity.h" #include "../entities/mobentity.h" #include "../party.h" #include "charutils.h" #include "../alliance.h" #include "zoneutils.h" #include "itemutils.h" #include "battlefieldutils.h" #include "../battlefield.h" #include "../battlefield_handler.h" #include "../packets/entity_update.h" namespace battlefieldutils{ /*************************************************************** Loads the given battlefield from the database and returns a new Battlefield object. ****************************************************************/ CBattlefield* loadBattlefield(CBattlefieldHandler* hand, uint16 bcnmid, BATTLEFIELDTYPE type){ const int8* fmtQuery = "SELECT name, bcnmId, fastestName, fastestTime, timeLimit, levelCap, lootDropId, rules, partySize, zoneId \ FROM bcnm_info \ WHERE bcnmId = %u"; int32 ret = Sql_Query(SqlHandle, fmtQuery, bcnmid); if (ret == SQL_ERROR || Sql_NumRows(SqlHandle) == 0 || Sql_NextRow(SqlHandle) != SQL_SUCCESS) { ShowError("Cannot load battlefield BCNM:%i \n",bcnmid); } else { CBattlefield* PBattlefield = new CBattlefield(hand,Sql_GetUIntData(SqlHandle,1), type); int8* tmpName; Sql_GetData(SqlHandle,0,&tmpName,NULL); PBattlefield->setBcnmName(tmpName); PBattlefield->setTimeLimit(Sql_GetUIntData(SqlHandle,4)); PBattlefield->setLevelCap(Sql_GetUIntData(SqlHandle,5)); PBattlefield->setLootId(Sql_GetUIntData(SqlHandle,6)); PBattlefield->setMaxParticipants(Sql_GetUIntData(SqlHandle,8)); PBattlefield->setZoneId(Sql_GetUIntData(SqlHandle,9)); PBattlefield->m_RuleMask = (uint16)Sql_GetUIntData(SqlHandle,7); return PBattlefield; } return NULL; } /*************************************************************** Spawns monsters for the given BCNMID/Battlefield number by looking at bcnm_battlefield table for mob ids then spawning them and adding them to the monster list for the given battlefield. ****************************************************************/ bool spawnMonstersForBcnm(CBattlefield* battlefield){ DSP_DEBUG_BREAK_IF(battlefield==NULL); //get ids from DB const int8* fmtQuery = "SELECT monsterId, conditions \ FROM bcnm_battlefield \ WHERE bcnmId = %u AND battlefieldNumber = %u"; int32 ret = Sql_Query(SqlHandle, fmtQuery, battlefield->getID(), battlefield->getBattlefieldNumber()); if (ret == SQL_ERROR || Sql_NumRows(SqlHandle) == 0) { ShowError("spawnMonstersForBcnm : SQL error - Cannot find any monster IDs for BCNMID %i Battlefield %i \n", battlefield->getID(), battlefield->getBattlefieldNumber()); } else{ while(Sql_NextRow(SqlHandle) == SQL_SUCCESS){ uint32 mobid = Sql_GetUIntData(SqlHandle,0); uint8 condition = Sql_GetUIntData(SqlHandle,1); CMobEntity* PMob = (CMobEntity*)zoneutils::GetEntity(mobid, TYPE_MOB); if (PMob != NULL) { PMob->m_battlefieldID = battlefield->getBattlefieldNumber(); PMob->m_bcnmID = battlefield->getID(); if (condition & CONDITION_SPAWNED_AT_START) { // This condition is needed for some mob at dynamis, else he don't pop if(PMob->PBattleAI->GetCurrentAction() == ACTION_FADE_OUT){ PMob->PBattleAI->SetLastActionTime(0); PMob->PBattleAI->SetCurrentAction(ACTION_NONE); } if (PMob->PBattleAI->GetCurrentAction() == ACTION_NONE || PMob->PBattleAI->GetCurrentAction() == ACTION_SPAWN) { PMob->PBattleAI->SetLastActionTime(0); PMob->PBattleAI->SetCurrentAction(ACTION_SPAWN); if(strcmp(PMob->GetName(),"Maat")==0){ mobutils::SetupMaat(PMob, (JOBTYPE)battlefield->getPlayerMainJob()); PMob->m_DropID = 4485; //Give Maat his stealable Warp Scroll // disable players subjob battlefield->disableSubJob(); // disallow subjob, this will enable for later battlefield->m_RuleMask &= ~(1 << RULES_ALLOW_SUBJOBS); } //ShowDebug("Spawned %s (%u) id %i inst %i \n",PMob->GetName(),PMob->id,battlefield->getID(),battlefield->getBattlefieldNumber()); battlefield->addEnemy(PMob, condition); } else { ShowDebug(CL_CYAN"SpawnMobForBcnm: <%s> (%u) is alredy spawned\n" CL_RESET, PMob->GetName(), PMob->id); } } else { battlefield->addEnemy(PMob, condition); } } else { ShowDebug("SpawnMobForBcnm: mob %u not found\n", mobid); } } return true; } return false; } /*************************************************************** Spawns treasure chest/armory crate, what ever on winning bcnm ****************************************************************/ bool spawnTreasureForBcnm(CBattlefield* battlefield){ DSP_DEBUG_BREAK_IF(battlefield==NULL); //get ids from DB const int8* fmtQuery = "SELECT npcId \ FROM bcnm_treasure_chests \ WHERE bcnmId = %u AND battlefieldNumber = %u"; int32 ret = Sql_Query(SqlHandle, fmtQuery, battlefield->getID(), battlefield->getBattlefieldNumber()); if (ret == SQL_ERROR || Sql_NumRows(SqlHandle) == 0) { ShowError("spawnTreasureForBcnm : SQL error - Cannot find any npc IDs for BCNMID %i Battlefield %i \n", battlefield->getID(), battlefield->getBattlefieldNumber()); } else { while(Sql_NextRow(SqlHandle) == SQL_SUCCESS) { uint32 npcid = Sql_GetUIntData(SqlHandle,0); CBaseEntity* PNpc = (CBaseEntity*)zoneutils::GetEntity(npcid, TYPE_NPC); if (PNpc != NULL) { PNpc->status = STATUS_NORMAL; PNpc->animation = 0; PNpc->loc.zone->PushPacket(PNpc, CHAR_INRANGE, new CEntityUpdatePacket(PNpc, ENTITY_SPAWN, UPDATE_ALL)); battlefield->addNpc(PNpc); ShowDebug(CL_CYAN"Spawned %s id %i inst %i \n",PNpc->status,PNpc->id,battlefield->getBattlefieldNumber()); }else { ShowDebug(CL_CYAN"spawnTreasureForBcnm: <%s> is already spawned\n" CL_RESET, PNpc->GetName()); } } return true; } return false; } /************************************************************** Called by ALL BCNMs to check winning conditions every tick. This is usually when all the monsters are defeated but can be other things (e.g. mob below X% HP, successful Steal, etc) ***************************************************************/ bool meetsWinningConditions(CBattlefield* battlefield, uint32 tick){ if (battlefield->won()) return true; //handle odd cases e.g. stop fight @ x% HP //handle Maat fights if(battlefield->locked && (battlefield->m_RuleMask & RULES_MAAT)) { // survive for 5 mins if(battlefield->getPlayerMainJob() == JOB_WHM && (tick - battlefield->fightTick) > 5 * 60 * 1000) return true; if(battlefield->isEnemyBelowHPP(10)) return true; if(battlefield->getPlayerMainJob() == JOB_THF && battlefield->m_EnemyList.at(0)->m_ItemStolen) //thf can win by stealing from maat only if maat not previously defeated { const int8* fmtQuery = "SELECT value FROM char_vars WHERE charid = %u AND varname = '%s' LIMIT 1;"; int32 ret = Sql_Query(SqlHandle,fmtQuery,battlefield->m_PlayerList.at(0)->id, "maatDefeated"); if(ret != SQL_ERROR && Sql_NumRows(SqlHandle) == 0) return true; else if(ret != SQL_ERROR && Sql_NumRows(SqlHandle) != 0 && Sql_NextRow(SqlHandle) == SQL_SUCCESS) { int16 value = (int16)Sql_GetIntData(SqlHandle,0); if(value <= 0) return true; } } } // savage if(battlefield->getID() == 961 && battlefield->isEnemyBelowHPP(30)){ return true; } //generic cases, kill all mobs if(battlefield->allEnemiesDefeated()){ return true; } return false; } /************************************************************** Called by ALL BCNMs to check losing conditions every tick. This will be when everyone is dead and the death timer is >3min (usually) or when everyone has left, etc. ****************************************************************/ bool meetsLosingConditions(CBattlefield* battlefield, uint32 tick){ if (battlefield->lost()) return true; //check for expired duration e.g. >30min. Need the tick>start check as the start can be assigned //after the tick initially due to threading if(tick>battlefield->getStartTime() && (tick - battlefield->getStartTime()) > battlefield->getTimeLimit()*1000){ ShowDebug("BCNM %i inst:%i - You have exceeded your time limit!\n",battlefield->getID(), battlefield->getBattlefieldNumber(),tick,battlefield->getStartTime(),battlefield->getTimeLimit()); return true; } battlefield->lastTick = tick; //check for all dead for 3min (or whatever the rule mask says) if(battlefield->getDeadTime()!=0){ if(battlefield->m_RuleMask & RULES_REMOVE_3MIN){ // if(((tick - battlefield->getDeadTime())/1000) % 20 == 0){ // battlefield->pushMessageToAllInBcnm(200,180 - (tick - battlefield->getDeadTime())/1000); // } if(tick - battlefield->getDeadTime() > 180000){ ShowDebug("All players from the battlefield %i inst:%i have fallen for 3mins. Removing.\n", battlefield->getID(),battlefield->getBattlefieldNumber()); return true; } } else{ ShowDebug("All players have fallen. Failed battlefield %i inst %i. No 3min mask. \n",battlefield->getID(),battlefield->getBattlefieldNumber()); return true; } } return false; } /************************************************************* Returns the losing exit position for this BCNM. ****************************************************************/ void getLosePosition(CBattlefield* battlefield, int (&pPosition)[4]){ if(battlefield==NULL) return; switch(battlefield->getZoneId()){ case 139: //Horlais Peak pPosition[0]=-503; pPosition[1]=158; pPosition[2]=-212; pPosition[3]=131; break; } } void getStartPosition(uint8 zoneid, int (&pPosition)[4]){ switch(zoneid){ case 139: //Horlais Peak pPosition[0]=-503; pPosition[1]=158; pPosition[2]=-212; pPosition[3]=131; break; case 144: //Waug. Shrine pPosition[0]=-361; pPosition[1]=100; pPosition[2]=-260; pPosition[3]=131; break; case 146: //Balgas Dias pPosition[0]=317; pPosition[1]=-126; pPosition[2]=380; pPosition[3]=131; break; case 165: //Throne Room pPosition[0]=114; pPosition[1]=-8; pPosition[2]=0; pPosition[3]=131; break; case 206: //QuBia Arena pPosition[0]=-241; pPosition[1]=-26; pPosition[2]=20; pPosition[3]=131; break; } } /************************************************************* Returns the winning exit position for this BCNM. ****************************************************************/ void getWinPosition(CBattlefield* battlefield, int (&pPosition)[4]){ if(battlefield==NULL) return; switch(battlefield->getZoneId()){ case 139: //Horlais Peak pPosition[0]=445; pPosition[1]=-38; pPosition[2]=-19; pPosition[3]=200; break; } } uint8 getMaxLootGroups(CBattlefield* battlefield){ const int8* fmtQuery = "SELECT MAX(lootGroupId) \ FROM bcnm_loot \ JOIN bcnm_info ON bcnm_info.LootDropId = bcnm_loot.LootDropId \ WHERE bcnm_info.LootDropId = %u LIMIT 1"; int32 ret = Sql_Query(SqlHandle, fmtQuery, battlefield->getLootId()); if (ret == SQL_ERROR || Sql_NumRows(SqlHandle) == 0 || Sql_NextRow(SqlHandle) != SQL_SUCCESS){ ShowError("SQL error occured \n"); return 0; } else { return (uint8)Sql_GetUIntData(SqlHandle,0); } } uint16 getRollsPerGroup(CBattlefield* battlefield, uint8 groupID){ const int8* fmtQuery = "SELECT SUM(CASE \ WHEN LootDropID = %u \ AND lootGroupId = %u \ THEN rolls \ ELSE 0 END) \ FROM bcnm_loot;"; int32 ret = Sql_Query(SqlHandle, fmtQuery, battlefield->getLootId(), groupID); if (ret == SQL_ERROR || Sql_NumRows(SqlHandle) == 0 || Sql_NextRow(SqlHandle) != SQL_SUCCESS){ ShowError("SQL error occured \n"); return 0; } else { return (uint16)Sql_GetUIntData(SqlHandle,0); } } /************************************************************* Get loot from the armoury crate ****************************************************************/ void getChestItems(CBattlefield* battlefield){ int instzone = battlefield->getZoneId(); uint8 maxloot = 0; LootList_t* LootList = itemutils::GetLootList(battlefield->getLootId()); if (LootList == NULL){ ShowError("BCNM Chest opened with no valid loot list!"); //no loot available for bcnm. End bcnm. battlefield->winBcnm(); return; } else { for (uint8 sizeoflist=0; sizeoflist < LootList->size() ; ++sizeoflist){ if(LootList->at(sizeoflist).LootGroupId > maxloot){ maxloot= LootList->at(sizeoflist).LootGroupId; } } } //getMaxLootGroups(battlefield); if(maxloot!=0){ for (uint8 group = 0; group <= maxloot; ++group){ uint16 maxRolls = getRollsPerGroup(battlefield,group); uint16 groupRoll = (uint16)(WELL512::irand()%maxRolls); uint16 itemRolls = 0; for (uint8 item = 0; item < LootList->size(); ++item) { if (group == LootList->at(item).LootGroupId) { itemRolls += LootList->at(item).Rolls; if (groupRoll <= itemRolls) { battlefield->m_PlayerList.at(0)->PTreasurePool->AddItem(LootList->at(item).ItemID, battlefield->m_NpcList.at(0)); break; } } } } } //user opened chest, complete bcnm if(instzone!=37 && instzone!=38 ){ battlefield->winBcnm(); } else{ battlefield->m_NpcList.clear(); } } bool spawnSecondPartDynamis(CBattlefield* battlefield){ DSP_DEBUG_BREAK_IF(battlefield==NULL); //get ids from DB const int8* fmtQuery = "SELECT monsterId \ FROM bcnm_battlefield \ WHERE bcnmId = %u AND battlefieldNumber = 2"; int32 ret = Sql_Query(SqlHandle, fmtQuery, battlefield->getID()); if (ret == SQL_ERROR || Sql_NumRows(SqlHandle) == 0) { ShowError("spawnSecondPartDynamis : SQL error - Cannot find any monster IDs for Dynamis %i \n", battlefield->getID(), battlefield->getBattlefieldNumber()); } else{ while(Sql_NextRow(SqlHandle) == SQL_SUCCESS){ uint32 mobid = Sql_GetUIntData(SqlHandle,0); CMobEntity* PMob = (CMobEntity*)zoneutils::GetEntity(mobid, TYPE_MOB); if (PMob != NULL) { if (PMob->PBattleAI->GetCurrentAction() == ACTION_NONE || PMob->PBattleAI->GetCurrentAction() == ACTION_SPAWN) { PMob->PBattleAI->SetLastActionTime(0); PMob->PBattleAI->SetCurrentAction(ACTION_SPAWN); PMob->m_battlefieldID = battlefield->getBattlefieldNumber(); ShowDebug("Spawned %s (%u) id %i inst %i \n",PMob->GetName(),PMob->id,battlefield->getID(),battlefield->getBattlefieldNumber()); battlefield->addEnemy(PMob, CONDITION_SPAWNED_AT_START & CONDITION_WIN_REQUIREMENT); } else { ShowDebug(CL_CYAN"spawnSecondPartDynamis: <%s> (%u) is alredy spawned\n" CL_RESET, PMob->GetName(), PMob->id); } } else { ShowDebug("spawnSecondPartDynamis: mob %u not found\n", mobid); } } return true; } return false; } };
maikuru23/darkstar
src/map/utils/battlefieldutils.cpp
C++
gpl-3.0
15,998
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // Fichier source, a modifier dans svn://zone.spip.org/spip-zone/_plugins_/seo/lang/ if (!defined('_ECRIRE_INC_VERSION')) return; $GLOBALS[$GLOBALS['idx_lang']] = array( // S 'S.E.O' => 'SEO', // A 'alexa' => 'Alexa', 'alexa_activate' => 'Activer Alexa', 'alexa_id' => 'Identifiant du site pour Alexa', // B 'bing_webmaster' => 'Bing Webmaster Tools', 'bing_webmaster_activate' => 'Activer Bing Webmaster Tools', 'bing_webmaster_id' => 'Meta code de vérification', // C 'canonical_url' => 'URL Canoniques', 'canonical_url_activate' => 'Activer les URL Canoniques', // F 'forcer_squelette_descriptif' => 'Les metas SEO sont prioritaires aux meta générées par les squelettes', 'forcer_squelette_label' => 'Charger les metas pour tous squelettes', // G 'google_analytics' => 'Google Analytics', 'google_analytics_activate' => 'Activer Analytics', 'google_analytics_id' => 'Google Analytics web property ID', 'google_webmaster_tools' => 'Google Webmaster Tools', 'google_webmaster_tools_activate' => 'Activer Webmaster Tools', 'google_webmaster_tools_id' => 'Meta code de vérification', // I 'insert_head' => 'Insertion automatique dans #INSERT_HEAD', 'insert_head_activate' => 'Activer l\'insertion automatique', 'insert_head_descriptif' => 'Insertion automatique de la configuration SEO dans le &lt;header&gt;', // M 'meta_author' => 'Auteur :', 'meta_copyright' => 'Copyright :', 'meta_description' => 'Description :', 'meta_keywords' => 'Mots Clefs :', 'meta_page_description_sommaire_value' => 'Valeur de la Description de la Page + Valeur Meta du Sommaine', 'meta_page_description_value' => 'Valeur de la Description de la Page', 'meta_page_title_sommaire_value' => 'Valeur du Titre de la Page + Valeur Meta du Sommaire', 'meta_page_title_value' => 'Valeur du Titre de la Page', 'meta_robots' => 'Robots :', 'meta_sommaire_value' => 'Valeur de la Meta du Sommaire', 'meta_tags' => 'Meta Tags', 'meta_tags_activate' => 'Activer les meta tags', 'meta_tags_default' => 'Valeur des Meta Tags par Défaut (pour les Articles et les Rubriques)', 'meta_tags_edit_activate' => 'Activer l\'édition des meta tags dans les rubriques et les articles', 'meta_tags_editing' => 'Edition des Meta Tags', 'meta_tags_sommaire' => 'Valeur des Meta Tags du Sommaire (page d\'accueil)', 'meta_title' => 'Titre :', // S 'seo' => 'Search Engine Optimisation' ); ?>
VertigeASBL/genrespluriels
plugins/seo-v1/lang/seo_fr.php
PHP
gpl-3.0
2,485
/* * Copyright (C) 2017 GG-Net GmbH * * 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/>. */ /** * Contains the Ui and actions for the detailed document view and edit and all supplemental uis. */ package eu.ggnet.dwoss.redtapext.ui.cao.document;
gg-net/dwoss
ui/redtapext/src/main/java/eu/ggnet/dwoss/redtapext/ui/cao/document/package-info.java
Java
gpl-3.0
865
using System; using System.Threading; using Viki.LoadRunner.Engine.Core.Scenario.Interfaces; using Viki.LoadRunner.Engine.Strategies.Replay.Interfaces; using Viki.LoadRunner.Engine.Strategies.Replay.Scheduler.Interfaces; namespace Viki.LoadRunner.Playground.Replay { public class ReplayScenario : IReplayScenario<string> { private string _data; private TimeSpan _target = TimeSpan.Zero; public void ScenarioSetup(IIteration context) { Console.Out.WriteLine($"[{context.Timer.Value.TotalSeconds:F2}] Scenario Setup"); } public void SetData(IData<string> data) { _data = data.Value; _target = data.TargetTime; // Lets skip requests between 4-8 seconds if (data.TargetTime > TimeSpan.FromSeconds(4) && data.TargetTime < TimeSpan.FromSeconds(8)) { Console.Out.WriteLine($"[{data.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] SetData: [{_data}] SKIP"); data.Execute = false; data.Context.UserData = $"[{data.Context.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] SKIP"; } TimeSpan fallenBehind = data.Timer.Value - data.TargetTime; if (fallenBehind > TimeSpan.Zero) Console.WriteLine($@"[{data.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] SetData: [{_data}] FALL BEHIND {fallenBehind}"); Console.Out.WriteLine($"[{data.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] SetData: [{_data}]"); } public void IterationSetup(IIteration context) { context.UserData = _data; Console.Out.WriteLine($"[{context.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] Iteration Setup"); } public void ExecuteScenario(IIteration context) { Console.Out.WriteLine($"[{context.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] Execute"); Thread.Sleep(1000); } public void IterationTearDown(IIteration context) { Console.Out.WriteLine($"[{context.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] Iteration End"); } public void ScenarioTearDown(IIteration context) { Console.Out.WriteLine($"[{context.Timer.Value.TotalSeconds:F2}][A:{_target.TotalSeconds:F2}] Scenario End"); } } }
Vycka/LoadRunner
src/Viki.LoadRunner.Playground/Replay/ReplayScenario.cs
C#
gpl-3.0
2,474
#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result if __name__ == '__main__': print(serial_ports())
Mobleyta/GasChromino
PythonCode/serial_ports.py
Python
gpl-3.0
1,189
function Greeter(person) { return "Hello, " + person; } var RandomGuy = "Random Dude"; alert(Greeter(RandomGuy)); //# sourceMappingURL=HelloWorld.js.map
LenardHessHAW/TypeScriptTesting
JavaScript/HelloWorld.js
JavaScript
gpl-3.0
156
<?php namespace sebastiangolian\php\logger; /* Logger::getInstance()->addDefaultLog('test'); Logger::getInstance()->addLog(new Message('type', 'message')); echo Logger::getInstance()->generateAllMessages(); */ class Logger { private static $instance; private $messages = []; private function __construct() {} private function __clone() {} /** * @return Logger */ public static function getInstance() { if(self::$instance === null) { self::$instance = new self; } return self::$instance; } /** * Logger::getInstance()->add('XYZ'); * Add new log * @param mixed $var * @param string $type */ public function add($var,$type = 'default') { $message = print_r($var, true); $objMessage = new Message($type, $message); array_push($this->messages, $objMessage); } /** * Return all messages * @return array */ public function getMessages() { return $this->messages; } /** * Return all messages in string with break * @param string $break * @return string */ public function generateAllMessages($break = "<br />") { $ret = ''; foreach ($this->messages as $message) { $ret .= $message->getDateTime()." - [".$message->getType()."] ".$message->getMessage().$break; } return $ret; } }
sebastiangolian/php
logger/Logger.php
PHP
gpl-3.0
1,533
/** * This file defines the fitness_params object. * * TODOs: * - a few TODOs in the file but ok * * FINISHED! * */ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using toolbox; /** * namespace for biogas plant optimization * * Definition of: * - fitness_params * - objective function * - weights used inside objective function * */ namespace biooptim { /// <summary> /// definition of fitness parameters used in objective function /// </summary> public partial class fitness_params { // ------------------------------------------------------------------------------------- // !!! CONSTRUCTOR METHODS !!! // ------------------------------------------------------------------------------------- /// <summary> /// Standard Constructor creates the fitness_params object with default params /// </summary> /// <param name="numDigesters">number of digesters on plant</param> public fitness_params(int numDigesters/*biogas.plant myPlant*/) { set_params_to_default(/*myPlant*/numDigesters); } /// <summary> /// Constructor used to read fitness_params out of a XML file /// </summary> /// <param name="XMLfile">name of the xml file</param> public fitness_params(string XMLfile) { XmlTextReader reader= new System.Xml.XmlTextReader(XMLfile); getParamsFromXMLReader(ref reader); reader.Close(); } // ------------------------------------------------------------------------------------- // !!! PUBLIC METHODS !!! // ------------------------------------------------------------------------------------- /// <summary> /// set fitness params to values read out of a xml file /// </summary> /// <param name="reader"></param> public void getParamsFromXMLReader(ref XmlTextReader reader) { string xml_tag = ""; int digester_index = 0; // do not set params, because plant is not known // TODO - macht probleme wenn ein neuer parameter hinzugefügt wird, da dann // dessen list leer bleibt // im grunde müsste man am ende der funktion die listen füllen, welche // leer geblieben sind mit default werten bool do_while = true; // go through the file while (reader.Read() && do_while) { switch (reader.NodeType) { case System.Xml.XmlNodeType.Element: // this knot is an element xml_tag = reader.Name; while (reader.MoveToNextAttribute()) { // read the attributes, here only the attribute of digester // is of interest, all other attributes are ignored, // actually there usally are no other attributes if (xml_tag == "digester" && reader.Name == "index") { // TODO // index of digester, not used at the moment digester_index = Convert.ToInt32(reader.Value); break; } } if (xml_tag == "weights") { myWeights.getParamsFromXMLReader(ref reader); } else if (xml_tag == "setpoints") { mySetpoints.getParamsFromXMLReader(ref reader); } break; case System.Xml.XmlNodeType.Text: // text, thus value, of each element switch (xml_tag) { // TODO - use digester_index here, compare with size of pH_min, ... // here we assume that params are given in the correct // order, thus first the first digester, then the 2nd digester, ... case "pH_min": pH_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "pH_max": pH_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "pH_optimum": pH_optimum.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "TS_max": TS_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "VFA_TAC_min": VFA_TAC_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "VFA_TAC_max": VFA_TAC_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "VFA_min": VFA_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "VFA_max": VFA_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "TAC_min": TAC_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "HRT_min": HRT_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "HRT_max": HRT_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "OLR_max": OLR_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "Snh4_max": Snh4_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "Snh3_max": Snh3_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "AcVsPro_min": AcVsPro_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value)); break; case "TS_feed_max": _TS_feed_max= System.Xml.XmlConvert.ToDouble(reader.Value); break; case "HRT_plant_min": _HRT_plant_min = System.Xml.XmlConvert.ToDouble(reader.Value); break; case "HRT_plant_max": _HRT_plant_max = System.Xml.XmlConvert.ToDouble(reader.Value); break; case "OLR_plant_max": _OLR_plant_max = System.Xml.XmlConvert.ToDouble(reader.Value); break; // read in manurebonus case "manurebonus": _manurebonus = System.Xml.XmlConvert.ToBoolean(reader.Value); break; case "fitness_function": _fitness_function = reader.Value; break; case "nObjectives": _nObjectives = System.Xml.XmlConvert.ToInt32(reader.Value); break; //case "Ndelta": // _Ndelta = System.Xml.XmlConvert.ToInt32(reader.Value); // break; } break; case System.Xml.XmlNodeType.EndElement: // end of fitness_params if (reader.Name == "fitness_params") do_while = false; // end while loop break; } } } /// <summary> /// Returns fitness params as XML string, such that it can be saved /// in a XML file /// </summary> /// <returns></returns> public string getParamsAsXMLString() { StringBuilder sb = new StringBuilder(); sb.Append("<fitness_params>\n"); for (int idigester = 0; idigester < pH_min.Count; idigester++) { sb.Append(String.Format("<digester index= \"{0}\">\n", idigester)); sb.Append(xmlInterface.setXMLTag("pH_min", pH_min[idigester])); sb.Append(xmlInterface.setXMLTag("pH_max", pH_max[idigester])); sb.Append(xmlInterface.setXMLTag("pH_optimum", pH_optimum[idigester])); sb.Append(xmlInterface.setXMLTag("TS_max", TS_max[idigester])); sb.Append(xmlInterface.setXMLTag("VFA_TAC_min", VFA_TAC_min[idigester])); sb.Append(xmlInterface.setXMLTag("VFA_TAC_max", VFA_TAC_max[idigester])); sb.Append(xmlInterface.setXMLTag("VFA_min", VFA_min[idigester])); sb.Append(xmlInterface.setXMLTag("VFA_max", VFA_max[idigester])); sb.Append(xmlInterface.setXMLTag("TAC_min", TAC_min[idigester])); sb.Append(xmlInterface.setXMLTag("HRT_min", HRT_min[idigester])); sb.Append(xmlInterface.setXMLTag("HRT_max", HRT_max[idigester])); sb.Append(xmlInterface.setXMLTag("OLR_max", OLR_max[idigester])); sb.Append(xmlInterface.setXMLTag("Snh4_max", Snh4_max[idigester])); sb.Append(xmlInterface.setXMLTag("Snh3_max", Snh3_max[idigester])); sb.Append(xmlInterface.setXMLTag("AcVsPro_min", AcVsPro_min[idigester])); sb.Append("</digester>\n"); } sb.Append(xmlInterface.setXMLTag("TS_feed_max", TS_feed_max)); // add weights sb.Append(myWeights.getParamsAsXMLString()); sb.Append(xmlInterface.setXMLTag("HRT_plant_min", HRT_plant_min)); sb.Append(xmlInterface.setXMLTag("HRT_plant_max", HRT_plant_max)); sb.Append(xmlInterface.setXMLTag("OLR_plant_max", OLR_plant_max)); // write manurebonus inside file sb.Append(xmlInterface.setXMLTag("manurebonus", manurebonus)); sb.Append(xmlInterface.setXMLTag("fitness_function", fitness_function)); sb.Append(xmlInterface.setXMLTag("nObjectives", nObjectives)); //sb.Append(xmlInterface.setXMLTag("Ndelta", _Ndelta)); // add setpoints sb.Append(mySetpoints.getParamsAsXMLString()); // sb.Append("</fitness_params>\n"); return sb.ToString(); } /// <summary> /// Saves the fitness_params in a xml file /// </summary> /// <param name="XMLfile">name of the xml file</param> public void saveAsXML(string XMLfile) { StreamWriter writer = File.CreateText(XMLfile); writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); writer.Write(getParamsAsXMLString()); writer.Close(); } /// <summary> /// Prints the fitness params to a string, such that the string /// can be written to a console. /// /// For Custom Numeric Format Strings see: /// /// http://msdn.microsoft.com/en-us/library/0c899ak8.aspx /// /// </summary> /// <returns></returns> public string print() { StringBuilder sb = new StringBuilder(); sb.Append(" ---------- fitness_params: ---------- \r\n"); for (int idigester = 0; idigester < pH_min.Count; idigester++) { sb.Append(String.Format("digester: {0}\n", idigester)); sb.Append(String.Format("pH_min: {0}\t\t\t", pH_min[idigester])); sb.Append(String.Format("pH_max: {0}\t\t\t", pH_max[idigester])); sb.Append(String.Format("pH_optimum: {0}\n", pH_optimum[idigester])); sb.Append(String.Format("TS_max: {0}\t\t\t", TS_max[idigester])); sb.Append(String.Format("VFA_TAC_min: {0}\t\t\t", VFA_TAC_min[idigester])); sb.Append(String.Format("VFA_TAC_max: {0}\n", VFA_TAC_max[idigester])); sb.Append(String.Format("VFA_min: {0}\t\t\t", VFA_min[idigester])); sb.Append(String.Format("VFA_max: {0}\t\t\t", VFA_max[idigester])); sb.Append(String.Format("TAC_min: {0}\n", TAC_min[idigester])); sb.Append(String.Format("HRT_min: {0}\t\t\t", HRT_min[idigester])); sb.Append(String.Format("HRT_max: {0}\t\t\t", HRT_max[idigester])); sb.Append(String.Format("OLR_max: {0}\n", OLR_max[idigester])); sb.Append(String.Format("Snh4_max: {0}\t\t\t", Snh4_max[idigester])); sb.Append(String.Format("Snh3_max: {0}\t\t\t", Snh3_max[idigester])); sb.Append(String.Format("AcVsPro_min: {0}\r\n", AcVsPro_min[idigester])); } sb.Append(String.Format("TS_feed_max: {0}\r\n", TS_feed_max)); // add weights sb.Append(myWeights.print()); sb.Append(String.Format("\nHRT_plant_min: {0}\t\t\t", HRT_plant_min)); sb.Append(String.Format("HRT_plant_max: {0}\t\t\t", HRT_plant_max)); sb.Append(String.Format("OLR_plant_max: {0}\n", OLR_plant_max)); sb.Append(String.Format("manurebonus: {0}\n", manurebonus)); sb.Append(String.Format("fitness_function: {0}\t\t", fitness_function)); sb.Append(String.Format("nObjectives: {0}\r\n", nObjectives)); //sb.Append(String.Format("Ndelta: {0}\n", _Ndelta)); // add setpoints sb.Append(mySetpoints.print()); sb.Append(" ---------- ---------- ---------- ---------- \n"); return sb.ToString(); } } }
dgaida/matlab_toolboxes
biogas_c#/scripts/scripts/toolbox/optim_params/fitness_params.cs
C#
gpl-3.0
12,539
/* _ _ _ _ ___| (_) ___| | __ (_)___ / __| | |/ __| |/ / | / __| \__ \ | | (__| < _ | \__ \ |___/_|_|\___|_|\_(_)/ |___/ |__/ Version: 1.8.1 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 class="slick-prev" aria-label="Previous" type="button">Previous</button>', nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>', autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', customPaging: function(slider, i) { return $('<button type="button" />').text(i + 1); }, dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, focusOnChange: 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, scrolling: false, slideCount: null, slideWidth: null, $slideTrack: null, $slides: null, sliding: false, slideOffset: 0, swipeLeft: null, swiping: false, $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'); } }; 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 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 > 0) { 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)); if (_.options.accessibility === true) { _.$dots.off('keydown.slick', _.keyHandler); } } _.$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); if (_.options.accessibility === true) { _.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler); _.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler); } } _.$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); }; 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 > 0) { 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', '*', 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) { if (_.slideCount <= _.options.slidesToShow) { ++pagerQty; } else { 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, coef; _.slideOffset = 0; verticalHeight = _.$slides.first().outerHeight(true); if (_.options.infinite === true) { if (_.slideCount > _.options.slidesToShow) { _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1; coef = -1 if (_.options.vertical === true && _.options.centerMode === true) { if (_.options.slidesToShow === 2) { coef = -1.5; } else if (_.options.slidesToShow === 1) { coef = -2 } } verticalOffset = (verticalHeight * _.options.slidesToShow) * coef; } 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 && _.slideCount <= _.options.slidesToShow) { _.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2); } else 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; } var fs = 0; while (breakPoint < max) { indexes.push(breakPoint); breakPoint = counter + _.options.slidesToScroll; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; fs++; if ( fs > 200 ) { console.log( 'WARNING! Infinite loop!' ); break; } } 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, numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow), tabControlIndexes = _.getNavigableIndexes().filter(function(val) { return (val >= 0) && (val < _.slideCount); }); _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({ 'aria-hidden': 'true', 'tabindex': '-1' }).find('a, input, button, select').attr({ 'tabindex': '-1' }); if (_.$dots !== null) { _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) { var slideControlIndex = tabControlIndexes.indexOf(i); $(this).attr({ 'role': 'tabpanel', 'id': 'slick-slide' + _.instanceUid + i, 'tabindex': -1 }); if (slideControlIndex !== -1) { var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex if ($('#' + ariaButtonControl).length) { $(this).attr({ 'aria-describedby': ariaButtonControl }); } } }); _.$dots.attr('role', 'tablist').find('li').each(function(i) { var mappedSlideIndex = tabControlIndexes[i]; $(this).attr({ 'role': 'presentation' }); $(this).find('button').first().attr({ 'role': 'tab', 'id': 'slick-slide-control' + _.instanceUid + i, 'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex, 'aria-label': (i + 1) + ' of ' + numDotGroups, 'aria-selected': null, 'tabindex': '-1' }); }).eq(_.currentSlide).find('button').attr({ 'aria-selected': 'true', 'tabindex': '0' }).end(); } for (var i=_.currentSlide, max=i+_.options.slidesToShow; i < max; i++) { if (_.options.focusOnChange) { _.$slides.eq(i).attr({'tabindex': '0'}); } else { _.$slides.eq(i).removeAttr('tabindex'); } } _.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); if (_.options.accessibility === true) { _.$prevArrow.on('keydown.slick', _.keyHandler); _.$nextArrow.on('keydown.slick', _.keyHandler); } } }; Slick.prototype.initDotEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).on('click.slick', { message: 'index' }, _.changeSlide); if (_.options.accessibility === true) { _.$dots.on('keydown.slick', _.keyHandler); } } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) { $('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); $(_.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'), imageSrcSet = $(this).attr('data-srcset'), imageSizes = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'), imageToLoad = document.createElement('img'); imageToLoad.onload = function() { image .animate({ opacity: 0 }, 100, function() { if (imageSrcSet) { image .attr('srcset', imageSrcSet ); if (imageSizes) { image .attr('sizes', imageSizes ); } } image .attr('src', imageSource) .animate({ opacity: 1 }, 200, function() { image .removeAttr('data-lazy data-srcset data-sizes') .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); if (_.options.lazyLoad === 'anticipated') { var prevSlide = rangeStart - 1, nextSlide = rangeEnd, $slides = _.$slider.find('.slick-slide'); for (var i = 0; i < _.options.slidesToScroll; i++) { if (prevSlide < 0) prevSlide = _.slideCount - 1; loadRange = loadRange.add($slides.eq(prevSlide)); loadRange = loadRange.add($slides.eq(nextSlide)); prevSlide--; nextSlide++; } } 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; if (_.slideCount > _.options.slidesToShow) { _.setPosition(); } _.swipeLeft = null; if ( _.options.autoplay ) { _.autoPlay(); } if (_.options.accessibility === true) { _.initADA(); if (_.options.focusOnChange) { var $currentSlide = $(_.$slides.get(_.currentSlide)); $currentSlide.attr('tabindex', 0).focus(); } } } }; 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, imageSrcSet, imageSizes, imageToLoad; if ( $imgsToLoad.length ) { image = $imgsToLoad.first(); imageSource = image.attr('data-lazy'); imageSrcSet = image.attr('data-srcset'); imageSizes = image.attr('data-sizes') || _.$slider.attr('data-sizes'); imageToLoad = document.createElement('img'); imageToLoad.onload = function() { if (imageSrcSet) { image .attr('srcset', imageSrcSet ); if (imageSizes) { image .attr('sizes', imageSizes ); } } image .attr( 'src', imageSource ) .removeAttr('data-lazy data-srcset data-sizes') .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; if (responsiveSettings.hasOwnProperty(breakpoint)) { currentBreakpoint = responsiveSettings[breakpoint].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) { _.slideWidth = Math.ceil(_.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) { var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0; centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.infinite === true) { if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) { _.$slides .slice(index - centerOffset + evenCoef, index + centerOffset + 1) .addClass('slick-active') .attr('aria-hidden', 'false'); } else { indexOffset = _.options.slidesToShow + index; allSlides .slice(indexOffset - centerOffset + 1 + evenCoef, 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' || _.options.lazyLoad === 'anticipated') { _.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 + _.slideCount; 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) { _.slideHandler(index, false, true); 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 (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 && _.slideCount > _.options.slidesToShow) { _.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 && _.slideCount > _.options.slidesToShow) { _.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 && _.slideCount > _.options.slidesToShow) { _.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; _.swiping = false; if (_.scrolling) { _.scrolling = false; return 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, verticalSwipeLength; touches = event.originalEvent !== undefined ? event.originalEvent.touches : null; if (!_.dragging || _.scrolling || 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))); verticalSwipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curY - _.touchObject.startY, 2))); if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) { _.scrolling = true; return false; } if (_.options.verticalSwiping === true) { _.touchObject.swipeLength = verticalSwipeLength; } swipeDirection = _.swipeDirection(); if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) { _.swiping = true; 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') .end(); _.$dots .find('li') .eq(Math.floor(_.currentSlide / _.options.slidesToScroll)) .addClass('slick-active'); } }; 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 _; }; $( document ).ready(function() { $( '.exopite-multifilter-items.slick-carousel' ).each(function ( idx, item ) { var carouselId = "slick-carousel" + idx; var data = $( this ).parent( '.exopite-multifilter-container' ).data( 'carousel' ); if ( typeof data !== "undefined" ) { this.id = carouselId; $( this ).slick({ autoplay: ( data.autoplay === 'false' ) ? false : true, arrows: ( data.arrows === 'false' ) ? false : true, autoplaySpeed: data.autoplay_speed, infinite: ( data.infinite === 'false' ) ? false : true, speed: parseInt( data.speed ), pauseOnHover: ( data.pause_on_hover === 'false' ) ? false : true, dots: ( data.dots === 'false' ) ? false : true, adaptiveHeight: ( data.adaptive_height === 'false' ) ? false : true, mobileFirst: ( data.mobile_first === 'false' ) ? false : true, slidesPerRow: parseInt( data.slides_per_row ), slidesToShow: parseInt( data.slides_to_show ), slidesToScroll: parseInt( data.slides_to_scroll ), useTransform: ( data.use_transform === 'false' ) ? false : true, }); } }); }); }));
JoeSz/exopite-multifilter
exopite-multifilter/public/js/slick.dev.js
JavaScript
gpl-3.0
90,524
namespace BarionClientLibrary.Operations.Common { public class ShippingAddress { public string Country { get; set; } public string City { get; set; } public string Region { get; set; } public string Zip { get; set; } public string Street { get; set; } public string Street2 { get; set; } public string Street3 { get; set; } public string FullName { get; set; } } }
szelpe/barion-dotnet
BarionClientLibrary/Operations/Common/ShippingAddress.cs
C#
gpl-3.0
444
#include <iostream> #include <stdexcept> #include <vector> #include "latticeBase.hpp" #include "collisionBase.hxx" #include "latticeNode.hxx" #include "latticeModel.hxx" #include "ZouHeNode.hpp" #include "latticeNode.hxx" ZouHeNode::ZouHeNode ( latticeBase &lb, collisionBase &cb, latticeModelD2Q9 &D2Q9, fluidField &field ) : boundaryNode(false, false, lb), nodes {}, cb_ (cb), is_normal_flow_ {false}, beta1_ {}, beta2_ {}, beta3_ {}, D2Q9_ (D2Q9), field_ (field) { const auto c = lb_.getLatticeSpeed(); const auto cs_sqr = c * c / 3.0; beta1_ = c / (9.0 *cs_sqr); beta2_ = 0.5 / c; beta3_ = beta2_ - beta1_; } void ZouHeNode::addNode ( std::size_t x, std::size_t y, double u_x, double u_y ) { const auto nx = lb_.getNumberOfNx(); const auto ny = lb_.getNumberOfNy(); const auto n = y * nx + x; const auto left = x == 0; const auto right = x == nx - 1; const auto bottom = y == 0; const auto top = y == ny - 1; auto edge_i = -1; if (right) edge_i = 0; if (top) edge_i = 1; if (left) edge_i = 2; if (bottom) edge_i = 3; // adds a corner node if ((top || bottom) && (left || right)) { auto corner_i = -1; if (bottom && left) corner_i = 0; if (bottom && right) corner_i = 1; if (top && left) corner_i = 2; if (top && right) corner_i = 3; nodes.push_back(latticeNode(x, y, n, u_x, u_y, true, corner_i)); } // adds a side node else { nodes.push_back(latticeNode(x, y, n, u_x, u_y, false, edge_i)); } } void ZouHeNode::updateNode ( std::vector<std::vector<double>> &df, bool is_modify_stream ) { if (!is_modify_stream) { for (auto node : nodes) { if (node.corner) { ZouHeNode::updateCorner(df, node); } else { ZouHeNode::updateEdge(df, node); } } // n } } void ZouHeNode::updateEdge ( std::vector<std::vector<double>> &df, latticeNode &node ) { const auto n = node.n_node; const auto nx = lb_.getNumberOfNx(); const auto c = lb_.getLatticeSpeed(); switch(node.index_i) { case 0: { // right auto vel = is_normal_flow_ ? field_.u[n - 1] : node.u_node; const auto rho_node = (df[n][0] + df[n][D2Q9_.N] + df[n][D2Q9_.S] + 2.0 * (df[n][D2Q9_.E] + df[n][D2Q9_.NE] + df[n][D2Q9_.SE])) / (1.0 + vel[0] / c); const auto df_diff = 0.5 * (df[n][D2Q9_.S] - df[n][D2Q9_.N]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.W] = df[n][D2Q9_.E] - 2.0 * beta1_ * vel[0]; df[n][D2Q9_.NW] = df[n][D2Q9_.SE] + df_diff - beta3_ * vel[0] + beta2_ * vel[1]; df[n][D2Q9_.SW] = df[n][D2Q9_.NE] - df_diff - beta3_ * vel[0] - beta2_ * vel[1]; break; } case 1: { // top auto vel = is_normal_flow_ ? field_.u[n - nx] : node.u_node; const auto rho_node = (df[n][0] + df[n][D2Q9_.E] + df[n][D2Q9_.W] + 2.0 * (df[n][D2Q9_.N] + df[n][D2Q9_.NE] + df[n][D2Q9_.NW])) / (1.0 + vel[1] / c); const auto df_diff = 0.5 * (df[n][D2Q9_.E] - df[n][D2Q9_.W]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.S] = df[n][D2Q9_.N] - 2.0 * beta1_ * vel[1]; df[n][D2Q9_.SW] = df[n][D2Q9_.NE] + df_diff - beta2_ * vel[0] - beta3_ * vel[1]; df[n][D2Q9_.SE] = df[n][D2Q9_.NW] - df_diff + beta2_ * vel[0] - beta3_ * vel[1]; break; } case 2: { // left auto vel = is_normal_flow_ ? field_.u[n + 1] : node.u_node; const auto rho_node = (df[n][0] + df[n][D2Q9_.N] + df[n][D2Q9_.S] + 2.0 * (df[n][D2Q9_.W] + df[n][D2Q9_.NW] + df[n][D2Q9_.SW])) / (1.0 - vel[0] / c); const auto df_diff = 0.5 * (df[n][D2Q9_.S] - df[n][D2Q9_.N]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.E] = df[n][D2Q9_.W] + 2.0 * beta1_ * vel[0]; df[n][D2Q9_.NE] = df[n][D2Q9_.SW] + df_diff + beta3_ * vel[0] + beta2_ * vel[1]; df[n][D2Q9_.SE] = df[n][D2Q9_.NW] - df_diff + beta3_ * vel[0] - beta2_ * vel[1]; break; } case 3: { // bottom auto vel = is_normal_flow_ ? field_.u[n + nx] : node.u_node; const auto rho_node = (df[n][0] + df[n][D2Q9_.E] + df[n][D2Q9_.W] + 2.0 * (df[n][D2Q9_.S] + df[n][D2Q9_.SW] + df[n][D2Q9_.SE])) / (1.0 - vel[1] / c); const auto df_diff = 0.5 * (df[n][D2Q9_.W] - df[n][D2Q9_.E]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.N] = df[n][D2Q9_.S] + 2.0 * beta1_ * vel[1]; df[n][D2Q9_.NE] = df[n][D2Q9_.SW] + df_diff + beta2_ * vel[0] + beta3_ * vel[1]; df[n][D2Q9_.NW] = df[n][D2Q9_.SE] - df_diff - beta2_ * vel[0] + beta3_ * vel[1]; break; } default: { throw std::runtime_error("Not a side"); } } } void ZouHeNode::updateCorner ( std::vector<std::vector<double>> &df, latticeNode &node ) { const auto n = node.n_node; auto vel = node.u_node; const auto nx = lb_.getNumberOfNx(); const auto nc = lb_.getNumberOfDirections(); switch (node.index_i) { case 0: { // bottom-left auto rho_node = 0.5 * (cb_.rho_[n + nx] + cb_.rho_[n + 1]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.E] = df[n][D2Q9_.W] + 2.0 * beta1_ * vel[0]; df[n][D2Q9_.N] = df[n][D2Q9_.S] + 2.0 * beta1_ * vel[1]; df[n][D2Q9_.NE] = df[n][D2Q9_.SW] + 0.5 * beta1_ * vel[0] + 0.5 * beta1_ * vel[1]; df[n][D2Q9_.NW] = -0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1]; df[n][D2Q9_.SE] = 0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1]; for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i]; df[n][0] = rho_node; break; } case 1: { // bottom-right auto rho_node = 0.5 * (cb_.rho_[n + nx] + cb_.rho_[n - 1]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.W] = df[n][D2Q9_.E] - 2.0 * beta1_ * vel[0]; df[n][D2Q9_.N] = df[n][D2Q9_.S] + 2.0 * beta1_ * vel[1]; df[n][D2Q9_.NW] = df[n][D2Q9_.SE] - 0.5 * beta1_ * vel[0] + 0.5 * beta1_ * vel[1]; df[n][D2Q9_.NE] = 0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1]; df[n][D2Q9_.SW] = -0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1]; for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i]; df[n][0] = rho_node; break; } case 2: { // top-left auto rho_node = 0.5 * (cb_.rho_[n - nx] + cb_.rho_[n + 1]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.E] = df[n][D2Q9_.W] + 2.0 * beta1_ * vel[0]; df[n][D2Q9_.S] = df[n][D2Q9_.N] - 2.0 * beta1_ * vel[1]; df[n][D2Q9_.SE] = df[n][D2Q9_.NW] + 0.5 * beta1_ * vel[0] - 0.5 * beta1_ * vel[1]; df[n][D2Q9_.NE] = 0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1]; df[n][D2Q9_.SW] = -0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1]; for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i]; df[n][0] = rho_node; break; } case 3: { // top-right auto rho_node = 0.5 * (cb_.rho_[n - nx] + cb_.rho_[n - 1]); for (auto &u : vel) u *= rho_node; df[n][D2Q9_.W] = df[n][D2Q9_.E] - 2.0 * beta1_ * vel[0]; df[n][D2Q9_.S] = df[n][D2Q9_.N] - 2.0 * beta1_ * vel[1]; df[n][D2Q9_.SW] = df[n][D2Q9_.NE] - 0.5 * beta1_ * vel[0] - 0.5 * beta1_ * vel[1]; df[n][D2Q9_.NW] = -0.5 * beta3_ * vel[0] + 0.5 * beta3_ * vel[1]; df[n][D2Q9_.SE] = 0.5 * beta3_ * vel[0] - 0.5 * beta3_ * vel[1]; for (auto i = 1u; i < nc; ++i) rho_node -= df[n][i]; df[n][0] = rho_node; break; } default: { throw std::runtime_error("Not a corner"); } } } void ZouHeNode::toggleNormalFlow() { is_normal_flow_ = true; }
zhishang72/OpenLBM
src/ZouHeNode.cpp
C++
gpl-3.0
8,375
package net.minecraft.server; import java.io.IOException; public class PacketPlayOutEntityHeadRotation implements Packet<PacketListenerPlayOut> { private int a; private byte b; public PacketPlayOutEntityHeadRotation() {} public PacketPlayOutEntityHeadRotation(Entity entity, byte b0) { this.a = entity.getId(); this.b = b0; } public void a(PacketDataSerializer packetdataserializer) throws IOException { this.a = packetdataserializer.g(); this.b = packetdataserializer.readByte(); } public void b(PacketDataSerializer packetdataserializer) throws IOException { packetdataserializer.d(this.a); packetdataserializer.writeByte(this.b); } public void a(PacketListenerPlayOut packetlistenerplayout) { packetlistenerplayout.a(this); } }
bergerkiller/SpigotSource
src/main/java/net/minecraft/server/PacketPlayOutEntityHeadRotation.java
Java
gpl-3.0
839
package cmake.icons; import com.intellij.openapi.util.IconLoader; import javax.swing.*; /** * Created by alex on 12/21/14. */ public class CMakeIcons { public static final Icon FILE = IconLoader.getIcon("/icons/cmake.png"); public static final Icon MACRO = IconLoader.getIcon("/icons/hashtag.png"); public static final Icon FUN = IconLoader.getIcon("/icons/fun.jpg"); public static final Icon LOOP = IconLoader.getIcon("/icons/loop.png"); }
dubrousky/CMaker
src/cmake/icons/CMakeIcons.java
Java
gpl-3.0
462
/* * Cantata * * Copyright (c) 2011-2013 Craig Drummond <craig.p.drummond@gmail.com> * * ---- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "umsdevice.h" #include "utils.h" #include "devicepropertiesdialog.h" #include "devicepropertieswidget.h" #include "actiondialog.h" #include "localize.h" #include <QDir> #include <QFile> #include <QFileInfo> #include <QTextStream> static const QLatin1String constSettingsFile("/.is_audio_player"); static const QLatin1String constMusicFolderKey("audio_folder"); UmsDevice::UmsDevice(MusicModel *m, Solid::Device &dev) : FsDevice(m, dev) , access(dev.as<Solid::StorageAccess>()) { spaceInfo.setPath(access->filePath()); setup(); } UmsDevice::~UmsDevice() { } void UmsDevice::connectionStateChanged() { if (isConnected()) { spaceInfo.setPath(access->filePath()); setup(); if (opts.autoScan || scanned){ // Only scan if we are set to auto scan, or we have already scanned before... rescan(false); // Read from cache if we have it! } else { setStatusMessage(i18n("Not Scanned")); } } else { clear(); } } void UmsDevice::toggle() { if (solidDev.isValid() && access && access->isValid()) { if (access->isAccessible()) { if (scanner) { scanner->stop(); } access->teardown(); } else { access->setup(); } } } bool UmsDevice::isConnected() const { return solidDev.isValid() && access && access->isValid() && access->isAccessible(); } double UmsDevice::usedCapacity() { if (cacheProgress>-1) { return (cacheProgress*1.0)/100.0; } if (!isConnected()) { return -1.0; } return spaceInfo.size()>0 ? (spaceInfo.used()*1.0)/(spaceInfo.size()*1.0) : -1.0; } QString UmsDevice::capacityString() { if (cacheProgress>-1) { return statusMessage(); } if (!isConnected()) { return i18n("Not Connected"); } return i18n("%1 free", Utils::formatByteSize(spaceInfo.size()-spaceInfo.used())); } qint64 UmsDevice::freeSpace() { if (!isConnected()) { return 0; } return spaceInfo.size()-spaceInfo.used(); } void UmsDevice::setup() { if (!isConnected()) { return; } QString path=spaceInfo.path(); audioFolder = path; QFile file(path+constSettingsFile); QString audioFolderSetting; opts=DeviceOptions(); if (file.open(QIODevice::ReadOnly|QIODevice::Text)) { configured=true; QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if (line.startsWith(constMusicFolderKey+"=")) { audioFolderSetting=audioFolder=Utils::cleanPath(path+'/'+line.section('=', 1, 1)); if (!QDir(audioFolder).exists()) { audioFolder = path; } } else if (line.startsWith(constMusicFilenameSchemeKey+"=")) { QString scheme = line.section('=', 1, 1); //protect against empty setting. if( !scheme.isEmpty() ) { opts.scheme = scheme; } } else if (line.startsWith(constVfatSafeKey+"=")) { opts.vfatSafe = QLatin1String("true")==line.section('=', 1, 1); } else if (line.startsWith(constAsciiOnlyKey+"=")) { opts.asciiOnly = QLatin1String("true")==line.section('=', 1, 1); } else if (line.startsWith(constIgnoreTheKey+"=")) { opts.ignoreThe = QLatin1String("true")==line.section('=', 1, 1); } else if (line.startsWith(constReplaceSpacesKey+"=")) { opts.replaceSpaces = QLatin1String("true")==line.section('=', 1, 1); } else { unusedParams+=line; } } } bool haveOpts=FsDevice::readOpts(path+constCantataSettingsFile, opts, false); if (!configured) { configured=haveOpts; } if (opts.coverName.isEmpty()) { opts.coverName=constDefCoverFileName; } // No setting, see if any standard dirs exist in path... if (audioFolderSetting.isEmpty() || audioFolderSetting!=audioFolder) { QStringList dirs; dirs << QLatin1String("Music") << QLatin1String("MUSIC") << QLatin1String("Albums") << QLatin1String("ALBUMS"); foreach (const QString &d, dirs) { if (QDir(path+d).exists()) { audioFolder=path+d; break; } } } if (!audioFolder.endsWith('/')) { audioFolder+='/'; } if (opts.autoScan || scanned){ // Only scan if we are set to auto scan, or we have already scanned before... rescan(false); // Read from cache if we have it! } else { setStatusMessage(i18n("Not Scanned")); } } void UmsDevice::configure(QWidget *parent) { if (!isIdle()) { return; } DevicePropertiesDialog *dlg=new DevicePropertiesDialog(parent); connect(dlg, SIGNAL(updatedSettings(const QString &, const DeviceOptions &)), SLOT(saveProperties(const QString &, const DeviceOptions &))); if (!configured) { connect(dlg, SIGNAL(cancelled()), SLOT(saveProperties())); } dlg->show(audioFolder, opts, qobject_cast<ActionDialog *>(parent) ? (DevicePropertiesWidget::Prop_All-DevicePropertiesWidget::Prop_Folder) : DevicePropertiesWidget::Prop_All); } void UmsDevice::saveProperties() { saveProperties(audioFolder, opts); } static inline QString toString(bool b) { return b ? QLatin1String("true") : QLatin1String("false"); } void UmsDevice::saveOptions() { if (!isConnected()) { return; } QString path=spaceInfo.path(); QFile file(path+constSettingsFile); QString fixedPath(audioFolder); if (fixedPath.startsWith(path)) { fixedPath=QLatin1String("./")+fixedPath.mid(path.length()); } DeviceOptions def; if (file.open(QIODevice::WriteOnly|QIODevice::Text)) { QTextStream out(&file); if (!fixedPath.isEmpty()) { out << constMusicFolderKey << '=' << fixedPath << '\n'; } if (opts.scheme!=def.scheme) { out << constMusicFilenameSchemeKey << '=' << opts.scheme << '\n'; } if (opts.scheme!=def.scheme) { out << constVfatSafeKey << '=' << toString(opts.vfatSafe) << '\n'; } if (opts.asciiOnly!=def.asciiOnly) { out << constAsciiOnlyKey << '=' << toString(opts.asciiOnly) << '\n'; } if (opts.ignoreThe!=def.ignoreThe) { out << constIgnoreTheKey << '=' << toString(opts.ignoreThe) << '\n'; } if (opts.replaceSpaces!=def.replaceSpaces) { out << constReplaceSpacesKey << '=' << toString(opts.replaceSpaces) << '\n'; } foreach (const QString &u, unusedParams) { out << u << '\n'; } } } void UmsDevice::saveProperties(const QString &newPath, const DeviceOptions &newOpts) { QString nPath=Utils::fixPath(newPath); if (configured && opts==newOpts && nPath==audioFolder) { return; } configured=true; bool diffCacheSettings=opts.useCache!=newOpts.useCache; opts=newOpts; if (diffCacheSettings) { if (opts.useCache) { saveCache(); } else { removeCache(); } } emit configurationChanged(); QString oldPath=audioFolder; if (!isConnected()) { return; } audioFolder=nPath; saveOptions(); FsDevice::writeOpts(spaceInfo.path()+constCantataSettingsFile, opts, false); if (oldPath!=audioFolder) { rescan(); // Path changed, so we can ignore cache... } }
polpo/cantata-mac
devices/umsdevice.cpp
C++
gpl-3.0
8,544
HostCMS 6.7 = 9fdd2118a94f53ca1c411a7629edf565
gohdan/DFC
known_files/hashes/admin/wysiwyg/plugins/imagetools/plugin.min.js
JavaScript
gpl-3.0
47
def _setup_pkgresources(): import pkg_resources import os import plistlib pl = plistlib.readPlist(os.path.join( os.path.dirname(os.getenv('RESOURCEPATH')), "Info.plist")) appname = pl.get('CFBundleIdentifier') if appname is None: appname = pl['CFBundleDisplayName'] path = os.path.expanduser('~/Library/Caches/%s/python-eggs' % (appname,)) pkg_resources.set_extraction_path(path) _setup_pkgresources()
nCoda/macOS
.eggs/py2app-0.14-py2.7.egg/py2app/bootstrap/setup_pkgresource.py
Python
gpl-3.0
453
<?php /** * Kunena Plugin * @package Kunena.Plugins * @subpackage Joomla16 * * @Copyright (C) 2008 - 2012 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org **/ defined ( '_JEXEC' ) or die (); class plgKunenaJoomla extends JPlugin { public function __construct(&$subject, $config) { // Do not load if Kunena version is not supported or Kunena is offline if (!(class_exists('KunenaForum') && KunenaForum::isCompatible('2.0') && KunenaForum::installed())) return; parent::__construct ( $subject, $config ); $this->loadLanguage ( 'plg_kunena_joomla.sys', JPATH_ADMINISTRATOR ) || $this->loadLanguage ( 'plg_kunena_joomla.sys', KPATH_ADMIN ); $this->path = dirname ( __FILE__ ); } /* * Get Kunena access control object. * * @return KunenaAccess */ public function onKunenaGetAccessControl() { if (!$this->params->get('access', 1)) return; require_once "{$this->path}/access.php"; return new KunenaAccessJoomla($this->params); } /* * Get Kunena login integration object. * * @return KunenaLogin */ public function onKunenaGetLogin() { if (!$this->params->get('login', 1)) return; require_once "{$this->path}/login.php"; return new KunenaLoginJoomla($this->params); } }
810/k3.0-frontend
administrator/components/com_kunena/install/plugins/plg_kunena_joomla/joomla.php
PHP
gpl-3.0
1,295
<?php /** * Automatically loads the specified file. * * @package PluginName\Lib */ namespace PluginName\Lib; /** * Automatically loads the specified file. * * Examines the fully qualified class name, separates it into components, then creates * a string that represents where the file is loaded on disk. * * @package PluginName\Lib */ spl_autoload_register( function ( $filename ) { // First, separate the components of the incoming file. $file_path = explode( '\\', $filename ); /** * - The first index will always be WCATL since it's part of the plugin. * - All but the last index will be the path to the file. */ // Get the last index of the array. This is the class we're loading. if ( isset( $file_path[ count( $file_path ) - 1 ] ) ) { $class_file = strtolower( $file_path[ count( $file_path ) - 1 ] ); // The classname has an underscore, so we need to replace it with a hyphen for the file name. $class_file = str_ireplace( '_', '-', $class_file ); $class_file = "class-$class_file.php"; } /** * Find the fully qualified path to the class file by iterating through the $file_path array. * We ignore the first index since it's always the top-level package. The last index is always * the file so we append that at the end. */ $fully_qualified_path = trailingslashit( dirname( dirname( __FILE__ ) ) ); for ( $i = 1; $i < count( $file_path ) - 1; $i++ ) { $dir = strtolower( $file_path[ $i ] ); $fully_qualified_path .= trailingslashit( $dir ); } $fully_qualified_path .= $class_file; // Now we include the file. if ( file_exists( $fully_qualified_path ) ) { include_once( $fully_qualified_path ); } });
bjonesy/plugin-name
lib/autoloader.php
PHP
gpl-3.0
1,681
/* Copyright (C) 2011 Equinor ASA, Norway. The file 'rsh_driver.c' is part of ERT - Ensemble based Reservoir Tool. ERT 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. ERT 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 at <http://www.gnu.org/licenses/gpl.html> for more details. */ #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netdb.h> #include <pthread.h> #include <errno.h> #include <ert/util/util.hpp> #include <ert/res_util/arg_pack.hpp> #include <ert/job_queue/queue_driver.hpp> #include <ert/job_queue/rsh_driver.hpp> struct rsh_job_struct { UTIL_TYPE_ID_DECLARATION; bool active; /* Means that it allocated - not really in use */ job_status_type status; pthread_t run_thread; const char * host_name; /* Currently not set */ char * run_path; }; typedef struct { char * host_name; int max_running; /* How many can the host handle. */ int running; /* How many are currently running on the host (goverened by this driver instance that is). */ pthread_mutex_t host_mutex; } rsh_host_type; #define RSH_DRIVER_TYPE_ID 44963256 #define RSH_JOB_TYPE_ID 63256701 struct rsh_driver_struct { UTIL_TYPE_ID_DECLARATION; pthread_mutex_t submit_lock; pthread_attr_t thread_attr; char * rsh_command; int num_hosts; int last_host_index; rsh_host_type **host_list; hash_type *__host_hash; /* Stupid redundancy ... */ }; /******************************************************************/ static UTIL_SAFE_CAST_FUNCTION_CONST( rsh_driver , RSH_DRIVER_TYPE_ID ) static UTIL_SAFE_CAST_FUNCTION( rsh_driver , RSH_DRIVER_TYPE_ID ) static UTIL_SAFE_CAST_FUNCTION( rsh_job , RSH_JOB_TYPE_ID ) /** If the host is for some reason not available, NULL should be returned. Will also return NULL if some funny guy tries to allocate with max_running <= 0. */ static rsh_host_type * rsh_host_alloc(const char * host_name , int max_running) { if (max_running > 0) { struct addrinfo * result; if (getaddrinfo(host_name , NULL , NULL , &result) == 0) { rsh_host_type * host = (rsh_host_type*)util_malloc(sizeof * host ); host->host_name = util_alloc_string_copy(host_name); host->max_running = max_running; host->running = 0; pthread_mutex_init( &host->host_mutex , NULL ); freeaddrinfo( result ); return host; } else { fprintf(stderr,"** Warning: could not locate server: %s \n",host_name); return NULL; } } else return NULL; } static void rsh_host_free(rsh_host_type * rsh_host) { free(rsh_host->host_name); free(rsh_host); } static bool rsh_host_available(rsh_host_type * rsh_host) { bool available; pthread_mutex_lock( &rsh_host->host_mutex ); { available = false; if ((rsh_host->max_running - rsh_host->running) > 0) { // The host has free slots() available = true; rsh_host->running++; } } pthread_mutex_unlock( &rsh_host->host_mutex ); return available; } static void rsh_host_submit_job(rsh_host_type * rsh_host , rsh_job_type * job, const char * rsh_cmd , const char * submit_cmd , int num_cpu , int job_argc , const char ** job_argv) { /* Observe that this job has already been added to the running jobs in the rsh_host_available function. */ int argc = job_argc + 2; const char ** argv = (const char**)util_malloc( argc * sizeof * argv ); argv[0] = rsh_host->host_name; argv[1] = submit_cmd; { int iarg; for (iarg = 0; iarg < job_argc; iarg++) argv[iarg + 2] = job_argv[iarg]; } util_spawn_blocking(rsh_cmd, argc, argv, NULL, NULL); /* This call is blocking. */ job->status = JOB_QUEUE_DONE; pthread_mutex_lock( &rsh_host->host_mutex ); rsh_host->running--; pthread_mutex_unlock( &rsh_host->host_mutex ); free( argv ); } /* static const char * rsh_host_get_hostname(const rsh_host_type * host) { return host->host_name; } */ static void * rsh_host_submit_job__(void * __arg_pack) { arg_pack_type * arg_pack = arg_pack_safe_cast(__arg_pack); char * rsh_cmd = (char *) arg_pack_iget_ptr(arg_pack , 0); rsh_host_type * rsh_host = (rsh_host_type *)arg_pack_iget_ptr(arg_pack , 1); char * submit_cmd = (char *) arg_pack_iget_ptr(arg_pack , 2); int num_cpu = arg_pack_iget_int(arg_pack , 3); int argc = arg_pack_iget_int(arg_pack , 4); const char ** argv = (const char **) arg_pack_iget_ptr(arg_pack , 5); rsh_job_type * job = (rsh_job_type*) arg_pack_iget_ptr(arg_pack , 6); rsh_host_submit_job(rsh_host , job , rsh_cmd , submit_cmd , num_cpu , argc , argv); pthread_exit( NULL ); arg_pack_free( arg_pack ); } /*****************************************************************/ /*****************************************************************/ rsh_job_type * rsh_job_alloc(const char * run_path) { rsh_job_type * job; job = (rsh_job_type*)util_malloc(sizeof * job ); job->active = false; job->status = JOB_QUEUE_WAITING; job->run_path = util_alloc_string_copy(run_path); UTIL_TYPE_ID_INIT( job , RSH_JOB_TYPE_ID ); return job; } void rsh_job_free(rsh_job_type * job) { free(job->run_path); free(job); } job_status_type rsh_driver_get_job_status(void * __driver , void * __job) { if (__job == NULL) /* The job has not been registered at all ... */ return JOB_QUEUE_NOT_ACTIVE; else { rsh_job_type * job = rsh_job_safe_cast( __job ); { if (job->active == false) { util_abort("%s: internal error - should not query status on inactive jobs \n" , __func__); return JOB_QUEUE_NOT_ACTIVE; /* Dummy to shut up compiler */ } else return job->status; } } } void rsh_driver_free_job( void * __job ) { rsh_job_type * job = rsh_job_safe_cast( __job ); rsh_job_free(job); } void rsh_driver_kill_job(void * __driver ,void * __job) { rsh_job_type * job = rsh_job_safe_cast( __job ); if (job->active) pthread_cancel( job->run_thread ); rsh_job_free( job ); } void * rsh_driver_submit_job(void * __driver, const char * submit_cmd , int num_cpu , /* Ignored */ const char * run_path , const char * job_name , int argc, const char ** argv ) { rsh_driver_type * driver = rsh_driver_safe_cast( __driver ); rsh_job_type * job = NULL; { /* command is freed in the start_routine() function */ pthread_mutex_lock( &driver->submit_lock ); { rsh_host_type * host = NULL; int ihost; int host_index = 0; if (driver->num_hosts == 0) util_abort("%s: fatal error - no hosts added to the rsh driver.\n",__func__); for (ihost = 0; ihost < driver->num_hosts; ihost++) { host_index = (ihost + driver->last_host_index) % driver->num_hosts; if (rsh_host_available(driver->host_list[host_index])) { host = driver->host_list[host_index]; break; } } driver->last_host_index = (host_index + 1) % driver->num_hosts; if (host != NULL) { /* A host is available */ arg_pack_type * arg_pack = arg_pack_alloc(); /* The arg_pack is freed() in the rsh_host_submit_job__() function. freeing it here is dangerous, because we might free it before the thread-called function is finished with it. */ job = rsh_job_alloc(run_path); arg_pack_append_ptr(arg_pack , driver->rsh_command); arg_pack_append_ptr(arg_pack , host); arg_pack_append_ptr(arg_pack , (char *) submit_cmd); arg_pack_append_int(arg_pack , num_cpu ); arg_pack_append_int(arg_pack , argc ); arg_pack_append_ptr(arg_pack , argv ); arg_pack_append_ptr(arg_pack , job); { int pthread_return_value = pthread_create( &job->run_thread , &driver->thread_attr , rsh_host_submit_job__ , arg_pack); if (pthread_return_value != 0) util_abort("%s failed to create thread ERROR:%d \n", __func__ , pthread_return_value); } job->status = JOB_QUEUE_RUNNING; job->active = true; } } pthread_mutex_unlock( &driver->submit_lock ); } return job; } void rsh_driver_clear_host_list( rsh_driver_type * driver ) { int ihost; for (ihost =0; ihost < driver->num_hosts; ihost++) rsh_host_free(driver->host_list[ihost]); free(driver->host_list); driver->num_hosts = 0; driver->host_list = NULL; driver->last_host_index = 0; } void rsh_driver_free(rsh_driver_type * driver) { rsh_driver_clear_host_list( driver ); pthread_attr_destroy ( &driver->thread_attr ); free(driver->rsh_command ); hash_free( driver->__host_hash ); free(driver); driver = NULL; } void rsh_driver_free__(void * __driver) { rsh_driver_type * driver = rsh_driver_safe_cast( __driver ); rsh_driver_free( driver ); } void rsh_driver_set_host_list( rsh_driver_type * rsh_driver , const hash_type * rsh_host_list) { rsh_driver_clear_host_list( rsh_driver ); if (rsh_host_list != NULL) { hash_iter_type * hash_iter = hash_iter_alloc( rsh_host_list ); while (!hash_iter_is_complete( hash_iter )) { const char * host = hash_iter_get_next_key( hash_iter ); int max_running = hash_get_int( rsh_host_list , host ); rsh_driver_add_host(rsh_driver , host , max_running); } if (rsh_driver->num_hosts == 0) util_abort("%s: failed to add any valid RSH hosts - aborting.\n",__func__); } } /** */ void * rsh_driver_alloc( ) { rsh_driver_type * rsh_driver = (rsh_driver_type*)util_malloc( sizeof * rsh_driver ); UTIL_TYPE_ID_INIT( rsh_driver , RSH_DRIVER_TYPE_ID ); pthread_mutex_init( &rsh_driver->submit_lock , NULL ); pthread_attr_init( &rsh_driver->thread_attr ); pthread_attr_setdetachstate( &rsh_driver->thread_attr , PTHREAD_CREATE_DETACHED ); /** To simplify the Python wrapper it is possible to pass in NULL as rsh_host_list pointer, and then subsequently add hosts with rsh_driver_add_host(). */ rsh_driver->num_hosts = 0; rsh_driver->host_list = NULL; rsh_driver->last_host_index = 0; rsh_driver->rsh_command = NULL; rsh_driver->__host_hash = hash_alloc(); return rsh_driver; } void rsh_driver_add_host(rsh_driver_type * rsh_driver , const char * hostname , int host_max_running) { rsh_host_type * new_host = rsh_host_alloc(hostname , host_max_running); /* Could in principle update an existing node if the host name is old. */ if (new_host != NULL) { rsh_driver->num_hosts++; rsh_driver->host_list = (rsh_host_type**)util_realloc(rsh_driver->host_list , rsh_driver->num_hosts * sizeof * rsh_driver->host_list ); rsh_driver->host_list[(rsh_driver->num_hosts - 1)] = new_host; } } /** Hostname should be a string as host:max_running, the ":max_running" part is optional, and will default to 1. */ void rsh_driver_add_host_from_string(rsh_driver_type * rsh_driver , const char * hostname) { int host_max_running; char ** tmp; char * host; int tokens; util_split_string( hostname , ":" , &tokens , &tmp); if (tokens > 1) { if (!util_sscanf_int( tmp[tokens - 1] , &host_max_running)) util_abort("%s: failed to parse out integer from: %s \n",__func__ , hostname); host = util_alloc_joined_string((const char **) tmp , tokens - 1 , ":"); } else host = util_alloc_string_copy( tmp[0] ); rsh_driver_add_host( rsh_driver , host , host_max_running ); util_free_stringlist( tmp , tokens ); free( host ); } bool rsh_driver_set_option( void * __driver , const char * option_key , const void * value_ ) { const char * value = (const char*) value_; rsh_driver_type * driver = rsh_driver_safe_cast( __driver ); bool has_option = true; { if (strcmp(RSH_HOST , option_key) == 0) /* Add one host - value should be hostname:max */ rsh_driver_add_host_from_string( driver , value ); else if (strcmp(RSH_HOSTLIST , option_key) == 0) { /* Set full host list - value should be hash of integers. */ if (value != NULL) { const hash_type * hash_value = hash_safe_cast_const( value ); rsh_driver_set_host_list( driver , hash_value ); } } else if (strcmp( RSH_CLEAR_HOSTLIST , option_key) == 0) /* Value is not considered - this is an action, and not a _set operation. */ rsh_driver_set_host_list( driver , NULL ); else if (strcmp( RSH_CMD , option_key) == 0) driver->rsh_command = util_realloc_string_copy( driver->rsh_command , value ); else has_option = false; } return has_option; } const void * rsh_driver_get_option( const void * __driver , const char * option_key ) { const rsh_driver_type * driver = rsh_driver_safe_cast_const( __driver ); { if (strcmp( RSH_CMD , option_key ) == 0) return driver->rsh_command; else if (strcmp( RSH_HOSTLIST , option_key) == 0) { int ihost; hash_clear( driver->__host_hash ); for (ihost = 0; ihost < driver->num_hosts; ihost++) { rsh_host_type * host = driver->host_list[ ihost ]; hash_insert_int( driver->__host_hash , host->host_name , host->max_running); } return driver->__host_hash; } else { util_abort("%s: get not implemented fro option_id:%s for rsh \n",__func__ , option_key ); return NULL; } } } void rsh_driver_init_option_list(stringlist_type * option_list) { stringlist_append_copy(option_list, RSH_HOST); stringlist_append_copy(option_list, RSH_HOSTLIST); stringlist_append_copy(option_list, RSH_CMD); stringlist_append_copy(option_list, RSH_CLEAR_HOSTLIST); } #undef RSH_JOB_ID /*****************************************************************/
andreabrambilla/libres
lib/job_queue/rsh_driver.cpp
C++
gpl-3.0
14,676
require 'package' class Harfbuzz < Package description 'HarfBuzz is an OpenType text shaping engine.' homepage 'https://www.freedesktop.org/wiki/Software/HarfBuzz/' version '1.7.6-0' source_url 'https://github.com/harfbuzz/harfbuzz/releases/download/1.7.6/harfbuzz-1.7.6.tar.bz2' source_sha256 'da7bed39134826cd51e57c29f1dfbe342ccedb4f4773b1c951ff05ff383e2e9b' binary_url ({ aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-armv7l.tar.xz', armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-armv7l.tar.xz', i686: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-i686.tar.xz', x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/harfbuzz-1.7.6-0-chromeos-x86_64.tar.xz', }) binary_sha256 ({ aarch64: 'd92567e640f2b847ff35d1dcb5e0fcabaa640cea8c709755a3fed8b1ed59a598', armv7l: 'd92567e640f2b847ff35d1dcb5e0fcabaa640cea8c709755a3fed8b1ed59a598', i686: '220ae1416d6fb21e9d5621d97c66e65dddd15eb63108fb4c5e3d5fe6c75e662a', x86_64: '3dd360778d0ffbd12b23a9d1e2fe5d3031f8a93eb9f9618cd430dc91349bee7d', }) depends_on 'glib' depends_on 'icu4c' depends_on 'freetype_sub' def self.build system "./configure --prefix=#{CREW_PREFIX} --libdir=#{CREW_LIB_PREFIX}" system "make" end def self.install system "pip install six" system "make", "DESTDIR=#{CREW_DEST_DIR}", "install" system "pip uninstall --yes six" end end
thedamian/chromebrew
packages/harfbuzz.rb
Ruby
gpl-3.0
1,486