repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
climatescope/climatescope.org
|
src/components/pages/ResultsPage/Ranking/useRankingData.js
|
2048
|
import { useRef, useMemo } from "react"
import sortBy from "lodash/sortBy"
const topicNames = ["Fundamentals", "Opportunities", "Experience"]
const computeFinalScore = (topics, weighting, sector) => {
const weightedTopics = topics.reduce((acc, cur) => {
if (cur.sector !== sector) return acc
const name = cur.name
const weight = weighting[topicNames.indexOf(name)]
const value = cur.data[0].value
const weightedValue = value * (weight / 100)
const item = {
id: cur.id,
name,
sector: cur.sector,
value,
weight,
weightedValue,
width: (100 / 5) * weightedValue,
}
return [...acc, item]
}, [])
const finalScore = weightedTopics.reduce(
(acc, cur) => acc + cur.weightedValue,
0
)
return { finalScore, weightedTopics }
}
const useRankingData = ({
weighting,
sector = "power",
region,
marketGroup,
data,
}) => {
if (!data) return null
const count = useRef(0)
const len = data.length
const augmented = useMemo(() => {
return data.map((d) => {
const isVisible =
(!region || d.region.id === region) &&
(!marketGroup || d.marketGrouping === marketGroup)
if (sector === "all") {
return {
...d,
isVisible,
finalScore: d.score.data[0].value,
weightedTopics: [],
}
}
const hasData = sector === "all sectors" || d.sectors.find((s) => s.id === sector).data[0].value
const { finalScore, weightedTopics } = computeFinalScore(
d.topics,
weighting,
sector
)
return {
...d,
isVisible: !!hasData && isVisible,
finalScore,
weightedTopics,
}
})
}, [region, weighting, sector, len, marketGroup])
const sorted = sortBy(augmented, (o) => -o.finalScore)
return sorted.map((cur, i) => {
if (!i) count.current = 0
count.current = count.current + (cur.isVisible ? 1 : 0)
return { ...cur, masterRank: count.current }
})
}
export default useRankingData
|
gpl-3.0
|
Relicum/SignMagic
|
src/main/java/com/relicum/signmagic/Handlers/Line.java
|
5864
|
/*
* SignMagic is a development API for Minecraft Sign Editing, developed
* originally by libraryaddict now by Relicum
* Copyright (C) 2014. Chris Lutte
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.relicum.signmagic.Handlers;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Name: Line.java Created: 19 December 2014
*
* @author Relicum
* @version 0.0.1
*/
@SerializableAs("Line")
public class Line implements Identifier, ConfigurationSerializable {
private String id;
private boolean enable;
private String regex;
private List<String> lookUps;
private String actionType;
protected Line(String actionType, boolean enable, String id, List<String> lookUps, String regex) {
this.actionType = actionType;
this.enable = enable;
this.id = id;
this.lookUps = lookUps;
this.regex = regex;
}
public Line(LINE_INDEX id) {
this.id = id.name();
this.lookUps = new ArrayList<>();
this.enable = false;
this.actionType = ActionType.LEAVE.name();
this.regex = " ";
}
/**
* {@inheritDoc}
*/
@Override
public String getId() {
return id;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEnabled() {
return enable;
}
/**
* {@inheritDoc}
*/
@Override
public void enableIdentifier() {
this.enable = true;
}
/**
* {@inheritDoc}
*/
@Override
public void disableIdentifier() {
this.enable = false;
}
/**
* {@inheritDoc}
*/
@Override
public void addIdentifierPattern(String regex) {
Validate.notNull(regex);
this.regex = regex;
}
/**
* {@inheritDoc}
*/
@Override
public void updateIdentifierPattern(String regex) {
Validate.notNull(regex);
this.regex = regex;
}
/**
* {@inheritDoc}
*/
@Override
public String getIdentifierPattern() {
return this.regex;
}
/**
* {@inheritDoc}
*/
@Override
public void addNewLookup(String lookup) {
Validate.notNull(lookup);
this.lookUps.add(lookup);
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeLookup(String lookup) {
return this.lookUps.remove(lookup);
}
/**
* {@inheritDoc}
*/
@Override
public ImmutableList<String> getListOfIdentifiers() {
return ImmutableList.copyOf(lookUps);
}
/**
* {@inheritDoc}
*/
@Override
public void setActionType(ActionType actionType) {
this.actionType = actionType.name();
}
/**
* {@inheritDoc}
*/
@Override
public ActionType getActionType() {
return ActionType.valueOf(actionType);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Line)) return false;
Line line = (Line) o;
if (enable != line.enable) return false;
if (!actionType.equals(line.actionType)) return false;
if (!id.equals(line.id)) return false;
if (!regex.equals(line.regex)) return false;
return true;
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + (enable ? 1 : 0);
result = 31 * result + regex.hashCode();
result = 31 * result + actionType.hashCode();
return result;
}
public static Line deserialize(Map<String, Object> map) {
Object objId = map.get("id"), objEnable = map.get("enable"),
objRegex = map.get("regex"), objLookups = map.get("lookups"),
objAction = map.get("action");
if (objId == null || objEnable == null || objRegex == null || objLookups == null || objAction == null)
throw new RuntimeException("Error while deserializing object something was null");
return new Line((String) objAction, (Boolean) objEnable, (String) objId, (List<String>) objLookups, (String) objRegex);
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("id", id);
map.put("enable", enable);
map.put("regex", regex);
map.put("lookups", lookUps);
map.put("action", actionType);
return map;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("actionType", actionType)
.append("id", id)
.append("enable", enable)
.append("regex", regex)
.append("lookUps", lookUps)
.append("enabled", isEnabled())
.append("listOfIdentifiers", getListOfIdentifiers())
.append("rialize", serialize())
.toString();
}
}
|
gpl-3.0
|
bezout/libv-core
|
src/libv/core/draw_tools.hpp
|
4719
|
/**
\file
\author Vadim Litvinov (2013)
\copyright 2013 Institut Pascal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBV_CORE_DRAW_TOOLS_HPP
#define LIBV_CORE_DRAW_TOOLS_HPP
#include <cmath>
#include <algorithm>
#include "miscmath.hpp"
namespace libv {
namespace core {
/// \addtogroup image
/// \{
/// \brief Fill the image with the given color
///
/// Uniformly fills the image with the given color.
///
/// \param image Image to fill.
/// \param color Filling color.
template<class Image>
inline void draw_fill(Image& image, typename Image::const_reference_to_pixel color) {
std::fill(image.begin_pixel(), image.end_pixel(), color);
}
/// \brief Draw a point
///
/// Draw a point on the given image.
///
/// \param image Image to draw to.
/// \param x Point horizontal position.
/// \param y Point vertical position.
/// \param color Point color.
template<class Image>
inline void draw_point(Image& image, float x, float y, typename Image::const_reference_to_pixel color)
{
image(round(y), round(x)) = color;
}
/// \brief Draw line
///
/// Draw a line on the given image.
///
/// \param image Image to draw to.
/// \param x1 First point horizontal position.
/// \param y1 First point vertical position.
/// \param x2 Second point horizontal position.
/// \param y2 Second point vertical position.
/// \param color Line color.
template<class Image>
inline void draw_line(Image& image, float x1, float y1, float x2, float y2, typename Image::const_reference_to_pixel color)
{
const bool steep = std::fabs(y2 - y1) > std::fabs(x2 - x1);
if(steep)
{
std::swap(x1, y1);
std::swap(x2, y2);
}
if(x1 > x2)
{
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = std::fabs(y2 - y1);
float error = dx/2.0f;
const int ystep = (y1 < y2)?1:-1;
int y = (int)y1;
const int maxX = (int)x2;
for(int x = (int)x1; x < maxX; ++x)
{
if(steep) image(x, y) = color;
else image(y, x) = color;
error -= dy;
if(error < 0)
{
y += ystep;
error += dx;
}
}
}
/// \brief Draw rectangle
///
/// Draw a rectangle outline on the given image.
///
/// \param image Image to draw to.
/// \param x1 First corner horizontal position.
/// \param y1 First corner vertical position.
/// \param x2 Second corner horizontal position.
/// \param y2 Second corner vertical position.
/// \param color Rectangle color.
template<class Image>
inline void draw_rect(Image& image, float x1, float y1, float x2, float y2, typename Image::const_reference_to_pixel color)
{
draw_line(image, x1, y1, x2, y1, color);
draw_line(image, x1, y1, x1, y2, color);
draw_line(image, x2, y1, x2, y2, color);
draw_line(image, x1, y2, x2, y2, color);
}
/// \brief Draw circle
///
/// Draw a circle on the given image.
///
/// \param image Image to draw to.
/// \param cx Circle center horizontal position.
/// \param cy Circle center vertical position.
/// \param radius Circle radius.
/// \param color Circle color.
template<class Image>
inline void draw_circle(Image& image, float cx, float cy, float radius, typename Image::const_reference_to_pixel color) {
const int x0 = (int)round(cx);
const int y0 = (int)round(cy);
const int r = (int)round(radius);
int x = r, y = 0;
int x_chg = 1 - (r << 1);
int y_chg = 0;
int r_err = 0;
while(x >= y)
{
image(y + y0, x + x0) = color;
image(x + y0, y + x0) = color;
image(y + y0, -x + x0) = color;
image(x + y0, -y + x0) = color;
image(-y + y0, -x + x0) = color;
image(-x + y0, -y + x0) = color;
image(-y + y0, x + x0) = color;
image(-x + y0, y + x0) = color;
++y;
r_err += y_chg;
y_chg += 2;
if((r_err << 1) + x_chg > 0)
{
--x;
r_err += x_chg;
x_chg += 2;
}
}
}
/// \}
}}
#endif
|
gpl-3.0
|
miracle091/transmission-remote-dotnet
|
TransmissionClientNew/Libs/MonoTorrent/MonoTorrentCollectionBase.cs
|
757
|
using System;
using System.Collections.Generic;
namespace MonoTorrent.Common
{
public class MonoTorrentCollection<T> : List<T>, ICloneable
{
public MonoTorrentCollection() : base()
{
}
public MonoTorrentCollection(IEnumerable<T> collection) : base(collection)
{
}
public MonoTorrentCollection(int capacity) : base(capacity)
{
}
object ICloneable.Clone()
{
return Clone();
}
public MonoTorrentCollection<T> Clone()
{
return new MonoTorrentCollection<T>(this);
}
public T Dequeue()
{
T result = this[0];
RemoveAt(0);
return result;
}
}
}
|
gpl-3.0
|
ivansams/PostmanCleaner
|
PostmanCleaner/RequestDto.cs
|
1901
|
using Newtonsoft.Json;
using System.Collections.Generic;
namespace PostmanCleaner
{
public class RequestDto
{
[JsonProperty(Order = 1)]
[JsonRequired]
public string Id { get; set; }
[JsonProperty(Order = 2)]
[JsonRequired]
public string CollectionId { get; set; }
[JsonProperty(Order = 3)]
[JsonRequired]
public string Name { get; set; }
[JsonProperty(Order = 4)]
[JsonRequired]
public string Method { get; set; }
[JsonProperty(Order = 5)]
[JsonRequired]
public string Headers { get; set; }
[JsonProperty(Order = 6)]
[JsonRequired]
public string Url { get; set; }
[JsonProperty(Order = 7)]
[JsonRequired]
public string Tests { get; set; }
[JsonProperty(Order = 8)]
public string PreRequestScript { get; set; }
[JsonProperty(Order = 9)]
public string DataMode { get; set; }
[JsonProperty(Order = 10)]
public List<DataDto> Data { get; set; }
[JsonProperty(Order = 11)]
public string RawModeData { get; set; }
[JsonProperty(Order = 12)]
[JsonIgnore]
public object PathVariables { get; set; }
[JsonProperty(Order = 13)]
[JsonIgnore]
public int Version { get; set; }
[JsonProperty(Order = 14)]
[JsonIgnore]
public string CurrentHelper { get; set; }
[JsonProperty(Order = 15)]
[JsonIgnore]
public object HelperAttributes { get; set; }
[JsonProperty(Order = 16)]
[JsonIgnore]
public long? Time { get; set; }
[JsonProperty(Order = 17)]
[JsonIgnore]
public string Description { get; set; }
[JsonIgnore]
[JsonProperty(Order = 18)]
public List<string> Responses { get; set; }
}
}
|
gpl-3.0
|
vestrada/docs
|
source/conf.py
|
13092
|
# -*- coding: utf-8 -*-
#
# CrafterCMS documentation build configuration file, created by
# sphinx-quickstart on Thu Dec 3 15:22:20 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
sys.path.insert(0, os.path.abspath('_ext'))
import shlex
from datetime import date
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'edit_on_github',
'sphinx.ext.extlinks',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Crafter CMS'
copyright = u"%s, Crafter Software Corporation"% str(date.today().year)
author = u'Crafter Software Corporation'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'3.1'
# The full version, including alpha/beta/rc tags.
release = u'3.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['includes/*.rst']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#html_theme = 'default'
#html_theme = 'alabaster'
#html_theme = 'sphinx_rtd_theme'
# https://github.com/rart/craftercms-sphinx-theme
html_theme = 'craftercms_sphinx_theme'
html_show_sphinx = False
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"analytics_id": "UA-40677244-9",
"topbar_items": [
{"text":"Crafter CMS Site", "link":"//craftercms.org"}
],
"has_sidebar_top_text": True,
"sidebar_top_text": "⚠ We are currently updating this version of our documentation to match this release. Please bear with us."
}
# Adding additional css files...
html_context = { "extra_css_files": ["_static/custom.css"] }
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["."]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = "_static/images/favicon.ico"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'CrafterCMSdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'CrafterCMS.tex', u'Crafter CMS Documentation',
u'Crafter Software Corporation', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'craftercms', u'Crafter CMS Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Crafter CMS', u'Crafter CMS Documentation',
author, 'Crafter CMS', 'Open Source Java-based Web CMS.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The basename for the epub file. It defaults to the project name.
#epub_basename = project
# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# Fix unsupported image types using the Pillow.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
# The default source code language for literals
highlight_language = 'java'
# Configure Edit on Github
edit_on_github_project = 'craftercms/docs'
edit_on_github_branch = version
edit_on_github_base_folder = 'source'
# Place substitution available in all files here
rst_epilog = """
.. |checkmark| unicode:: U+2713
.. |ex| unicode:: U+2718
.. |siteConfig| image:: /_static/images/configuration-site-config-icon.png
:width: 15%
.. |mainMenu| image:: /_static/images/main-menu-button.png
:width: 5%
"""
# Javadoc home and version
javadoc_base = 'http://javadoc.craftercms.org/'
javadoc_version = '3.1.0'
# Shorten external links
extlinks = {'javadoc_base_url': (javadoc_base + javadoc_version + '/%s', None )}
|
gpl-3.0
|
Lana-B/Pheno4T
|
tools/SampleAnalyzer/Interfaces/fastjet/ClusterAlgoStandard.cpp
|
4066
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2012-2013 Eric Conte, Benjamin Fuks
// The MadAnalysis development team, email: <ma5team@iphc.cnrs.fr>
//
// This file is part of MadAnalysis 5.
// Official website: <https://launchpad.net/madanalysis5>
//
// MadAnalysis 5 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.
//
// MadAnalysis 5 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 MadAnalysis 5. If not, see <http://www.gnu.org/licenses/>
//
////////////////////////////////////////////////////////////////////////////////
//SampleAnalyser headers
#include "SampleAnalyzer/Interfaces/fastjet/ClusterAlgoStandard.h"
//FastJet headers
#include <fastjet/ClusterSequence.hh>
#include <fastjet/PseudoJet.hh>
using namespace MA5;
bool ClusterAlgoStandard::SetParameter(const std::string& key, const std::string& value)
{
// radius
if (key=="r")
{
float tmp=0;
std::stringstream str;
str << value;
str >> tmp;
if (tmp<0) WARNING << "R must be positive. Using default value R = "
<< R_ << endmsg;
else R_=tmp;
}
// ptmin
else if (key=="ptmin")
{
float tmp=0;
std::stringstream str;
str << value;
str >> tmp;
if (tmp<0) WARNING << "Ptmin must be positive. Using default value Ptmin = "
<< Ptmin_ << endmsg;
else Ptmin_=tmp;
}
// p
else if (key=="p")
{
float tmp=0;
std::stringstream str;
str << value;
str >> tmp;
p_=tmp;
}
// exclusive
else if (key=="exclusive")
{
int tmp=0;
std::stringstream str;
str << value;
str >> tmp;
if (tmp==1) Exclusive_=true;
else if (tmp==0) Exclusive_=false;
else
{
WARNING << "Exclusive must be equal to 0 or 1. Using default value Exclusive = "
<< Exclusive_ << endmsg;
}
}
// other
else return false;
return true;
}
bool ClusterAlgoStandard::Initialize()
{
// Creating Jet Definition
if (JetAlgorithm_=="kt")
{
JetDefinition_ = new fastjet::JetDefinition(fastjet::kt_algorithm, R_);
}
else if (JetAlgorithm_=="antikt")
{
JetDefinition_ = new fastjet::JetDefinition(fastjet::antikt_algorithm, R_);
}
else if (JetAlgorithm_=="cambridge")
{
JetDefinition_ = new fastjet::JetDefinition(fastjet::cambridge_algorithm, R_);
}
else if (JetAlgorithm_== "genkt")
{
JetDefinition_ = new fastjet::JetDefinition(fastjet::genkt_algorithm, R_, p_);
}
else
{
JetDefinition_ = 0;
ERROR << "No FastJet algorithm found with the name " << JetAlgorithm_ << endmsg;
return false;
}
return true;
}
void ClusterAlgoStandard::PrintParam()
{
if (JetAlgorithm_=="kt") INFO << "Algorithm : kt" << endmsg;
else if (JetAlgorithm_=="cambridge") INFO << "Algorithm : Cambridge/Aachen" << endmsg;
else if (JetAlgorithm_=="antikt") INFO << "Algorithm : anti kt" << endmsg;
else if (JetAlgorithm_=="genkt") INFO << "Algorithm : generalized kt" << endmsg;
INFO << "Parameters used :" << endmsg;
INFO << "R = " << R_ << "; p = " << p_ << "; Ptmin = " << Ptmin_ << endmsg;
}
std::string ClusterAlgoStandard::GetName()
{
if (JetAlgorithm_=="kt") return "kt";
else if (JetAlgorithm_=="cambridge") return "Cambridge/Aachen";
else if (JetAlgorithm_=="antikt") return "anti kt";
else if (JetAlgorithm_=="genkt") return "generalized kt";
return "unknown";
}
std::string ClusterAlgoStandard::GetParameters()
{
std::stringstream str;
str << "R=" << R_ << " ; p=" << p_ << " ; PTmin=" << Ptmin_;
return str.str();
}
|
gpl-3.0
|
Jnig/openPCM
|
src/Jan/ZevirtBundle/Service/ClusterService.php
|
3241
|
<?php
namespace Jan\ZevirtBundle\Service;
use Jan\ZevirtBundle\Model\Ssh;
use Jan\ZevirtBundle\Entity\Cluster;
use Jan\ZevirtBundle\Entity\VirtualMachine;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Jan\ZevirtBundle\Entity\Node;
class ClusterService {
private $em;
protected $container;
public function __construct(ContainerInterface $container, $em) {
$this->em = $em;
$this->container = $container;
}
public function persist(Cluster $cluster) {
$this->em->persist($cluster);
$this->em->flush();
if ($this->container->get('control.service')->isCli()) {
$this->persistTasks($cluster);
} else {
$this->container->get('job.service')->clusterPersist($cluster);
}
}
public function remove(Cluster $cluster) {
if ($this->container->get('control.service')->isCli()) {
$this->removeTasks($cluster);
} else {
$this->container->get('job.service')->clusterRemove($cluster);
}
}
private function persistTasks(Cluster $cluster) {
foreach ($cluster->getNodes() as $node) {
foreach ($cluster->getStorages() as $storage) {
$this->container->get('node.service')->defineStorage($node, $storage);
}
}
}
private function removeTasks(Cluster $cluster) {
$nodes = $cluster->getNodes();
if (count($nodes)) {
throw new \Exception("Can't delete cluster, because it has nodes associated to it");
}
$this->em->remove($cluster);
$this->em->flush();
}
public function setMaintenanceMode(Node $node, $value) {
foreach ($node->getCluster()->getNodes() as $node) {
try {
$this->container->get('node.service')->getConnection($node)->exec('crm_attribute --name maintenance-mode --update ' . $value);
break;
} catch (\Exception $e) {
}
}
}
public function verfiyClusterConfig(Node $node) {
$out = $this->container->get('control.service')->getOutputWriter();
try {
$this->container->get('node.service')->getConnection($node)->exec('crm_verify -L -V');
} catch (\Exception $e) {
$out->writeln("Cluster has errors and can't run resources.\n" . $e->getMessage());
return 0;
}
return 1;
}
public function cibadminAdd(Cluster $cluster, $content) {
$out = $this->container->get('control.service');
foreach ($cluster->getNodes() as $node) {
try {
$this->container->get('node.service')->cibadminAdd($node, $content);
break;
} catch (\Exception $e) {
}
}
}
public function cibadminDelete(Cluster $cluster, $content) {
$out = $this->container->get('control.service');
foreach ($cluster->getNodes() as $node) {
try {
$this->container->get('node.service')->cibadminDelete($node, $content);
break;
} catch (\Exception $e) {
}
}
}
}
|
gpl-3.0
|
wenhao87/WPPlugins
|
wp-statistics/ajax.php
|
10116
|
<?php
// Setup an AJAX action to close the donation nag banner on the overview page.
function wp_statistics_close_donation_nag_action_callback() {
GLOBAL $WP_Statistics, $wpdb; // this is how you get access to the database
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option('manage_capability', 'manage_options') );
if( current_user_can( $manage_cap ) ) {
$WP_Statistics->update_option( 'disable_donation_nag', true );
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_wp_statistics_close_donation_nag', 'wp_statistics_close_donation_nag_action_callback' );
// Setup an AJAX action to delete an agent in the optimization page.
function wp_statistics_delete_agents_action_callback() {
GLOBAL $WP_Statistics, $wpdb; // this is how you get access to the database
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option('manage_capability', 'manage_options') );
if( current_user_can( $manage_cap ) ) {
$agent = $_POST['agent-name'];
if( $agent ) {
$result = $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}statistics_visitor WHERE `agent` = %s", $agent ));
if($result) {
echo sprintf(__('%s agent data deleted successfully.', 'wp_statistics'), '<code>' . $agent . '</code>');
}
else {
_e('No agent data found to remove!', 'wp_statistics');
}
} else {
_e('Please select the desired items.', 'wp_statistics');
}
} else {
_e('Access denied!', 'wp_statistics');
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_wp_statistics_delete_agents', 'wp_statistics_delete_agents_action_callback' );
// Setup an AJAX action to delete a platform in the optimization page.
function wp_statistics_delete_platforms_action_callback() {
GLOBAL $WP_Statistics, $wpdb; // this is how you get access to the database
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option('manage_capability', 'manage_options') );
if( current_user_can( $manage_cap ) ) {
$platform = $_POST['platform-name'];
if( $platform ) {
$result = $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}statistics_visitor WHERE `platform` = %s", $platform));
if($result) {
echo sprintf(__('%s platform data deleted successfully.', 'wp_statistics'), '<code>' . htmlentities( $platform, ENT_QUOTES ) . '</code>');
}
else {
_e('No platform data found to remove!', 'wp_statistics');
}
} else {
_e('Please select the desired items.', 'wp_statistics');
}
} else {
_e('Access denied!', 'wp_statistics');
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_wp_statistics_delete_platforms', 'wp_statistics_delete_platforms_action_callback' );
// Setup an AJAX action to empty a table in the optimization page.
function wp_statistics_empty_table_action_callback() {
GLOBAL $WP_Statistics, $wpdb; // this is how you get access to the database
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option('manage_capability', 'manage_options') );
if( current_user_can( $manage_cap ) ) {
$table_name = $_POST['table-name'];
if($table_name) {
switch( $table_name ) {
case 'useronline':
echo wp_statitiscs_empty_table($wpdb->prefix . 'statistics_useronline');
break;
case 'visit':
echo wp_statitiscs_empty_table($wpdb->prefix . 'statistics_visit');
break;
case 'visitors':
echo wp_statitiscs_empty_table($wpdb->prefix . 'statistics_visitor');
break;
case 'exclusions':
echo wp_statitiscs_empty_table($wpdb->prefix . 'statistics_exclusions');
break;
case 'pages':
echo wp_statitiscs_empty_table($wpdb->prefix . 'statistics_pages');
break;
case 'search':
echo wp_statitiscs_empty_table($wpdb->prefix . 'statistics_search');
break;
case 'all':
$result_string = wp_statitiscs_empty_table($wpdb->prefix . 'statistics_useronline');
$result_string .= '<br>' . wp_statitiscs_empty_table($wpdb->prefix . 'statistics_visit');
$result_string .= '<br>' . wp_statitiscs_empty_table($wpdb->prefix . 'statistics_visitor');
$result_string .= '<br>' . wp_statitiscs_empty_table($wpdb->prefix . 'statistics_exclusions');
$result_string .= '<br>' . wp_statitiscs_empty_table($wpdb->prefix . 'statistics_pages');
$result_string .= '<br>' . wp_statitiscs_empty_table($wpdb->prefix . 'statistics_search');
echo $result_string;
break;
default:
_e('Please select the desired items.', 'wp_statistics');
}
$WP_Statistics->Primary_Values();
} else {
_e('Please select the desired items.', 'wp_statistics');
}
} else {
_e('Access denied!', 'wp_statistics');
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_wp_statistics_empty_table', 'wp_statistics_empty_table_action_callback' );
// Setup an AJAX action to purge old data in the optimization page.
function wp_statistics_purge_data_action_callback() {
GLOBAL $WP_Statistics, $wpdb; // this is how you get access to the database
require($WP_Statistics->plugin_dir . '/includes/functions/purge.php');
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option('manage_capability', 'manage_options') );
if( current_user_can( $manage_cap ) ) {
$purge_days = 0;
if( array_key_exists( 'purge-days', $_POST ) ) {
// Get the number of days to purge data before.
$purge_days = intval($_POST['purge-days']);
}
echo wp_statistics_purge_data( $purge_days );
} else {
_e('Access denied!', 'wp_statistics');
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_wp_statistics_purge_data', 'wp_statistics_purge_data_action_callback' );
// Setup an AJAX action to purge visitors with more than a defined number of hits.
function wp_statistics_purge_visitor_hits_action_callback() {
GLOBAL $WP_Statistics, $wpdb; // this is how you get access to the database
require($WP_Statistics->plugin_dir . '/includes/functions/purge-hits.php');
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option('manage_capability', 'manage_options') );
if( current_user_can( $manage_cap ) ) {
$purge_hits = 10;
if( array_key_exists( 'purge-hits', $_POST ) ) {
// Get the number of days to purge data before.
$purge_hits = intval($_POST['purge-hits']);
}
if( $purge_hits < 10 ) {
_e('Number of hits must be greater than or equal to 10!', 'wp_statistics');
}
else {
echo wp_statistics_purge_visitor_hits( $purge_hits );
}
} else {
_e('Access denied!', 'wp_statistics');
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_wp_statistics_purge_visitor_hits', 'wp_statistics_purge_visitor_hits_action_callback' );
// Setup an AJAX action to purge visitors with more than a defined number of hits.
function wp_statistics_get_widget_contents_callback() {
GLOBAL $WP_Statistics, $wpdb; // this is how you get access to the database
$widgets = array( 'about', 'browsers', 'map', 'countries', 'hits', 'hitsmap', 'page', 'pages', 'quickstats', 'recent', 'referring', 'search', 'summary', 'top.visitors', 'words' );
$view_cap = wp_statistics_validate_capability( $WP_Statistics->get_option('read_capability', 'manage_options') );
if( current_user_can( $view_cap ) ) {
$widget = '';
if( array_key_exists( 'widget', $_POST ) ) {
// Get the widget we're going to display.
if( in_array( $_POST['widget'], $widgets ) ) {
$widget = $_POST['widget'];
}
}
if( 'map' == $widget || 'hitsmap' == $widget ) {
if( $WP_Statistics->get_option( 'map_type' ) == 'jqvmap' ) {
$widget = 'jqv.map';
}
else {
$widget = 'google.map';
}
}
if( '' == $widget ) {
_e('No matching widget found!', 'wp_statistics');
wp_die();
}
$ISOCountryCode = $WP_Statistics->get_country_codes();
$search_engines = wp_statistics_searchengine_list();
require( $WP_Statistics->plugin_dir . '/includes/log/widgets/' . $widget . '.php' );
switch( $widget ) {
case 'summary':
wp_statistics_generate_summary_postbox_content($search_engines);
break;
case 'quickstats':
wp_statistics_generate_quickstats_postbox_content($search_engines);
break;
case 'browsers':
wp_statistics_generate_browsers_postbox_content();
break;
case 'referring':
wp_statistics_generate_referring_postbox_content();
break;
case 'countries':
wp_statistics_generate_countries_postbox_content($ISOCountryCode);
break;
case 'jqv.map':
case 'google.map':
wp_statistics_generate_map_postbox_content($ISOCountryCode);
break;
case 'hits':
wp_statistics_generate_hits_postbox_content();
break;
case 'search':
wp_statistics_generate_search_postbox_content($search_engines);
break;
case 'words':
wp_statistics_generate_words_postbox_content($ISOCountryCode);
break;
case 'page':
$pageid = (int)$_POST['page-id'];
wp_statistics_generate_page_postbox_content( null, $pageid );
break;
case 'pages':
list( $total, $uris ) = wp_statistics_get_top_pages();
wp_statistics_generate_pages_postbox_content($total, $uris);
break;
case 'recent':
wp_statistics_generate_recent_postbox_content($ISOCountryCode);
break;
case 'top.visitors':
wp_statistics_generate_top_visitors_postbox_content($ISOCountryCode);
break;
case 'about':
wp_statistics_generate_about_postbox_content($ISOCountryCode);
break;
default:
_e( 'ERROR: Widget not found!', 'wp_statistics' );
}
} else {
_e('Access denied!', 'wp_statistics');
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_wp_statistics_get_widget_contents', 'wp_statistics_get_widget_contents_callback' );
|
gpl-3.0
|
Beirdo/gjhurlbu-plugin-video-irishtv
|
proxyconfig.py
|
1977
|
import sys
import urllib2
import httplib
import socks
class ProxyConfig:
def __init__(self, type, server, port, dns = True, user = None, password = None):
self.server = server
self.type = type
self.port = port
self.user = user
self.password = password
self.dns = dns
self.urllib2_socket = None
self.httplib_socket = None
#==============================================================================
def Enable(self):
self.urllib2_socket = None
self.httplib_socket = None
log = sys.modules[u"__main__"].log
try:
log(u"Using proxy: type %i rdns: %i server: %s port: %s user: %s pass: %s" % (self.type, self.dns, self.server, self.port, u"***", u"***") )
self.urllib2_socket = urllib2.socket.socket
self.httplib_socket = httplib.socket.socket
socks.setdefaultproxy(self.type, self.server, self.port, self.dns, self.user, self.password)
socks.wrapmodule(urllib2)
socks.wrapmodule(httplib)
except ( Exception ) as exception:
log(u"Error processing proxy settings", xbmc.LOGERROR)
log(u"Exception: " + exception.me, xbmc.LOGERROR)
def Disable(self):
if self.urllib2_socket is not None:
urllib2.socket.socket = self.urllib2_socket
if self.httplib_socket is not None:
httplib.socket.socket = self.httplib_socket
self.urllib2_socket = None
self.httplib_socket = None
def toString(self):
#string = ""
#if self.user is not None and self.password is not None:
# string = "%s:%s@" % (self.user, self.password)
#string = string + "%s:%s" % (self.server, self.port)
string = u"%s:%s" % (self.server, self.port)
return string
|
gpl-3.0
|
basdog22/Qool
|
templates/backend/charisma/groupslist.php
|
1605
|
<?php message()?>
<div class="row-fluid sortable">
<div class="box span12">
<div class="box-header well">
<h2><i class="icon-user"></i> <?php t('Groups List');?></h2>
<div class="box-icon">
<a href="#" class="btn btn-minimize"><i class="icon-chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>#</th>
<th><?php t("Title")?></th>
<th><?php t("User Level")?></th>
<th colspan="2"><?php t("Actions")?></th>
</tr>
</thead>
<?php foreach (the_list() as $k=>$v):?>
<tr>
<td><?php echo ($k+1)?></td>
<td width="60%"><a class="qoolmodal" data-toggle="modal" title="<?php t("Edit Group")?> <?php echo $v['title']?>" data-target="#myModal" href='<?php qoolinfo('home')?>/admin/edit<?php qoolinfo('theaction')?>?id=<?php echo $v['id']?>'><?php echo $v['title']?></a></td>
<td><?php echo $v['level']?></td>
<td ><a data-toggle="modal" title="<?php t("Edit Group")?> <?php echo $v['title']?>" data-target="#myModal" class="btn btn-warning qoolmodal" href='<?php qoolinfo('home')?>/admin/edit<?php qoolinfo('theaction')?>?id=<?php echo $v['id']?>'><i class=" icon-edit"> </i><?php t("Edit")?></a></td>
<td ><a class="btn btn-danger warnme" title="<?php t('Delete')?>" rel="<?php t('Please revise your action. Are you sure you want to do this?')?>" href='<?php qoolinfo('home')?>/admin/del<?php qoolinfo('theaction')?>?id=<?php echo $v['id']?>'><i class=" icon-remove"> </i><?php t("Delete")?></a></td>
</tr>
<?php endforeach;?>
</table>
</div>
</div><!--/span-->
</div><!--/row-->
|
gpl-3.0
|
vorburger/LeviatorWorld
|
src/main/java/ch/vorburger/meta/adaptable/AbstractAdaptable.java
|
627
|
package ch.vorburger.meta.adaptable;
import java.util.Optional;
public abstract class AbstractAdaptable implements Adaptable {
protected abstract <T> Optional<T> getAdapted(Class<T> clazz);
@Override
public final <T> T adaptTo(Class<T> clazz) throws IllegalArgumentException {
Optional<T> adapted = getAdapted(clazz);
if (adapted.isPresent())
return adapted.get();
else
throw new IllegalArgumentException("cannot adapt " + this.getClass() + " to " + clazz);
}
@Override
public final boolean isAdaptableTo(Class<?> clazz) {
Optional<?> adapted = getAdapted(clazz);
return adapted.isPresent();
}
}
|
gpl-3.0
|
sethten/MoDesserts
|
mcp50/temp/src/minecraft_server/net/minecraft/src/EntityAINearestAttackableTargetSorter.java
|
1192
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.util.Comparator;
// Referenced classes of package net.minecraft.src:
// Entity, EntityAINearestAttackableTarget
public class EntityAINearestAttackableTargetSorter
implements Comparator
{
private Entity field_48471_b;
final EntityAINearestAttackableTarget field_48472_a; /* synthetic field */
public EntityAINearestAttackableTargetSorter(EntityAINearestAttackableTarget p_i1016_1_, Entity p_i1016_2_)
{
field_48472_a = p_i1016_1_;
super();
field_48471_b = p_i1016_2_;
}
public int func_48470_a(Entity p_48470_1_, Entity p_48470_2_)
{
double d = field_48471_b.func_102_b(p_48470_1_);
double d1 = field_48471_b.func_102_b(p_48470_2_);
if(d < d1)
{
return -1;
}
return d <= d1 ? 0 : 1;
}
public int compare(Object p_compare_1_, Object p_compare_2_)
{
return func_48470_a((Entity)p_compare_1_, (Entity)p_compare_2_);
}
}
|
gpl-3.0
|
manuelgu/PlotSquared
|
Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java
|
7598
|
package com.plotsquared.bukkit.object;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.PlotGameMode;
import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.WeatherType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventException;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.UUID;
import org.bukkit.plugin.RegisteredListener;
public class BukkitPlayer extends PlotPlayer {
public final Player player;
public boolean offline;
private UUID uuid;
private String name;
/**
* <p>Please do not use this method. Instead use
* BukkitUtil.getPlayer(Player), as it caches player objects.</p>
* @param player
*/
public BukkitPlayer(Player player) {
this.player = player;
super.populatePersistentMetaMap();
}
public BukkitPlayer(Player player, boolean offline) {
this.player = player;
this.offline = offline;
super.populatePersistentMetaMap();
}
@Override
public Location getLocation() {
Location location = super.getLocation();
return location == null ? BukkitUtil.getLocation(this.player) : location;
}
@Override
public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
}
return this.uuid;
}
@Override public long getLastPlayed() {
return this.player.getLastPlayed();
}
@Override
public boolean canTeleport(Location loc) {
org.bukkit.Location to = BukkitUtil.getLocation(loc);
org.bukkit.Location from = player.getLocation();
PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to);
RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PS.imp().getPluginName())) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
if (event.isCancelled() || !event.getTo().equals(to)) {
return false;
}
event = new PlayerTeleportEvent(player, to, from);
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PS.imp().getPluginName())) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
return true;
}
@Override
public boolean hasPermission(String permission) {
if (this.offline && EconHandler.manager != null) {
return EconHandler.manager.hasPermission(getName(), permission);
}
return this.player.hasPermission(permission);
}
@Override
public void sendMessage(String message) {
if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || (System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());
this.player.sendMessage(message);
}
}
@Override
public void teleport(Location location) {
if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) {
return;
}
this.player.teleport(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, location.getY(), location.getZ() + 0.5,
location.getYaw(), location.getPitch()), TeleportCause.COMMAND);
}
@Override
public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
}
@Override
public boolean isOnline() {
return !this.offline && this.player.isOnline();
}
@Override
public void setCompassTarget(Location location) {
this.player.setCompassTarget(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ()));
}
@Override
public Location getLocationFull() {
return BukkitUtil.getLocationFull(this.player);
}
@Override
public void setWeather(PlotWeather weather) {
switch (weather) {
case CLEAR:
this.player.setPlayerWeather(WeatherType.CLEAR);
break;
case RAIN:
this.player.setPlayerWeather(WeatherType.DOWNFALL);
break;
case RESET:
this.player.resetPlayerWeather();
break;
default:
this.player.resetPlayerWeather();
break;
}
}
@Override
public PlotGameMode getGameMode() {
switch (this.player.getGameMode()) {
case ADVENTURE:
return PlotGameMode.ADVENTURE;
case CREATIVE:
return PlotGameMode.CREATIVE;
case SPECTATOR:
return PlotGameMode.SPECTATOR;
case SURVIVAL:
return PlotGameMode.SURVIVAL;
default:
return PlotGameMode.NOT_SET;
}
}
@Override
public void setGameMode(PlotGameMode gameMode) {
switch (gameMode) {
case ADVENTURE:
this.player.setGameMode(GameMode.ADVENTURE);
break;
case CREATIVE:
this.player.setGameMode(GameMode.CREATIVE);
break;
case SPECTATOR:
this.player.setGameMode(GameMode.SPECTATOR);
break;
case SURVIVAL:
this.player.setGameMode(GameMode.SURVIVAL);
break;
default:
this.player.setGameMode(GameMode.SURVIVAL);
break;
}
}
@Override
public void setTime(long time) {
if (time != Long.MAX_VALUE) {
this.player.setPlayerTime(time, false);
} else {
this.player.resetPlayerTime();
}
}
@Override
public void setFlight(boolean fly) {
this.player.setAllowFlight(fly);
}
@Override
public boolean getFlight() {
return player.getAllowFlight();
}
@Override
public void playMusic(Location location, int id) {
//noinspection deprecation
this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id);
}
@Override
public void kick(String message) {
this.player.kickPlayer(message);
}
@Override public void stopSpectating() {
if (getGameMode() == PlotGameMode.SPECTATOR) {
this.player.setSpectatorTarget(null);
}
}
@Override
public boolean isBanned() {
return this.player.isBanned();
}
}
|
gpl-3.0
|
Cubiccl/Command-Generator
|
src/fr/cubiccl/generator/gameobject/advancements/Requirement.java
|
1786
|
package fr.cubiccl.generator.gameobject.advancements;
import java.awt.Component;
import fr.cubiccl.generator.gui.component.interfaces.IObjectList;
import fr.cubiccl.generator.gui.component.panel.CGPanel;
import fr.cubiccl.generator.gui.component.panel.advancement.PanelRequirement;
import fr.cubiccl.generator.gui.component.panel.utils.ListProperties;
import fr.cubiccl.generator.gui.component.panel.utils.PanelObjectList;
import fr.cubiccl.generator.utils.CommandGenerationException;
import fr.cubiccl.generator.utils.Text;
/** Represents a Requirement for an Advancement. Only used for {@link PanelObjectList Object Lists}. */
public class Requirement implements IObjectList<Requirement>
{
/** The list of criteria in this Requirement. */
public AdvancementCriterion[] criteria = new AdvancementCriterion[0];
public Requirement()
{}
public Requirement(AdvancementCriterion[] criteria)
{
this.criteria = criteria;
}
@Override
public CGPanel createPanel(ListProperties properties)
{
PanelRequirement p = new PanelRequirement((Advancement) properties.get("advancement"));
p.setupFrom(this.criteria);
return p;
}
@Override
public Requirement duplicate(Requirement object)
{
this.criteria = new AdvancementCriterion[object.criteria.length];
for (int i = 0; i < this.criteria.length; ++i)
this.criteria[i] = new AdvancementCriterion().duplicate(object.criteria[i]);
return this;
}
@Override
public Component getDisplayComponent()
{
return null;
}
@Override
public String getName(int index)
{
return this.criteria.length + " " + new Text("advancement.requirements");
}
@Override
public Requirement update(CGPanel panel) throws CommandGenerationException
{
this.criteria = ((PanelRequirement) panel).generate();
return this;
}
}
|
gpl-3.0
|
Glynn-Taylor/9-Gates
|
src/game/states/State_PREFAB_EDITOR.java
|
14979
|
/*******************************************************************************
* Copyright (c) 2013 Glynn Taylor.
* All rights reserved. This program and the accompanying materials,
* (excluding imported libraries, such as LWJGL and Slick2D)
* are made available under the terms of the GNU Public License
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Glynn Taylor - initial API and implementation
******************************************************************************/
/*
* A state that handles how the prefab editor functions
*/
package game.states;
import game.graphics.GUI_Layer;
import game.graphics.GUI_PrefabMap;
import game.graphics.GUI_PrefabPalette;
import game.level.map.Prefab;
import game.level.map.TileDefinition;
import game.level.map.TileMapGenerator;
import game.states.Game.GameState;
import game.util.PrefabBrowser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.swing.JOptionPane;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
public class State_PREFAB_EDITOR extends State {
private final int RoomWidth = 100;
private final int RoomHeight = 75;
private Prefab prefab = new Prefab(RoomWidth, RoomHeight);
private final int ScreenHeight = Game.Height;
private float CameraX = -16;
private float CameraY = 30;
private float CameraZ = 0;
private final float MapRotatef = 180;
private final long InputTimePassed = 0;
private final long InputDelayMili = 100;
private int FPS;
private long LastSecond;
private final float CameraDisplacement = TileMapGenerator.CUBE_LENGTH;
private GUI_Layer ButtonGUILayer;
private GUI_Layer MenuGUILayer;
private final GUI_PrefabMap PrefabMap = new GUI_PrefabMap(90, 68, 493, 389,
prefab);
private final GUI_PrefabPalette PrefabPalette = new GUI_PrefabPalette(53,
533, 558, 62, 634, 558, 62);
public void Create(int xLimit, int yLimit) {
prefab = new Prefab(xLimit, yLimit);
PrefabMap.setPrefab(prefab);
}
@Override
protected void Init() {
ButtonGUILayer = new GUI_Layer();
ButtonGUILayer.SetEnabled(true);
MenuGUILayer = new GUI_Layer();
MenuGUILayer.SetEnabled(false);
int ButtonStartX = 712;
int ButtonStartY = 600;
float xScale = 1.5f;
float yScale = 1.5f;
int Spacing = 145;
int menuButtonStartX = 640 - 128;
int menuButtonStartY = 150;
float menuXScale = 1f;
float menuYScale = 1f;
int menuSpacing = 110;
try {
GL11.glEnable(GL11.GL_TEXTURE_2D);
BackGroundImage = TextureLoader.getTexture("PNG", ResourceLoader
.getResourceAsStream("res/Materials/GUI/UI/GUIPrefab.png"));
Texture button1 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/UI/SaveIconButton.png"),
false, GL11.GL_NEAREST);
ButtonGUILayer.AddButton(ButtonStartX + Spacing * 0, ButtonStartY,
(int) (button1.getImageWidth() * xScale),
(int) (button1.getImageHeight() * yScale), button1);
Texture button2 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/UI/LoadIconButton.png"),
false, GL11.GL_NEAREST);
ButtonGUILayer.AddButton(ButtonStartX + Spacing * 1, ButtonStartY,
(int) (button2.getImageWidth() * xScale),
(int) (button2.getImageHeight() * yScale), button2);
Texture button3 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/UI/OptionsIconButton.png"),
false, GL11.GL_NEAREST);
ButtonGUILayer.AddButton(ButtonStartX + Spacing * 2, ButtonStartY,
(int) (button3.getImageWidth() * xScale),
(int) (button3.getImageHeight() * yScale), button3);
Texture button4 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/UI/HelpIconButton.png"),
false, GL11.GL_NEAREST);
ButtonGUILayer.AddButton(ButtonStartX + Spacing * 3, ButtonStartY,
(int) (button4.getImageWidth() * xScale),
(int) (button4.getImageHeight() * yScale), button4);
Texture mButton0 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/Buttons/ReturnButton.png"),
false, GL11.GL_NEAREST);
MenuGUILayer.AddButton(menuButtonStartX, menuButtonStartY
+ menuSpacing * 0,
(int) (mButton0.getImageWidth() * menuXScale),
(int) (mButton0.getImageHeight() * menuYScale), mButton0);
Texture mButton1 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/Buttons/LoadButton.png"),
false, GL11.GL_NEAREST);
MenuGUILayer.AddButton(menuButtonStartX, menuButtonStartY
+ menuSpacing * 1,
(int) (mButton1.getImageWidth() * menuXScale),
(int) (mButton1.getImageHeight() * menuYScale), mButton1);
Texture mButton2 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/Buttons/SaveButton.png"),
false, GL11.GL_NEAREST);
MenuGUILayer.AddButton(menuButtonStartX, menuButtonStartY
+ menuSpacing * 2,
(int) (mButton2.getImageWidth() * menuXScale),
(int) (mButton2.getImageHeight() * menuYScale), mButton2);
Texture mButton3 = TextureLoader
.getTexture(
"PNG",
ResourceLoader
.getResourceAsStream("res/Materials/GUI/Buttons/BackButton.png"),
false, GL11.GL_NEAREST);
MenuGUILayer.AddButton(menuButtonStartX, menuButtonStartY
+ menuSpacing * 3,
(int) (mButton3.getImageWidth() * menuXScale),
(int) (mButton3.getImageHeight() * menuYScale), mButton3);
} catch (IOException e) {
e.printStackTrace();
}
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_LIGHT0);
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GLU.gluPerspective(45.0f,
(float) Display.getWidth() / (float) Display.getHeight(), 0.1f,
600.0f);
GLU.gluLookAt(0, 20, 50, 0, -2, -100, 0, -1, 0);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
@Override
protected void Update() {
FPS++;
if (System.currentTimeMillis() - LastSecond > 1000) {
LastSecond = System.currentTimeMillis();
System.out.println("Running PREFAB EDITOR: "
+ Integer.toString(FPS));
FPS = 0;
}
}
private void DisableAllMenus() {
MenuGUILayer.SetEnabled(false);
}
@Override
protected void ProcessInput() {
MenuGUILayer
.ProcessInput(MouseLastX, MouseLastY, Mouse.isButtonDown(0));
ButtonGUILayer.ProcessInput(MouseLastX, MouseLastY,
Mouse.isButtonDown(0));
PrefabMap.ProcessInput(MouseLastX, ScreenHeight - MouseLastY,
Mouse.isButtonDown(0), PrefabPalette.getSelectedTile());
PrefabPalette.ProcessInput(MouseLastX, ScreenHeight - MouseLastY,
Mouse.isButtonDown(0));
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
DisableAllMenus();
MenuGUILayer.toggleEnabled();
}
if (Keyboard.isKeyDown(Keyboard.KEY_0)) {
System.out.println(CameraX);
System.out.println(CameraY);
System.out.println(CameraZ);
}
if (ButtonGUILayer.isButtonDown(2)) {
DisableAllMenus();
MenuGUILayer.toggleEnabled();
}
if (ButtonGUILayer.isButtonDown(1))
LoadPrefab();
if (ButtonGUILayer.isButtonDown(0))
SavePrefab();
if (MenuGUILayer.isButtonDown(0)) {
DisableAllMenus();
}
// Save
if (MenuGUILayer.isButtonDown(1)) {
}
// Load
if (MenuGUILayer.isButtonDown(2)) {
}
if (MenuGUILayer.isButtonDown(3)) {
DisableAllMenus();
GameState.SwitchToState(GameState.State_MapEditor,
GameState.State_Menu_MapEditor);
}
if (ButtonGUILayer.isButtonDown(3)) {
JOptionPane
.showMessageDialog(
null,
"Use the squares of color to the bottom left to select a color,"
+ System.getProperty("line.separator")
+ "then click on a tile on the top left to alter the prefab. View user manual for reference.",
"Help", JOptionPane.PLAIN_MESSAGE);
}
if (System.currentTimeMillis() - InputTimePassed >= InputDelayMili) {
if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
MoveCamera(0, -1);
} else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
MoveCamera(0, 1);
}
if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
MoveCamera(-1, 0);
} else if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
MoveCamera(1, 0);
}
}
if (Keyboard.isKeyDown(Keyboard.KEY_Q)) {
CameraZ -= 1f;
CameraX -= 0.01f;
CameraY -= 0.2f;
}
if (Keyboard.isKeyDown(Keyboard.KEY_E)) {
CameraZ += 1f;
CameraX += 0.01f;
CameraY += 0.2f;
}
}
private void SavePrefab() {
if (CheckBoundary(prefab.getMap()) & CheckMiddle(prefab.getMap())
& CheckConnected(prefab.getMap())) {
PrefabBrowser fb = new PrefabBrowser();
try {
String path = fb.GetSavePath();
if (path != null) {
FileOutputStream fileOut = new FileOutputStream(path
+ ".prefab");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(prefab);
out.close();
fileOut.close();
}
} catch (IOException i) {
i.printStackTrace();
}
} else {
JOptionPane
.showMessageDialog(
null,
"A tile is not connected, the center of the room is a wall, or a boundary tile is floor.",
"Room not valid", JOptionPane.PLAIN_MESSAGE);
}
}
private boolean CheckConnected(int[][] map) {
int xRef = 0;
int yRef = 0;
int count = 0;
String[][] refMap = new String[map.length][map[0].length];
for (int y = 0; y < map.length; y++) {
for (int x = 0; x < map[0].length; x++) {
if (map[y][x] < 0) {
count++;
xRef = x;
yRef = y;
refMap[y][x] = "O";
} else {
refMap[y][x] = "X";
}
}
}
int[] burnedCount = { 0 };
BurnNode(refMap, xRef, yRef, burnedCount);
if (burnedCount[0] == count) {
return true;
} else {
System.out.println("Unconnected tile");
return false;
}
}
private void BurnNode(String[][] refMap, int xRef, int yRef,
int[] burnedCount) {
if (refMap[yRef][xRef] == "O") {
refMap[yRef][xRef] = "X";
burnedCount[0]++;
if (yRef + 1 < refMap.length)
BurnNode(refMap, xRef, yRef + 1, burnedCount);
if (yRef - 1 >= 0)
BurnNode(refMap, xRef, yRef - 1, burnedCount);
if (xRef + 1 < refMap[0].length)
BurnNode(refMap, xRef + 1, yRef, burnedCount);
if (xRef - 1 >= 0)
BurnNode(refMap, xRef - 1, yRef, burnedCount);
}
}
private boolean CheckMiddle(int[][] map) {
if (map[map.length / 2][map[0].length / 2] >= 0) {
System.out.println("Middle tile");
return false;
}
return true;
}
private boolean CheckBoundary(int[][] map) {
boolean valid = true;
for (int y = 0; y < map.length; y++) {
if (map[y][0] < 0 || map[y][map[0].length - 1] < 0)
valid = false;
}
for (int x = 0; x < map[0].length; x++) {
if (map[0][x] < 0 || map[map.length - 1][x] < 0)
valid = false;
}
if (!valid)
System.out.println("Boundary");
return valid;
}
public void LoadPrefab() {
PrefabBrowser fb = new PrefabBrowser();
try {
String path = fb.GetOpenPath();
if (path != null) {
File f = new File(path);
FileInputStream fileIn = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fileIn);
Prefab p = (Prefab) in.readObject();
prefab = p;
PrefabMap.setPrefab(prefab);
in.close();
fileIn.close();
fb.DestroyMe();
}
} catch (IOException | ClassNotFoundException e) {
System.out.println("ERROR: Failed to load image @ Filebrowser");
e.printStackTrace();
}
}
private void MoveCamera(int x, int y) {
CameraY -= CameraDisplacement * y;
CameraX += CameraDisplacement * x;
}
@Override
protected void Render() {
OrthoMode();
ModelMode();
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glEnable(GL11.GL_TEXTURE_2D);
DrawBackground();
ButtonGUILayer.Render();
if (PrefabMap != null)
PrefabMap.Render();
PrefabPalette.Render();
Color.white.bind();
MenuGUILayer.Render();
ProjectionMode();
ModelMode();
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glTranslatef(CameraX, CameraY, -20f + CameraZ); // Move Right 1.5
GL11.glTranslatef(9, -45, 0);
GL11.glRotatef(MapRotatef, 0f, 1.0f, 0f);
RenderPrefab();
}
private void RenderPrefab() {
for (int y = 0; y < prefab.GetHeight(); y++) {
for (int x = 0; x < prefab.GetWidth(); x++) {
GL11.glTranslatef(x * TileMapGenerator.CUBE_LENGTH + 0.7f, y
* TileMapGenerator.CUBE_LENGTH + 0.7f, 0);
if (prefab.getColorRef(x, y) < 0) {
try {
DrawFloor(x, y, prefab.getColorRef(x, y));
} catch (Exception e) {
}
} else {
DrawWall(x, y, prefab.getColorRef(x, y));
}
GL11.glTranslatef(-x * TileMapGenerator.CUBE_LENGTH - 0.7f, -y
* TileMapGenerator.CUBE_LENGTH - 0.7f, 0);
}
}
}
private void DrawWall(int x, int y, int i) {
// BOTTOM
GL11.glBegin(GL11.GL_QUADS);
TileDefinition.setColor(i);
GL11.glNormal3f(0, -1, 0);
GL11.glVertex3f(-1f, -1f, 0f);
GL11.glVertex3f(1f, -1f, 0);
GL11.glVertex3f(1f, 1f, 0f);
GL11.glVertex3f(-1f, 1f, 0f);
// SIDES
GL11.glNormal3f(1, 0, 0);
GL11.glVertex3f(-1f, -1f, 0f);
GL11.glVertex3f(1f, -1f, 0f);
GL11.glVertex3f(1f, -1f, -4f);
GL11.glVertex3f(-1f, -1f, -4f);
GL11.glNormal3f(0, 0, 1);
GL11.glVertex3f(1f, -1f, 0f);
GL11.glVertex3f(1f, 1f, 0f);
GL11.glVertex3f(1f, 1f, -4f);
GL11.glVertex3f(1f, -1f, -4f);
GL11.glNormal3f(1, 0, 0);
GL11.glVertex3f(1f, 1f, 0f);
GL11.glVertex3f(-1f, 1f, 0f);
GL11.glVertex3f(-1f, 1f, -4f);
GL11.glVertex3f(1f, 1f, -4f);
GL11.glNormal3f(0, 0, 1);
GL11.glVertex3f(-1f, 1f, 0f);
GL11.glVertex3f(-1f, -1f, 0f);
GL11.glVertex3f(-1f, -1f, -4f);
GL11.glVertex3f(-1f, 1f, -4f);
// BOTTOM
GL11.glNormal3f(0, 1, 0);
GL11.glVertex3f(-1f, -1f, -4f);
GL11.glVertex3f(1f, -1f, -4f);
GL11.glVertex3f(1f, 1f, -4f);
GL11.glVertex3f(-1f, 1f, -4f);
GL11.glEnd();
}
private void DrawFloor(int x, int y, int i) {
GL11.glBegin(GL11.GL_QUADS);
TileDefinition.setColor(i);
GL11.glNormal3f(0, 1, 0);
GL11.glVertex3f(-1f, -1f, 0f);
GL11.glVertex3f(1f, -1f, 0f);
GL11.glVertex3f(1f, 1f, 0f);
GL11.glVertex3f(-1f, 1f, 0f);
GL11.glEnd();
}
@Override
public void Unload() {
}
}
|
gpl-3.0
|
IndustriaLeuven/dolibarr
|
htdocs/core/lib/project.lib.php
|
40410
|
<?php
/* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2010 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/core/lib/project.lib.php
* \brief Functions used by project module
* \ingroup project
*/
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
/**
* Prepare array with list of tabs
*
* @param Object $object Object related to tabs
* @return array Array of tabs to show
*/
function project_prepare_head($object)
{
global $langs, $conf, $user;
$h = 0;
$head = array();
$head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$object->id;
$head[$h][1] = $langs->trans("Project");
$head[$h][2] = 'project';
$h++;
$head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$object->id;
$head[$h][1] = $langs->trans("ProjectContact");
$head[$h][2] = 'contact';
$h++;
if (! empty($conf->fournisseur->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->commande->enabled)
|| ! empty($conf->facture->enabled) || ! empty($conf->contrat->enabled)
|| ! empty($conf->ficheinter->enabled) || ! empty($conf->agenda->enabled) || ! empty($conf->deplacement->enabled))
{
$head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$object->id;
$head[$h][1] = $langs->trans("ProjectOverview");
$head[$h][2] = 'element';
$h++;
}
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf,$langs,$object,$head,$h,'project');
if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
{
$nbNote = 0;
if(!empty($object->note_private)) $nbNote++;
if(!empty($object->note_public)) $nbNote++;
$head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$object->id;
$head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
$head[$h][2] = 'notes';
$h++;
}
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$upload_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($object->ref);
$nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview\.png)$'));
$head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$object->id;
$head[$h][1] = $langs->trans('Documents');
if($nbFiles > 0) $head[$h][1].= ' <span class="badge">'.$nbFiles.'</span>';
$head[$h][2] = 'document';
$h++;
if (empty($conf->global->PROJECT_HIDE_TASKS))
{
// Then tab for sub level of projet, i mean tasks
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$object->id;
$head[$h][1] = $langs->trans("Tasks");
$head[$h][2] = 'tasks';
$h++;
$head[$h][0] = DOL_URL_ROOT.'/projet/ganttview.php?id='.$object->id;
$head[$h][1] = $langs->trans("Gantt");
$head[$h][2] = 'gantt';
$h++;
}
complete_head_from_modules($conf,$langs,$object,$head,$h,'project','remove');
return $head;
}
/**
* Prepare array with list of tabs
*
* @param Object $object Object related to tabs
* @return array Array of tabs to show
*/
function task_prepare_head($object)
{
global $langs, $conf, $user;
$h = 0;
$head = array();
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/task.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
$head[$h][1] = $langs->trans("Card");
$head[$h][2] = 'task_task';
$h++;
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
$head[$h][1] = $langs->trans("TaskRessourceLinks");
$head[$h][2] = 'task_contact';
$h++;
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
$head[$h][1] = $langs->trans("TimeSpent");
$head[$h][2] = 'task_time';
$h++;
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf,$langs,$object,$head,$h,'task');
if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
{
$nbNote = 0;
if(!empty($object->note_private)) $nbNote++;
if(!empty($object->note_public)) $nbNote++;
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/note.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
$head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
$head[$h][2] = 'task_notes';
$h++;
}
$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/document.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
$filesdir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($object->project->ref) . '/' .dol_sanitizeFileName($object->ref);
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$listoffiles=dol_dir_list($filesdir,'files',1,'','thumbs');
$head[$h][1] = (count($listoffiles)?$langs->trans('DocumentsNb',count($listoffiles)):$langs->trans('Documents'));
$head[$h][2] = 'task_document';
$h++;
complete_head_from_modules($conf,$langs,$object,$head,$h,'task','remove');
return $head;
}
/**
* Prepare array with list of tabs
*
* @param string $mode Mode
* @return array Array of tabs to show
*/
function project_timesheet_prepare_head($mode)
{
global $langs, $conf, $user;
$h = 0;
$head = array();
$h = 0;
if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK))
{
$head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($mode?'?mode='.$mode:'');
$head[$h][1] = $langs->trans("InputPerWeek");
$head[$h][2] = 'inputperweek';
$h++;
}
if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME))
{
$head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($mode?'?mode='.$mode:'');
$head[$h][1] = $langs->trans("InputPerDay");
$head[$h][2] = 'inputperday';
$h++;
}
/*if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERACTION))
{
$head[$h][0] = DOL_URL_ROOT."/projet/activity/peraction.php".($mode?'?mode='.$mode:'');
$head[$h][1] = $langs->trans("InputPerAction");
$head[$h][2] = 'inputperaction';
$h++;
}*/
complete_head_from_modules($conf,$langs,null,$head,$h,'project_timesheet');
complete_head_from_modules($conf,$langs,null,$head,$h,'project_timesheet','remove');
return $head;
}
/**
* Prepare array with list of tabs
*
* @return array Array of tabs to show
*/
function project_admin_prepare_head()
{
global $langs, $conf, $user;
$h = 0;
$head = array();
$h = 0;
$head[$h][0] = DOL_URL_ROOT."/projet/admin/project.php";
$head[$h][1] = $langs->trans("Projects");
$head[$h][2] = 'project';
$h++;
complete_head_from_modules($conf,$langs,null,$head,$h,'project_admin');
$head[$h][0] = DOL_URL_ROOT."/projet/admin/project_extrafields.php";
$head[$h][1] = $langs->trans("ExtraFieldsProject");
$head[$h][2] = 'attributes';
$h++;
$head[$h][0] = DOL_URL_ROOT.'/projet/admin/project_task_extrafields.php';
$head[$h][1] = $langs->trans("ExtraFieldsProjectTask");
$head[$h][2] = 'attributes_task';
$h++;
complete_head_from_modules($conf,$langs,null,$head,$h,'project_admin','remove');
return $head;
}
/**
* Show task lines with a particular parent
*
* @param string $inc Line number (start to 0, then increased by recursive call)
* @param string $parent Id of parent project to show (0 to show all)
* @param Task[] $lines Array of lines
* @param int $level Level (start to 0, then increased/decrease by recursive call)
* @param string $var Color
* @param int $showproject Show project columns
* @param int $taskrole Array of roles of user for each tasks
* @param int $projectsListId List of id of project allowed to user (string separated with comma)
* @param int $addordertick Add a tick to move task
* @return void
*/
function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$taskrole, $projectsListId='', $addordertick=0)
{
global $user, $bc, $langs;
global $projectstatic, $taskstatic;
$lastprojectid=0;
$projectsArrayId=explode(',',$projectsListId);
$numlines=count($lines);
// We declare counter as global because we want to edit them into recursive call
global $total_projectlinesa_spent,$total_projectlinesa_planned,$total_projectlinesa_spent_if_planned;
if ($level == 0)
{
$total_projectlinesa_spent=0;
$total_projectlinesa_planned=0;
$total_projectlinesa_spent_if_planned=0;
}
for ($i = 0 ; $i < $numlines ; $i++)
{
if ($parent == 0) $level = 0;
// Process line
// print "i:".$i."-".$lines[$i]->fk_project.'<br>';
if ($lines[$i]->fk_parent == $parent)
{
// Show task line.
$showline=1;
$showlineingray=0;
// If there is filters to use
if (is_array($taskrole))
{
// If task not legitimate to show, search if a legitimate task exists later in tree
if (! isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent)
{
// So search if task has a subtask legitimate to show
$foundtaskforuserdeeper=0;
searchTaskInChild($foundtaskforuserdeeper,$lines[$i]->id,$lines,$taskrole);
//print '$foundtaskforuserpeeper='.$foundtaskforuserdeeper.'<br>';
if ($foundtaskforuserdeeper > 0)
{
$showlineingray=1; // We will show line but in gray
}
else
{
$showline=0; // No reason to show line
}
}
}
else
{
// Caller did not ask to filter on tasks of a specific user (this probably means he want also tasks of all users, into public project
// or into all other projects if user has permission to).
if (empty($user->rights->projet->all->lire))
{
// User is not allowed on this project and project is not public, so we hide line
if (! in_array($lines[$i]->fk_project, $projectsArrayId))
{
// Note that having a user assigned to a task into a project user has no permission on, should not be possible
// because assignement on task can be done only on contact of project.
// If assignement was done and after, was removed from contact of project, then we can hide the line.
$showline=0;
}
}
}
if ($showline)
{
// Break on a new project
if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
{
$var = !$var;
$lastprojectid=$lines[$i]->fk_project;
}
print '<tr '.$bc[$var].' id="row-'.$lines[$i]->id.'">'."\n";
if ($showproject)
{
// Project ref
print "<td>";
//if ($showlineingray) print '<i>';
$projectstatic->id=$lines[$i]->fk_project;
$projectstatic->ref=$lines[$i]->projectref;
$projectstatic->public=$lines[$i]->public;
if ($lines[$i]->public || in_array($lines[$i]->fk_project,$projectsArrayId) || ! empty($user->rights->projet->all->lire)) print $projectstatic->getNomUrl(1);
else print $projectstatic->getNomUrl(1,'nolink');
//if ($showlineingray) print '</i>';
print "</td>";
// Project status
print '<td>';
$projectstatic->statut=$lines[$i]->projectstatus;
print $projectstatic->getLibStatut(2);
print "</td>";
}
// Ref of task
print '<td>';
if ($showlineingray)
{
print '<i>'.img_object('','projecttask').' '.$lines[$i]->ref.'</i>';
}
else
{
$taskstatic->id=$lines[$i]->id;
$taskstatic->ref=$lines[$i]->ref;
$taskstatic->label=($taskrole[$lines[$i]->id]?$langs->trans("YourRole").': '.$taskrole[$lines[$i]->id]:'');
print $taskstatic->getNomUrl(1,'withproject');
}
print '</td>';
// Title of task
print "<td>";
if ($showlineingray) print '<i>';
else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/task.php?id='.$lines[$i]->id.'&withproject=1">';
for ($k = 0 ; $k < $level ; $k++)
{
print " ";
}
print $lines[$i]->label;
if ($showlineingray) print '</i>';
else print '</a>';
print "</td>\n";
// Date start
print '<td align="center">';
print dol_print_date($lines[$i]->date_start,'dayhour');
print '</td>';
// Date end
print '<td align="center">';
print dol_print_date($lines[$i]->date_end,'dayhour');
print '</td>';
$plannedworkloadoutputformat='allhourmin';
$timespentoutputformat='allhourmin';
if (! empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat=$conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT;
if (! empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat=$conf->global->PROJECT_TIME_SPENT_FORMAT;
// Planned Workload (in working hours)
print '<td align="right">';
$fullhour=convertSecondToTime($lines[$i]->planned_workload,$plannedworkloadoutputformat);
$workingdelay=convertSecondToTime($lines[$i]->planned_workload,'all',86400,7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks
if ($lines[$i]->planned_workload != '')
{
print $fullhour;
// TODO Add delay taking account of working hours per day and working day per week
//if ($workingdelay != $fullhour) print '<br>('.$workingdelay.')';
}
//else print '--:--';
print '</td>';
// Progress declared
print '<td align="right">';
if ($lines[$i]->progress != '')
{
print $lines[$i]->progress.' %';
}
print '</td>';
// Time spent
print '<td align="right">';
if ($showlineingray) print '<i>';
else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.($showproject?'':'&withproject=1').'">';
if ($lines[$i]->duration) print convertSecondToTime($lines[$i]->duration,$timespentoutputformat);
else print '--:--';
if ($showlineingray) print '</i>';
else print '</a>';
print '</td>';
// Progress calculated (Note: ->duration is time spent)
print '<td align="right">';
if ($lines[$i]->planned_workload || $lines[$i]->duration)
{
if ($lines[$i]->planned_workload) print round(100 * $lines[$i]->duration / $lines[$i]->planned_workload,2).' %';
else print $langs->trans('WorkloadNotDefined');
}
print '</td>';
// Tick to drag and drop
if ($addordertick)
{
print '<td align="center" class="tdlineupdown hideonsmartphone"> </td>';
}
print "</tr>\n";
if (! $showlineingray) $inc++;
$level++;
if ($lines[$i]->id) projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick);
$level--;
$total_projectlinesa_spent += $lines[$i]->duration;
$total_projectlinesa_planned += $lines[$i]->planned_workload;
if ($lines[$i]->planned_workload) $total_projectlinesa_spent_if_planned += $lines[$i]->duration;
}
}
else
{
//$level--;
}
}
if (($total_projectlinesa_planned > 0 || $total_projectlinesa_spent > 0) && $level==0)
{
print '<tr class="liste_total nodrag nodrop">';
print '<td class="liste_total">'.$langs->trans("Total").'</td>';
if ($showproject) print '<td></td><td></td>';
print '<td></td>';
print '<td></td>';
print '<td></td>';
print '<td align="right" class="nowrap liste_total">';
print convertSecondToTime($total_projectlinesa_planned, 'allhourmin');
print '</td>';
print '<td></td>';
print '<td align="right" class="nowrap liste_total">';
print convertSecondToTime($total_projectlinesa_spent, 'allhourmin');
print '</td>';
print '<td align="right" class="nowrap liste_total">';
if ($total_projectlinesa_planned) print round(100 * $total_projectlinesa_spent / $total_projectlinesa_planned,2).' %';
print '</td>';
if ($addordertick) print '<td class="hideonsmartphone"></td>';
print '</tr>';
}
return $inc;
}
/**
* Output a task line into a pertime intput mode
*
* @param string $inc Line number (start to 0, then increased by recursive call)
* @param string $parent Id of parent project to show (0 to show all)
* @param Task[] $lines Array of lines
* @param int $level Level (start to 0, then increased/decrease by recursive call)
* @param string $projectsrole Array of roles user has on project
* @param string $tasksrole Array of roles user has on task
* @param string $mine Show only task lines I am assigned to
* @param int $restricteditformytask 0=No restriction, 1=Enable add time only if task is a task i am affected to
* @param int $preselectedday Preselected day
* @return $inc
*/
function projectLinesPerDay(&$inc, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask=1, $preselectedday='')
{
global $db, $user, $bc, $langs;
global $form, $formother, $projectstatic, $taskstatic;
$lastprojectid=0;
$var=true;
$numlines=count($lines);
for ($i = 0 ; $i < $numlines ; $i++)
{
if ($parent == 0) $level = 0;
if ($lines[$i]->fk_parent == $parent)
{
// Break on a new project
if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
{
$var = !$var;
$lastprojectid=$lines[$i]->fk_project;
if ($preselectedday)
{
$projectstatic->id = $lines[$i]->fk_project;
$projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTaks for all day of a week
}
}
// If we want all or we have a role on task, we show it
if (empty($mine) || ! empty($tasksrole[$lines[$i]->id]))
{
$projectstatic->id=$lines[$i]->fk_project;
$projectstatic->ref=$lines[$i]->projectref;
$projectstatic->title=$lines[$i]->projectlabel;
$projectstatic->public=$lines[$i]->public;
$taskstatic->id=$lines[$i]->id;
print "<tr ".$bc[$var].">\n";
// Project
print "<td>";
print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
print "</td>";
// Ref
print '<td>';
$taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id);
print $taskstatic->getNomUrl(1,'withproject');
print '</td>';
// Label task
print "<td>";
for ($k = 0 ; $k < $level ; $k++) print " ";
$taskstatic->id=$lines[$i]->id;
$taskstatic->ref=$lines[$i]->label;
$taskstatic->date_start=$lines[$i]->date_start;
$taskstatic->date_end=$lines[$i]->date_end;
print $taskstatic->getNomUrl(0,'withproject');
//print "<br>";
//for ($k = 0 ; $k < $level ; $k++) print " ";
//print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0);
print "</td>\n";
// Planned Workload
print '<td align="right">';
if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload,'allhourmin');
else print '--:--';
print '</td>';
// Progress declared %
print '<td align="right">';
print $formother->select_percent($lines[$i]->progress, $lines[$i]->id . 'progress');
print '</td>';
// Time spent by everybody
print '<td align="right">';
// $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user
if ($lines[$i]->duration)
{
print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.'">';
print convertSecondToTime($lines[$i]->duration,'allhourmin');
print '</a>';
}
else print '--:--';
print "</td>\n";
// Time spent by user
print '<td align="right">';
$tmptimespent=$taskstatic->getSummaryOfTimeSpent();
if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'],'allhourmin');
else print '--:--';
print "</td>\n";
$disabledproject=1;$disabledtask=1;
//print "x".$lines[$i]->fk_project;
//var_dump($lines[$i]);
//var_dump($projectsrole[$lines[$i]->fk_project]);
// If at least one role for project
if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
{
$disabledproject=0;
$disabledtask=0;
}
// If $restricteditformytask is on and I have no role on task, i disable edit
if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
{
$disabledtask=1;
}
// Form to add new time
print '<td class="nowrap" align="center">';
$tableCell=$form->select_date($preselectedday,$lines[$i]->id,1,1,2,"addtime",0,0,1,$disabledtask);
print $tableCell;
print '</td><td align="right">';
$dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$preselectedday][$lines[$i]->id];
$alreadyspent='';
if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin');
$tableCell='';
$tableCell.='<span class="timesheetalreadyrecorded"><input type="text" class="center" size="2" disabled id="timespent['.$inc.']['.$idw.']" name="task['.$lines[$i]->id.']['.$idw.']" value="'.$alreadyspent.'"></span>';
$tableCell.=' + ';
//$tableCell.=' ';
$tableCell.=$form->select_duration($lines[$i]->id.'duration','',$disabledtask,'text',0,1);
//$tableCell.=' <input type="submit" class="button"'.($disabledtask?' disabled':'').' value="'.$langs->trans("Add").'">';
print $tableCell;
print '</td>';
print '<td align="right">';
if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('',$langs->trans("YouAreNotContactOfProject"));
else if ($disabledtask) print $form->textwithpicto('',$langs->trans("TaskIsNotAffectedToYou"));
print '</td>';
print "</tr>\n";
}
$inc++;
$level++;
if ($lines[$i]->id) projectLinesPerDay($inc, $lines[$i]->id, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday);
$level--;
}
else
{
//$level--;
}
}
return $inc;
}
/**
* Output a task line into a perday intput mode
*
* @param string $inc Line number (start to 0, then increased by recursive call)
* @param int $firstdaytoshow First day to show
* @param User|null $fuser Restrict list to user if defined
* @param string $parent Id of parent project to show (0 to show all)
* @param Task[] $lines Array of lines
* @param int $level Level (start to 0, then increased/decrease by recursive call)
* @param string $projectsrole Array of roles user has on project
* @param string $tasksrole Array of roles user has on task
* @param string $mine Show only task lines I am assigned to
* @param int $restricteditformytask 0=No restriction, 1=Enable add time only if task is a task i am affected to
* @return $inc
*/
function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask=1)
{
global $db, $user, $bc, $langs;
global $form, $formother, $projectstatic, $taskstatic;
$lastprojectid=0;
$var=true;
$numlines=count($lines);
for ($i = 0 ; $i < $numlines ; $i++)
{
if ($parent == 0) $level = 0;
if ($lines[$i]->fk_parent == $parent)
{
// Break on a new project
if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
{
$var = !$var;
$lastprojectid=$lines[$i]->fk_project;
$projectstatic->id = $lines[$i]->fk_project;
$projectstatic->loadTimeSpent($firstdaytoshow, 0, $fuser->id); // Load time spent into this->weekWorkLoad and this->weekWorkLoadPerTaks for all day of a week
}
// If we want all or we have a role on task, we show it
if (empty($mine) || ! empty($tasksrole[$lines[$i]->id]))
{
print "<tr ".$bc[$var].">\n";
// Project
print '<td class="nowrap">';
$projectstatic->id=$lines[$i]->fk_project;
$projectstatic->ref=$lines[$i]->projectref;
$projectstatic->title=$lines[$i]->projectlabel;
$projectstatic->public=$lines[$i]->public;
print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
print "</td>";
// Ref
print '<td class="nowrap">';
$taskstatic->id=$lines[$i]->id;
$taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id);
print $taskstatic->getNomUrl(1, 'withproject', 'time');
print '</td>';
// Label task
print "<td>";
print '<!-- Task id = '.$lines[$i]->id.' -->';
for ($k = 0 ; $k < $level ; $k++) print " ";
$taskstatic->id=$lines[$i]->id;
$taskstatic->ref=$lines[$i]->label;
$taskstatic->date_start=$lines[$i]->date_start;
$taskstatic->date_end=$lines[$i]->date_end;
print $taskstatic->getNomUrl(0, 'withproject', 'time');
//print "<br>";
//for ($k = 0 ; $k < $level ; $k++) print " ";
//print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0);
print "</td>\n";
// Planned Workload
print '<td align="right">';
if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload,'allhourmin');
else print '--:--';
print '</td>';
// Progress declared %
print '<td align="right">';
print $formother->select_percent($lines[$i]->progress, $lines[$i]->id . 'progress');
print '</td>';
// Time spent by everybody
print '<td align="right">';
// $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user
if ($lines[$i]->duration)
{
print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.'">';
print convertSecondToTime($lines[$i]->duration,'allhourmin');
print '</a>';
}
else print '--:--';
print "</td>\n";
// Time spent by user
print '<td align="right">';
$tmptimespent=$taskstatic->getSummaryOfTimeSpent();
if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'],'allhourmin');
else print '--:--';
print "</td>\n";
$disabledproject=1;$disabledtask=1;
//print "x".$lines[$i]->fk_project;
//var_dump($lines[$i]);
//var_dump($projectsrole[$lines[$i]->fk_project]);
// If at least one role for project
if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
{
$disabledproject=0;
$disabledtask=0;
}
// If $restricteditformytask is on and I have no role on task, i disable edit
if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
{
$disabledtask=1;
}
//var_dump($projectstatic->weekWorkLoadPerTask);
// Fields to show current time
$tableCell=''; $modeinput='hours';
for ($idw = 0; $idw < 7; $idw++)
{
$tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd');
$tmparray=dol_getdate($tmpday);
$dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$tmpday][$lines[$i]->id];
$alreadyspent='';
if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin');
$alttitle=$langs->trans("AddHereTimeSpentForDay",$tmparray['day'],$tmparray['mon']);
$tableCell ='<td align="center" class="hide'.$idw.'">';
if ($alreadyspent)
{
$tableCell.='<span class="timesheetalreadyrecorded"><input type="text" class="center smallpadd" size="2" disabled id="timespent['.$inc.']['.$idw.']" name="task['.$lines[$i]->id.']['.$idw.']" value="'.$alreadyspent.'"></span>';
//$placeholder=' placeholder="00:00"';
$placeholder='';
//$tableCell.='+';
}
$tableCell.='<input type="text" alt="'.($disabledtask?'':$alttitle).'" title="'.($disabledtask?'':$alttitle).'" '.($disabledtask?'disabled':$placeholder).' class="center smallpadd" size="2" id="timeadded['.$inc.']['.$idw.']" name="task['.$lines[$i]->id.']['.$idw.']" value="" cols="2" maxlength="5"';
$tableCell.=' onkeypress="return regexEvent(this,event,\'timeChar\')"';
$tableCell.= 'onblur="regexEvent(this,event,\''.$modeinput.'\'); updateTotal('.$idw.',\''.$modeinput.'\')" />';
$tableCell.='</td>';
print $tableCell;
}
print '<td align="right">';
if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('',$langs->trans("YouAreNotContactOfProject"));
else if ($disabledtask) print $form->textwithpicto('',$langs->trans("TaskIsNotAffectedToYou"));
print '</td>';
print "</tr>\n";
}
$inc++;
$level++;
if ($lines[$i]->id) projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask);
$level--;
}
else
{
//$level--;
}
}
return $inc;
}
/**
* Search in task lines with a particular parent if there is a task for a particular user (in taskrole)
*
* @param string $inc Counter that count number of lines legitimate to show (for return)
* @param int $parent Id of parent task to start
* @param array $lines Array of all tasks
* @param string $taskrole Array of task filtered on a particular user
* @return int 1 if there is
*/
function searchTaskInChild(&$inc, $parent, &$lines, &$taskrole)
{
//print 'Search in line with parent id = '.$parent.'<br>';
$numlines=count($lines);
for ($i = 0 ; $i < $numlines ; $i++)
{
// Process line $lines[$i]
if ($lines[$i]->fk_parent == $parent && $lines[$i]->id != $lines[$i]->fk_parent)
{
// If task is legitimate to show, no more need to search deeper
if (isset($taskrole[$lines[$i]->id]))
{
//print 'Found a legitimate task id='.$lines[$i]->id.'<br>';
$inc++;
return $inc;
}
searchTaskInChild($inc, $lines[$i]->id, $lines, $taskrole);
//print 'Found inc='.$inc.'<br>';
if ($inc > 0) return $inc;
}
}
return $inc;
}
/**
* Return HTML table with list of projects and number of opened tasks
*
* @param DoliDB $db Database handler
* @param Form $form Object form
* @param int $socid Id thirdparty
* @param int $projectsListId Id of project I have permission on
* @param int $mytasks Limited to task I am contact to
* @param int $statut -1=No filter on statut, 0 or 1 = Filter on status
* @param array $listofoppstatus List of opportunity status
* @param array $hiddenfields List of info to not show ('projectlabel', 'declaredprogress', '...', )
* @return void
*/
function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks=0, $statut=-1, $listofoppstatus=array(),$hiddenfields=array())
{
global $langs,$conf,$user,$bc;
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$projectstatic=new Project($db);
$thirdpartystatic=new Societe($db);
$sortfield='';
$sortorder='';
$project_year_filter=0;
$title=$langs->trans("Projects");
if (strcmp($statut, '') && $statut >= 0) $title=$langs->trans("Projects").' '.$langs->trans($projectstatic->statuts_long[$statut]);
$arrayidtypeofcontact=array();
print '<table class="noborder" width="100%">';
$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
if ($mytasks)
{
$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
$sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
$sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
}
else
{
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet";
}
$sql.= " WHERE p.entity = ".$conf->entity;
$sql.= " AND p.rowid IN (".$projectsListId.")";
if ($socid) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
if ($mytasks)
{
$sql.= " AND p.rowid = t.fk_projet";
$sql.= " AND ec.element_id = t.rowid";
$sql.= " AND ec.fk_socpeople = ".$user->id;
$sql.= " AND ec.fk_c_type_contact = ctc.rowid"; // Replace the 2 lines with ec.fk_c_type_contact in $arrayidtypeofcontact
$sql.= " AND ctc.element = 'project_task'";
}
if ($statut >= 0)
{
$sql.= " AND p.fk_statut = ".$statut;
}
if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE))
{
$project_year_filter = GETPOST("project_year_filter");
//Check if empty or invalid year. Wildcard ignores the sql check
if ($project_year_filter != "*")
{
if (empty($project_year_filter) || !ctype_digit($project_year_filter))
{
$project_year_filter = date("Y");
}
$sql.= " AND (p.dateo IS NULL OR p.dateo <= ".$db->idate(dol_get_last_day($project_year_filter,12,false)).")";
$sql.= " AND (p.datee IS NULL OR p.datee >= ".$db->idate(dol_get_first_day($project_year_filter,1,false)).")";
}
}
// Get id of project we must show tasks
$arrayidofprojects=array();
$sql1 = "SELECT p.rowid as projectid";
$sql1.= $sql;
$resql = $db->query($sql1);
if ($resql)
{
$i=0;
$num = $db->num_rows($resql);
while ($i < $num)
{
$objp = $db->fetch_object($resql);
$arrayidofprojects[$objp->projectid]=$objp->projectid;
$i++;
}
}
else dol_print_error($db);
if (empty($arrayidofprojects)) $arrayidofprojects[0]=-1;
// Get list of project with calculation on tasks
$sql2 = "SELECT p.rowid as projectid, p.ref, p.title, p.fk_soc, s.nom as socname, p.fk_user_creat, p.public, p.fk_statut as status, p.fk_opp_status as opp_status, p.opp_amount,";
$sql2.= " COUNT(t.rowid) as nb, SUM(t.planned_workload) as planned_workload, SUM(t.planned_workload * t.progress / 100) as declared_progess_workload";
$sql2.= " FROM ".MAIN_DB_PREFIX."projet as p";
$sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
$sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet";
$sql2.= " WHERE p.rowid IN (".join(',',$arrayidofprojects).")";
$sql2.= " GROUP BY p.rowid, p.ref, p.title, p.fk_soc, s.nom, p.fk_user_creat, p.public, p.fk_statut, p.fk_opp_status, p.opp_amount";
$sql2.= " ORDER BY p.title, p.ref";
$var=true;
$resql = $db->query($sql2);
if ($resql)
{
$total_task = 0;
$total_opp_amount = 0;
$ponderated_opp_amount = 0;
$num = $db->num_rows($resql);
$i = 0;
print '<tr class="liste_titre">';
print_liste_field_titre($title.' <span class="badge">'.$num.'</span>',$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder);
print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder);
if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
{
print_liste_field_titre($langs->trans("OpportunityAmount"),"","","","",'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("OpportunityStatus"),"","","","",'align="right"',$sortfield,$sortorder);
}
if (empty($conf->global->PROJECT_HIDE_TASKS))
{
print_liste_field_titre($langs->trans("Tasks"),"","","","",'align="right"',$sortfield,$sortorder);
if (! in_array('plannedworkload', $hiddenfields)) print_liste_field_titre($langs->trans("PlannedWorkload"),"","","","",'align="right"',$sortfield,$sortorder);
if (! in_array('declaredprogress', $hiddenfields)) print_liste_field_titre($langs->trans("ProgressDeclared"),"","","","",'align="right"',$sortfield,$sortorder);
}
print_liste_field_titre($langs->trans("Status"),"","","","",'align="right"',$sortfield,$sortorder);
print "</tr>\n";
while ($i < $num)
{
$objp = $db->fetch_object($resql);
$projectstatic->id = $objp->projectid;
$projectstatic->user_author_id = $objp->fk_user_creat;
$projectstatic->public = $objp->public;
// Check is user has read permission on project
$userAccess = $projectstatic->restrictedProjectArea($user);
if ($userAccess >= 0)
{
$var=!$var;
print "<tr ".$bc[$var].">";
print '<td>';
$projectstatic->ref=$objp->ref;
print $projectstatic->getNomUrl(1);
if (! in_array('projectlabel', $hiddenfields)) print ' - '.dol_trunc($objp->title,24);
print '</td>';
print '<td>';
if ($objp->fk_soc > 0)
{
$thirdpartystatic->id=$objp->fk_soc;
$thirdpartystatic->ref=$objp->socname;
$thirdpartystatic->name=$objp->socname;
print $thirdpartystatic->getNomUrl(1);
}
print '</td>';
if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
{
print '<td align="right">';
if ($objp->opp_amount) print price($objp->opp_amount, 0, '', 1, -1, -1, $conf->currency);
print '</td>';
print '<td align="right">';
$code = dol_getIdFromCode($db, $objp->opp_status, 'c_lead_status', 'rowid', 'code');
if ($code) print $langs->trans("OppStatus".$code);
print '</td>';
}
$projectstatic->statut = $objp->status;
if (empty($conf->global->PROJECT_HIDE_TASKS))
{
print '<td align="right">'.$objp->nb.'</td>';
$plannedworkload=$objp->planned_workload;
$total_plannedworkload+=$plannedworkload;
if (! in_array('plannedworkload', $hiddenfields))
{
print '<td align="right">'.($plannedworkload?convertSecondToTime($plannedworkload):'').'</td>';
}
if (! in_array('declaredprogress', $hiddenfields))
{
$declaredprogressworkload=$objp->declared_progess_workload;
$total_declaredprogressworkload+=$declaredprogressworkload;
print '<td align="right">';
//print $objp->planned_workload.'-'.$objp->declared_progess_workload."<br>";
print ($plannedworkload?round(100*$declaredprogressworkload/$plannedworkload,0).'%':'');
print '</td>';
}
}
print '<td align="right">'.$projectstatic->getLibStatut(3).'</td>';
print "</tr>\n";
$total_task = $total_task + $objp->nb;
$total_opp_amount = $total_opp_amount + $objp->opp_amount;
$ponderated_opp_amount = $ponderated_opp_amount + price2num($listofoppstatus[$objp->opp_status] * $objp->opp_amount / 100);
}
$i++;
}
print '<tr class="liste_total">';
print '<td colspan="2">'.$langs->trans("Total")."</td>";
if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
{
print '<td class="liste_total" align="right">'.price($total_opp_amount, 0, '', 1, -1, -1, $conf->currency).'</td>';
print '<td class="liste_total" align="right">'.$form->textwithpicto(price($ponderated_opp_amount, 0, '', 1, -1, -1, $conf->currency), $langs->trans("OpportunityPonderatedAmountDesc"), 1).'</td>';
}
if (empty($conf->global->PROJECT_HIDE_TASKS))
{
print '<td class="liste_total" align="right">'.$total_task.'</td>';
if (! in_array('plannedworkload', $hiddenfields)) print '<td class="liste_total" align="right">'.($total_plannedworkload?convertSecondToTime($total_plannedworkload):'').'</td>';
if (! in_array('declaredprogress', $hiddenfields)) print '<td class="liste_total" align="right">'.($total_plannedworkload?round(100*$total_declaredprogressworkload/$total_plannedworkload,0).'%':'').'</td>';
}
print '<td class="liste_total"></td>';
print '</tr>';
$db->free($resql);
}
else
{
dol_print_error($db);
}
print "</table>";
if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE))
{
//Add the year filter input
print '<form method="get" action="'.$_SERVER["PHP_SELF"].'">';
print '<table width="100%">';
print '<tr>';
print '<td>'.$langs->trans("Year").'</td>';
print '<td style="text-align:right"><input type="text" size="4" class="flat" name="project_year_filter" value="'.$project_year_filter.'"/>';
print "</tr>\n";
print '</table></form>';
}
}
|
gpl-3.0
|
mars-sim/mars-sim
|
mars-sim-core/src/main/java/org/mars_sim/msp/core/structure/building/function/SolarPowerSource.java
|
4711
|
/**
* Mars Simulation Project
* SolarPowerSource.java
* @version 3.2.0 2021-06-20
* @author Scott Davis
*/
package org.mars_sim.msp.core.structure.building.function;
import java.io.Serializable;
import org.mars_sim.msp.core.environment.SurfaceFeatures;
import org.mars_sim.msp.core.structure.Settlement;
import org.mars_sim.msp.core.structure.building.Building;
/**
* A power source that gives a supply of power proportional
* to the level of sunlight it receives.
*/
public class SolarPowerSource
extends PowerSource
implements Serializable {
/** default serial id. */
private static final long serialVersionUID = 1L;
/** default logger. */
// private static final Logger logger = Logger.getLogger(SolarPowerSource.class.getName());
private static final double MAINTENANCE_FACTOR = 2.5D;
/** NASA MER has an observable solar cell degradation rate of 0.14% per sol,
Here we tentatively set to 0.04% per sol instead of 0.14%, since that in 10 earth years,
the efficiency will drop down to 23.21% of the initial 100%
100*(1-.04/100)^(365*10) = 23.21% */
public static double DEGRADATION_RATE_PER_SOL = .0004; // assuming it is a constant through its mission
/*
* The number of layers/panels that can be mechanically steered
* toward the sun to maximum the solar irradiance
*/
// public static double NUM_LAYERS = 1.5D;
// public static double STEERABLE_ARRAY_AREA = 50D; // in square feet
// public static double AUXILLARY_PANEL_AREA = 15D; // in square feet
// public static double PI = Math.PI;
// public static double HALF_PI = PI / 2D;
// private static final String SOLAR_PHOTOVOLTAIC_ARRAY = "Solar Photovoltaic Array";
// Notes :
// 1. The solar Panel is made of triple-junction solar cells with theoretical max eff of 68%
// 2. the flat-plate single junction has max theoretical efficiency at 29%
// 3. The modern Shockley and Queisser (SQ) Limit calculation is a maximum efficiency of 33.16% for any
// type of single junction solar cell.
// see http://www.solarcellcentral.com/limits_page.html
/*
* The theoretical max efficiency of the triple-junction solar cells
*/
private double efficiency_solar_panel = .55;
/**
* The dust deposition rates is proportional to the dust loading. Here we use MER program's extended the analysis
* to account for variations in the atmospheric columnar dust amount.
*/
// private double dust_deposition_rate = 0;
// As of Sol 4786 (July 11, 2017), the solar array energy production was 352 watt-hours with
// an atmospheric opacity (Tau) of 0.748 and a solar array dust factor of 0.549.
/**
* Constructor.
* @param maxPower the maximum generated power (kW).
*/
public SolarPowerSource(double maxPower) {
// Call PowerSource constructor.
super(PowerSourceType.SOLAR_POWER, maxPower);
}
// /**
// * Computes and updates the dust deposition rate for a settlement
// * @param the rate
// */
// public void computeDustDeposition(Settlement settlement) {
//
// if (location == null)
// location = settlement.getCoordinates();
//
// double tau = surface.getOpticalDepth(location);
//
// // e.g. The Material Adherence Experiement (MAE) on Pathfinder indicate steady dust accumulation on the Martian
// // surface at a rate of ~ 0.28% of the surface area per day (Landis and Jenkins, 1999)
// dust_deposition_rate = .0018 * tau /.5;
//
// if (dust_deposition_rate > 0.001)
// logger.info(building.getNickName() + " dust_deposition_rate: " + Math.round(dust_deposition_rate* 10000.0)/10000.0);
// // during relatively periods of clear sky, typical values for tau (optical depth) were between 0.2 and 0.5
// }
/**
* Gets the current power produced by the power source.
* @param building the building this power source is for.
* @return power (kW)
*/
@Override
public double getCurrentPower(Building building) {
double I = surface.getSolarIrradiance(building.getCoordinates());
if (I <= 0)
return 0;
return I / SurfaceFeatures.MEAN_SOLAR_IRRADIANCE * getMaxPower();
}
@Override
public double getAveragePower(Settlement settlement) {
return getMaxPower() * 0.707;
}
@Override
public double getMaintenanceTime() {
return getMaxPower() * MAINTENANCE_FACTOR;
}
public void setEfficiency(double value) {
efficiency_solar_panel = value;
}
public double getEfficiency() {
return efficiency_solar_panel;
}
@Override
public void removeFromSettlement() {
}
@Override
public void setTime(double time) {
}
@Override
public void destroy() {
super.destroy();
}
}
|
gpl-3.0
|
SalmonDE/TopVoter
|
src/SalmonDE/TopVoter/FloatingTextParticle.php
|
451
|
<?php
declare(strict_types = 1);
namespace SalmonDE\TopVoter;
use pocketmine\world\particle\FloatingTextParticle as FTP;
use pocketmine\math\Vector3;
class FloatingTextParticle extends FTP {
private $vector3;
public function __construct(Vector3 $vector3, string $text, string $title = ''){
parent::__construct($text, $title);
$this->vector3 = $vector3->asVector3();
}
public function getVector3(): Vector3{
return $this->vector3;
}
}
|
gpl-3.0
|
nathantypanski/rtop
|
src/procfs/processes.rs
|
959
|
use regex::Regex;
use std::io::fs;
use std::io::fs::PathExtensions;
/*
* Returns true if the path is to a process's addr in procfs.
*/
fn is_proc(dir: &Path) -> Option<Path> {
let mut result = None;
if (*dir).is_dir() {
let fname_str = dir.filename_str().expect("");
let re = match Regex::new(r"^[0-9]+$") {
Ok(re) => re,
Err(err) => panic!("{}", err),
};
result = match re.is_match(fname_str) {
true => Some(dir.clone()),
false => None,
};
}
result
}
pub fn read_processes(procfs: &Path) {
match fs::readdir(procfs) {
Ok(diri) => {
for dir in diri.iter() {
match is_proc(dir) {
Some(procdir) => {
println!("{}", procdir.filename_display());
}
None => {}
}
}
}
Err(_) => {}
}
}
|
gpl-3.0
|
osfans/trime
|
app/src/main/java/com/osfans/trime/setup/Config.java
|
34057
|
/*
* Copyright (C) 2015-present, osfans
* waxaca@163.com https://github.com/osfans
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.osfans.trime.setup;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.NinePatch;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.TypedValue;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.osfans.trime.Rime;
import com.osfans.trime.ime.core.Preferences;
import com.osfans.trime.ime.enums.SymbolKeyboardType;
import com.osfans.trime.ime.enums.WindowsPositionType;
import com.osfans.trime.ime.keyboard.Key;
import com.osfans.trime.ime.keyboard.Sound;
import com.osfans.trime.ime.symbol.TabManager;
import com.osfans.trime.util.AppVersionUtils;
import com.osfans.trime.util.DataUtils;
import com.osfans.trime.util.YamlUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import kotlin.jvm.Synchronized;
import timber.log.Timber;
/** 解析 YAML 配置文件 */
public class Config {
// 默认的用户数据路径
private static final String RIME = "rime";
// private static final String TAG = "Config";
private static Config self = null;
private static AssetManager assetManager = null;
private final String sharedDataDir = DataUtils.getSharedDataDir();
private final String userDataDir = DataUtils.getUserDataDir();
@Synchronized
public static Config get(Context context) {
if (self == null) self = new Config(context);
return self;
}
private Map<?, ?> mStyle, mDefaultStyle;
private String themeName, soundPackageName, currentSound;
private static final String defaultName = "trime";
private String schema_id, colorID;
private Map<?, ?> fallbackColors;
private Map<String, ?> presetColorSchemes, presetKeyboards;
private Map<String, ?> liquidKeyboard;
private static final Pattern pattern = Pattern.compile("\\s*\n\\s*");
private String[] clipBoardCompare, clipBoardOutput, draftOutput;
@NonNull
private Preferences getPrefs() {
return Preferences.Companion.defaultInstance();
}
public Config(@NonNull Context context) {
self = this;
assetManager = context.getAssets();
themeName = getPrefs().getLooks().getSelectedTheme();
soundPackageName = getPrefs().getKeyboard().getSoundPackage();
prepareRime(context);
deployTheme();
init();
setSoundFromColor();
clipBoardCompare = getPrefs().getOther().getClipboardCompareRules().trim().split("\n");
clipBoardOutput = getPrefs().getOther().getClipboardOutputRules().trim().split("\n");
draftOutput = getPrefs().getOther().getDraftOutputRules().trim().split("\n");
}
public String[] getClipBoardCompare() {
return clipBoardCompare;
}
public String[] getClipBoardOutput() {
return clipBoardOutput;
}
public String[] getDraftOutput() {
return draftOutput;
}
public int getClipboardLimit() {
return Integer.parseInt(getPrefs().getOther().getClipboardLimit());
}
public int getDraftLimit() {
return Integer.parseInt(getPrefs().getOther().getDraftLimit());
}
public void setClipBoardCompare(String str) {
String s = pattern.matcher(str).replaceAll("\n").trim();
clipBoardCompare = s.split("\n");
getPrefs().getOther().setClipboardCompareRules(s);
}
public void setClipBoardOutput(String str) {
String s = pattern.matcher(str).replaceAll("\n").trim();
clipBoardOutput = s.split("\n");
getPrefs().getOther().setClipboardOutputRules(s);
}
public void setDraftOutput(String str) {
String s = pattern.matcher(str).replaceAll("\n").trim();
draftOutput = s.split("\n");
getPrefs().getOther().setDraftOutputRules(s);
}
public String getTheme() {
return themeName;
}
public String getSoundPackage() {
return soundPackageName;
}
public void prepareRime(Context context) {
boolean isExist = new File(sharedDataDir).exists();
boolean isOverwrite = AppVersionUtils.INSTANCE.isDifferentVersion(getPrefs());
String defaultFile = "trime.yaml";
if (isOverwrite) {
copyFileOrDir("", true);
} else if (isExist) {
String path = new File("", defaultFile).getPath();
copyFileOrDir(path, false);
} else {
copyFileOrDir("", false);
}
while (!new File(sharedDataDir, defaultFile).exists()) {
SystemClock.sleep(3000);
copyFileOrDir("", isOverwrite);
}
// 缺失导致获取方案列表为空
final String defaultCustom = "default.custom.yaml";
if (!new File(sharedDataDir, defaultCustom).exists()) {
try {
new File(sharedDataDir, defaultCustom).createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Rime.get(context, !isExist); // 覆蓋時不強制部署
}
public static String[] getThemeKeys(boolean isUser) {
File d = new File(isUser ? DataUtils.getUserDataDir() : DataUtils.getSharedDataDir());
FilenameFilter trimeFilter = (dir, filename) -> filename.endsWith("trime.yaml");
String[] list = d.list(trimeFilter);
if (list != null) return list;
return new String[] {};
}
public static String[] getSoundPackages() {
File d = new File(DataUtils.getUserDataDir(), "sound");
FilenameFilter trimeFilter = (dir, filename) -> filename.endsWith(".sound.yaml");
String[] list = d.list(trimeFilter);
if (list != null) return list;
return new String[] {};
}
public static String[] getYamlFileNames(String[] keys) {
if (keys == null) return null;
final int n = keys.length;
final String[] names = new String[n];
for (int i = 0; i < keys.length; i++) {
final String k =
keys[i].replace(".trime.yaml", "").replace(".sound.yaml", "").replace(".yaml", "");
names[i] = k;
}
return names;
}
@SuppressWarnings("UnusedReturnValue")
public static boolean deployOpencc() {
final String dataDir = DataUtils.getAssetsDir("opencc");
final File d = new File(dataDir);
if (d.exists()) {
final FilenameFilter txtFilter = (dir, filename) -> filename.endsWith(".txt");
for (String txtName : Objects.requireNonNull(d.list(txtFilter))) {
txtName = new File(dataDir, txtName).getPath();
String ocdName = txtName.replace(".txt", ".ocd2");
Rime.opencc_convert_dictionary(txtName, ocdName, "text", "ocd2");
}
}
return true;
}
public boolean copyFileOrDir(String path, boolean overwrite) {
try {
final String assetPath = new File(RIME, path).getPath();
final String[] assets = assetManager.list(assetPath);
if (assets.length == 0) {
// Files
copyFile(path, overwrite);
} else {
// Dirs
final File dir = new File(sharedDataDir, path);
if (!dir.exists()) // noinspection ResultOfMethodCallIgnored
dir.mkdir();
for (String asset : assets) {
final String subPath = new File(path, asset).getPath();
copyFileOrDir(subPath, overwrite);
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void copyFile(String fileName, boolean overwrite) {
if (fileName == null) return;
final String targetFileName = new File(sharedDataDir, fileName).getPath();
if (new File(targetFileName).exists() && !overwrite) return;
final String sourceFileName = new File(RIME, fileName).getPath();
try (InputStream in = assetManager.open(sourceFileName);
final FileOutputStream out = new FileOutputStream(targetFileName)) {
final byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void deployTheme() {
if (userDataDir.contentEquals(sharedDataDir)) return; // 相同文件夾不部署主題
final String[] configs = getThemeKeys(false);
for (String config : configs) Rime.deploy_config_file(config, "config_version");
}
public void setTheme(String theme) {
themeName = theme;
getPrefs().getLooks().setSelectedTheme(themeName);
init();
}
// 设置音效包
public void setSoundPackage(String name) {
soundPackageName = name;
String path =
DataUtils.getUserDataDir()
+ File.separator
+ "sound"
+ File.separator
+ name
+ ".sound.yaml";
File file = new File(path);
if (file.exists()) {
applySoundPackage(file, name);
}
getPrefs().getKeyboard().setSoundPackage(soundPackageName);
}
// 应用音效包
private void applySoundPackage(File file, String name) {
// copy soundpackage yaml file from sound folder to build folder
try {
InputStream in = new FileInputStream(file);
OutputStream out =
new FileOutputStream(
DataUtils.getUserDataDir()
+ File.separator
+ "build"
+ File.separator
+ name
+ ".sound.yaml");
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
Timber.i("applySoundPackage = " + name);
} catch (Exception e) {
e.printStackTrace();
}
Sound.get(name);
currentSound = name;
}
// 配色指定音效时自动切换音效效果(不会自动修改设置)。
public void setSoundFromColor() {
final Map<String, ?> m = (Map<String, ?>) presetColorSchemes.get(colorID);
if (m.containsKey("sound")) {
String sound = (String) m.get("sound");
if (sound != currentSound) {
String path =
DataUtils.getUserDataDir()
+ File.separator
+ "sound"
+ File.separator
+ sound
+ ".sound.yaml";
File file = new File(path);
if (file.exists()) {
applySoundPackage(file, sound);
return;
}
}
}
if (currentSound != soundPackageName) {
setSoundPackage(soundPackageName);
}
}
private void init() {
Timber.d("init() themeName=%s schema_id=%s", themeName, schema_id);
try {
Rime.deploy_config_file(themeName + ".yaml", "config_version");
Map<String, ?> m = YamlUtils.INSTANCE.loadMap(themeName, "");
if (m == null) {
themeName = defaultName;
m = YamlUtils.INSTANCE.loadMap(themeName, "");
}
final Map<?, ?> mk = (Map<?, ?>) m.get("android_keys");
mDefaultStyle = (Map<?, ?>) m.get("style");
fallbackColors = (Map<?, ?>) m.get("fallback_colors");
Key.androidKeys = (List<String>) mk.get("name");
Key.setSymbolStart(Key.androidKeys.contains("A") ? Key.androidKeys.indexOf("A") : 284);
Key.setSymbols((String) mk.get("symbols"));
if (TextUtils.isEmpty(Key.getSymbols()))
Key.setSymbols("ABCDEFGHIJKLMNOPQRSTUVWXYZ!\"$%&:<>?^_{|}~");
Key.presetKeys = (Map<String, Map<String, ?>>) m.get("preset_keys");
presetColorSchemes = (Map<String, ?>) m.get("preset_color_schemes");
presetKeyboards = (Map<String, ?>) m.get("preset_keyboards");
liquidKeyboard = (Map<String, ?>) m.get("liquid_keyboard");
initLiquidKeyboard();
Rime.setShowSwitches(getPrefs().getKeyboard().getSwitchesEnabled());
Rime.setShowSwitchArrow(getPrefs().getKeyboard().getSwitchArrowEnabled());
reset();
initCurrentColors();
Timber.d("init() finins");
} catch (Exception e) {
e.printStackTrace();
setTheme(defaultName);
}
}
public void reset() {
schema_id = Rime.getSchemaId();
if (schema_id != null) mStyle = (Map<?, ?>) Rime.schema_get_value(schema_id, "style");
}
@Nullable
private Object _getValue(String k1, String k2) {
Map<?, ?> m;
if (mStyle != null && mStyle.containsKey(k1)) {
m = (Map<?, ?>) mStyle.get(k1);
if (m != null && m.containsKey(k2)) return m.get(k2);
}
if (mDefaultStyle != null && mDefaultStyle.containsKey(k1)) {
m = (Map<?, ?>) mDefaultStyle.get(k1);
if (m != null && m.containsKey(k2)) return m.get(k2);
}
return null;
}
private Object _getValue(String k1, String k2, Object defaultValue) {
Map<?, ?> m;
if (mStyle != null && mStyle.containsKey(k1)) {
m = (Map<?, ?>) mStyle.get(k1);
if (m != null && m.containsKey(k2)) return m.get(k2);
}
if (mDefaultStyle != null && mDefaultStyle.containsKey(k1)) {
m = (Map<?, ?>) mDefaultStyle.get(k1);
if (m != null && m.containsKey(k2)) return m.get(k2);
}
return defaultValue;
}
@Nullable
private Object _getValue(String k1) {
if (mStyle != null && mStyle.containsKey(k1)) return mStyle.get(k1);
if (mDefaultStyle != null && mDefaultStyle.containsKey(k1)) return mDefaultStyle.get(k1);
return null;
}
private Object _getValue(String k1, Object defaultValue) {
if (mStyle != null && mStyle.containsKey(k1)) return mStyle.get(k1);
if (mDefaultStyle != null && mDefaultStyle.containsKey(k1)) return mDefaultStyle.get(k1);
return defaultValue;
}
public Object getValue(@NonNull String s) {
final String[] ss = s.split("/");
if (ss.length == 1) return _getValue(ss[0]);
else if (ss.length == 2) return _getValue(ss[0], ss[1]);
return null;
}
public Object getValue(@NonNull String s, Object defaultValue) {
final String[] ss = s.split("/");
if (ss.length == 1) return _getValue(ss[0], defaultValue);
else if (ss.length == 2) return _getValue(ss[0], ss[1], defaultValue);
return null;
}
public boolean hasKey(String s) {
return getValue(s) != null;
}
private String getKeyboardName(@NonNull String name) {
if (name.contentEquals(".default")) {
if (presetKeyboards.containsKey(schema_id)) name = schema_id; // 匹配方案名
else {
if (schema_id.contains("_")) name = schema_id.split("_")[0];
if (!presetKeyboards.containsKey(name)) { // 匹配“_”前的方案名
Object o = Rime.schema_get_value(schema_id, "speller/alphabet");
name = "qwerty"; // 26
if (o != null) {
final String alphabet = o.toString();
if (presetKeyboards.containsKey(alphabet)) name = alphabet; // 匹配字母表
else {
if (alphabet.contains(",") || alphabet.contains(";")) name += "_";
if (alphabet.contains("0") || alphabet.contains("1")) name += "0";
}
}
}
}
}
if (!presetKeyboards.containsKey(name)) name = "default";
@Nullable final Map<?, ?> m = (Map<?, ?>) presetKeyboards.get(name);
assert m != null;
if (m.containsKey("import_preset")) {
name = Objects.requireNonNull(m.get("import_preset")).toString();
}
return name;
}
public List<String> getKeyboardNames() {
final List<?> names = (List<?>) getValue("keyboards");
final List<String> keyboards = new ArrayList<>();
for (Object s : names) {
s = getKeyboardName((String) s);
if (!keyboards.contains(s)) keyboards.add((String) s);
}
return keyboards;
}
public void initLiquidKeyboard() {
TabManager.clear();
if (liquidKeyboard == null) return;
final List<?> names = (List<?>) liquidKeyboard.get("keyboards");
if (names == null) return;
for (Object s : names) {
String name = (String) s;
if (liquidKeyboard.containsKey(name)) {
Map<?, ?> keyboard = (Map<?, ?>) liquidKeyboard.get(name);
if (keyboard != null) {
if (keyboard.containsKey("name")) {
name = (String) keyboard.get("name");
}
if (keyboard.containsKey("type")) {
TabManager.get()
.addTab(
name,
SymbolKeyboardType.Companion.fromObject(keyboard.get("type")),
keyboard.get("keys"));
}
}
}
}
}
public Map<String, ?> getKeyboard(String name) {
if (!presetKeyboards.containsKey(name)) name = "default";
return (Map<String, ?>) presetKeyboards.get(name);
}
public Map<String, ?> getLiquidKeyboard() {
return liquidKeyboard;
}
public void destroy() {
if (mDefaultStyle != null) mDefaultStyle.clear();
if (mStyle != null) mStyle.clear();
self = null;
}
private int[] keyboardPadding;
public int[] getKeyboardPadding() {
return keyboardPadding;
}
public int[] getKeyboardPadding(boolean land_mode) {
Timber.i("update KeyboardPadding: getKeyboardPadding(boolean land_mode) ");
return getKeyboardPadding(one_hand_mode, land_mode);
}
private int one_hand_mode;
public int[] getKeyboardPadding(int one_hand_mode, boolean land_mode) {
keyboardPadding = new int[3];
this.one_hand_mode = one_hand_mode;
if (land_mode) {
keyboardPadding[0] = getPixel("keyboard_padding_land");
keyboardPadding[1] = keyboardPadding[0];
keyboardPadding[2] = getPixel("keyboard_padding_land_bottom");
} else {
switch (one_hand_mode) {
case 0:
// 普通键盘 预留,目前未实装
keyboardPadding[0] = getPixel("keyboard_padding");
keyboardPadding[1] = keyboardPadding[0];
keyboardPadding[2] = getPixel("keyboard_padding_bottom");
break;
case 1:
// 左手键盘
keyboardPadding[0] = getPixel("keyboard_padding_left");
keyboardPadding[1] = getPixel("keyboard_padding_right");
keyboardPadding[2] = getPixel("keyboard_padding_bottom");
break;
case 2:
// 右手键盘
keyboardPadding[1] = getPixel("keyboard_padding_left");
keyboardPadding[0] = getPixel("keyboard_padding_right");
keyboardPadding[2] = getPixel("keyboard_padding_bottom");
break;
}
}
Timber.d(
"update KeyboardPadding: %s %s %s one_hand_mode=%s",
keyboardPadding[0], keyboardPadding[1], keyboardPadding[2], one_hand_mode);
return keyboardPadding;
}
private static int getPixel(Float f) {
if (f == null) return 0;
return (int)
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, f, Resources.getSystem().getDisplayMetrics());
}
public int getPixel(String key) {
return getPixel(getFloat(key));
}
public int getPixel(String key, int defaultValue) {
float v = getFloat(key, Float.MAX_VALUE);
if (v == Float.MAX_VALUE) return defaultValue;
return getPixel(v);
}
public static Integer getPixel(Map<?, ?> m, String k, Object s) {
Object o = getValue(m, k, s);
if (o == null) return null;
return getPixel(Float.valueOf(o.toString()));
}
public static Integer getPixel(Map<?, ?> m, String k) {
return getPixel(m, k, null);
}
public static Integer getColor(Context context, @NonNull Map<?, ?> m, String k) {
Integer color = null;
if (m.containsKey(k)) {
Object o = m.get(k);
assert o != null;
String s = o.toString();
color = parseColor(s);
if (color == null) color = get(context).getCurrentColor(s);
}
return color;
}
public Integer getColor(String key) {
Object o = getColorObject(key);
if (o == null) {
o = ((Map<?, ?>) Objects.requireNonNull(presetColorSchemes.get(colorID))).get(key);
}
if (o == null) return null;
return parseColor(o.toString());
}
// API 2.0
public Drawable getDrawable(@NonNull Map<?, ?> m, String k) {
if (m.containsKey(k)) {
final Object o = m.get(k);
// Timber.d("getColorDrawable()" + k + " " + o);
return drawableObject(o);
}
return null;
}
public static Object getValue(@NonNull Map<?, ?> m, String k, Object o) {
return m.containsKey(k) ? m.get(k) : o;
}
@NonNull
public static String getString(Map<?, ?> m, String k, Object s) {
final Object o = getValue(m, k, s);
if (o == null) return "";
return o.toString();
}
@NonNull
public static String getString(Map<?, ?> m, String k) {
return getString(m, k, "");
}
public boolean getBoolean(String key) {
final Object o = getValue(key);
if (o == null) return true;
return Boolean.parseBoolean(o.toString());
}
public double getDouble(String key) {
final Object o = getValue(key);
if (o == null) return 0d;
return Double.parseDouble(o.toString());
}
public float getFloat(String key) {
final Object o = getValue(key);
if (o == null) return 0f;
return Float.parseFloat(o.toString());
}
public float getFloat(String key, float defaultValue) {
final Object o = getValue(key, defaultValue);
if (o == null) return defaultValue;
return Float.parseFloat(o.toString());
}
public int getInt(String key) {
final Object o = getValue(key);
if (o == null) return 0;
return Long.decode(o.toString()).intValue();
}
public String getString(String key) {
final Object o = getValue(key);
if (o == null) return "";
return o.toString();
}
// 获取当前配色方案的key的value,或者从fallback获取值。
@Nullable
private Object getColorObject(String key) {
final Map<?, ?> map = (Map<?, ?>) presetColorSchemes.get(colorID);
if (map == null) return null;
getPrefs().getLooks().setSelectedColor(colorID);
Object o = map.get(key);
String fallbackKey = key;
while (o == null && fallbackColors.containsKey(fallbackKey)) {
fallbackKey = (String) fallbackColors.get(fallbackKey);
o = map.get(fallbackKey);
}
return o;
}
/**
* 获取配色方案名<br>
* 优先级:设置>color_scheme>default <br>
* 避免直接读取 default
*
* @return java.lang.String 首个已配置的主题方案名
*/
private String getColorSchemeName() {
String scheme = getPrefs().getLooks().getSelectedColor();
if (!presetColorSchemes.containsKey(scheme)) scheme = getString("color_scheme"); // 主題中指定的配色
if (!presetColorSchemes.containsKey(scheme)) scheme = "default"; // 主題中的default配色
return scheme;
}
private static Integer parseColor(String s) {
Integer color = null;
if (s.contains(".")) return color; // picture name
try {
s = s.toLowerCase(Locale.getDefault());
if (s.startsWith("0x")) {
if (s.length() == 3 || s.length() == 4)
s = String.format("#%02x000000", Long.decode(s.substring(2))); // 0xAA
else if (s.length() < 8) s = String.format("#%06x", Long.decode(s.substring(2)));
else if (s.length() == 9) s = "#0" + s.substring(2);
}
color = Color.parseColor(s.replace("0x", "#"));
} catch (Exception e) {
// Log.e(TAG, "unknown color " + s);
}
return color;
}
public Integer getCurrentColor(String key) {
Object o = getColorObject(key);
if (o == null) return null;
return parseColor(o.toString());
}
public String[] getColorKeys() {
if (presetColorSchemes == null) return null;
final Object[] keys = new String[presetColorSchemes.size()];
presetColorSchemes.keySet().toArray(keys);
return (String[]) keys;
}
@Nullable
public String[] getColorNames(String[] keys) {
if (keys == null) return null;
final int n = keys.length;
final String[] names = new String[n];
for (int i = 0; i < n; i++) {
final Map<?, ?> m = (Map<?, ?>) presetColorSchemes.get(keys[i]);
assert m != null;
names[i] = Objects.requireNonNull(m.get("name")).toString();
}
return names;
}
public Typeface getFont(String key) {
final String name = getString(key);
if (name != null) {
final File f = new File(DataUtils.getAssetsDir("fonts"), name);
if (f.exists()) return Typeface.createFromFile(f);
}
return Typeface.DEFAULT;
}
// 返回drawable。参数可以是颜色或者图片。如果参数缺失,返回null
private Drawable drawableObject(Object o) {
if (o == null) return null;
String name = o.toString();
Integer color = parseColor(name);
if (color == null) {
if (curcentColors.containsKey(name)) {
o = curcentColors.get(name);
if (o instanceof Integer) color = (Integer) o;
}
}
if (color != null) {
final GradientDrawable gd = new GradientDrawable();
gd.setColor(color);
return gd;
}
return drawableBitmapObject(name);
}
// 返回图片的drawable。如果参数缺失、非图片,返回null
private Drawable drawableBitmapObject(Object o) {
if (o == null) return null;
if (o instanceof String) {
String name = (String) o;
String nameDirectory =
DataUtils.getAssetsDir("backgrounds" + File.separator + backgroundFolder);
File f = new File(nameDirectory, name);
if (!f.exists()) {
nameDirectory = DataUtils.getAssetsDir("backgrounds");
f = new File(nameDirectory, name);
}
if (!f.exists()) {
if (curcentColors.containsKey(name)) {
o = curcentColors.get(name);
if (o instanceof String) f = new File((String) o);
}
}
if (f.exists()) {
name = f.getPath();
if (name.contains(".9.png")) {
final Bitmap bitmap = BitmapFactory.decodeFile(name);
final byte[] chunk = bitmap.getNinePatchChunk();
// 如果 .9.png 没有经过第一步,那么 chunk 就是 null, 只能按照普通方式加载
if (NinePatch.isNinePatchChunk(chunk))
return new NinePatchDrawable(bitmap, chunk, new Rect(), null);
}
return Drawable.createFromPath(name);
}
}
return null;
}
public Drawable getColorDrawable(String key) {
final Object o = getColorObject(key);
return drawableObject(o);
}
public WindowsPositionType getWinPos() {
return WindowsPositionType.Companion.fromString(getString("layout/position"));
}
public int getLongTimeout() {
int progress = getPrefs().getKeyboard().getLongPressTimeout();
if (progress > 60) progress = 60;
return progress * 10 + 100;
}
public int getRepeatInterval() {
int progress = getPrefs().getKeyboard().getRepeatInterval();
if (progress > 9) progress = 9;
return progress * 10 + 10;
}
public int getLiquidPixel(String key) {
if (liquidKeyboard != null) {
if (liquidKeyboard.containsKey(key)) {
return YamlUtils.INSTANCE.getPixel(liquidKeyboard, key, 0);
}
}
return getPixel(key);
}
public Integer getLiquidColor(String key) {
if (liquidKeyboard != null) {
if (liquidKeyboard.containsKey(key)) {
Integer value = parseColor((String) Objects.requireNonNull(liquidKeyboard.get(key)));
if (value != null) return value;
}
}
return getColor(key);
}
// 获取当前色彩 Config 2.0
public Integer getCurrentColor_(String key) {
Object o = curcentColors.get(key);
return (Integer) o;
}
// 获取当前背景图路径 Config 2.0
public String getCurrentImage(String key) {
Object o = curcentColors.get(key);
if (o instanceof String) return (String) o;
return "";
}
// 返回drawable。 Config 2.0
// 参数可以是颜色或者图片。如果参数缺失,返回null
public Drawable getDrawable_(String key) {
if (key == null) return null;
Object o = curcentColors.get(key);
if (o instanceof Integer) {
Integer color = (Integer) o;
final GradientDrawable gd = new GradientDrawable();
gd.setColor(color);
return gd;
} else if (o instanceof String) return getDrawableBitmap_(key);
return null;
}
// 返回图片或背景的drawable,支持null参数。 Config 2.0
public Drawable getDrawable(
String key, String borderKey, String borderColorKey, String roundCornerKey, String alphaKey) {
if (key == null) return null;
Drawable drawable = getDrawableBitmap_(key);
if (drawable != null) {
if (alphaKey != null) {
if (hasKey(alphaKey)) {
int alpha = getInt("layout/alpha");
if (alpha <= 0) alpha = 0;
else if (alpha >= 255) alpha = 255;
drawable.setAlpha(alpha);
}
}
return drawable;
}
GradientDrawable gd = new GradientDrawable();
Object o = curcentColors.get(key);
if (!(o instanceof Integer)) return null;
gd.setColor((int) o);
if (roundCornerKey != null) gd.setCornerRadius(getFloat(roundCornerKey));
if (borderColorKey != null && borderKey != null) {
int border = getPixel(borderKey);
Object borderColor = curcentColors.get(borderColorKey);
if (borderColor instanceof Integer && border > 0) {
gd.setStroke(border, getCurrentColor_(borderColorKey));
}
}
if (alphaKey != null) {
if (hasKey(alphaKey)) {
int alpha = getInt("layout/alpha");
if (alpha <= 0) alpha = 0;
else if (alpha >= 255) alpha = 255;
gd.setAlpha(alpha);
}
}
return gd;
}
// 返回图片的drawable。 Config 2.0
// 如果参数缺失、非图片,返回null. 在genCurrentColors()中已经验证存在文件,因此不需要重新验证。
public Drawable getDrawableBitmap_(String key) {
if (key == null) return null;
Object o = curcentColors.get(key);
if (o instanceof String) {
String path = (String) o;
if (path.contains(".9.png")) {
final Bitmap bitmap = BitmapFactory.decodeFile(path);
final byte[] chunk = bitmap.getNinePatchChunk();
if (NinePatch.isNinePatchChunk(chunk))
return new NinePatchDrawable(bitmap, chunk, new Rect(), null);
}
return Drawable.createFromPath(path);
}
return null;
}
// 遍历当前配色方案的值、fallback的值,从而获得当前方案的全部配色Map
private final Map<String, Object> curcentColors = new HashMap<>();
private String backgroundFolder;
// 初始化当前配色 Config 2.0
public void initCurrentColors() {
curcentColors.clear();
colorID = getColorSchemeName();
backgroundFolder = getString("background_folder");
Timber.d(
"initCurrentColors() colorID=%s themeName=%s schema_id=%s", colorID, themeName, schema_id);
final Map<?, ?> map = (Map<?, ?>) presetColorSchemes.get(colorID);
if (map == null) {
Timber.i("no colorID %s", colorID);
return;
}
getPrefs().getLooks().setSelectedColor(colorID);
for (Map.Entry<?, ?> entry : map.entrySet()) {
Object value = getColorRealValue(entry.getValue());
if (value != null) curcentColors.put(entry.getKey().toString(), value);
}
for (Map.Entry<?, ?> entry : fallbackColors.entrySet()) {
String key = entry.getKey().toString();
if (!curcentColors.containsKey(key)) {
Object o = map.get(key);
String fallbackKey = key;
while (o == null && fallbackColors.containsKey(fallbackKey)) {
fallbackKey = (String) fallbackColors.get(fallbackKey);
o = map.get(fallbackKey);
}
if (o != null) {
Object value = getColorRealValue(o);
if (value != null) {
curcentColors.put(key, value);
curcentColors.put(fallbackKey, value);
}
}
}
}
}
// 获取参数的真实value,Config 2.0
// 如果是色彩返回int,如果是背景图返回path string,如果处理失败返回null
private Object getColorRealValue(Object object) {
if (object == null) return null;
if (object instanceof Integer) {
return object;
}
String s = object.toString();
if (!s.matches(".*[.\\\\/].*")) {
try {
s = s.toLowerCase(Locale.getDefault());
if (s.startsWith("0x")) {
if (s.length() == 3 || s.length() == 4)
s = String.format("#%02x000000", Long.decode(s.substring(2))); // 0xAA
else if (s.length() < 8) s = String.format("#%06x", Long.decode(s.substring(2)));
else if (s.length() == 9) s = "#0" + s.substring(2);
}
if (s.matches("(0x|#)?[a-f0-9]+")) return Color.parseColor(s.replace("0x", "#"));
} catch (Exception e) {
Timber.e("getColorRealValue() unknown color, %s ; object %s", s, object);
e.printStackTrace();
}
}
String nameDirectory =
DataUtils.getAssetsDir("backgrounds" + File.separator + backgroundFolder);
File f = new File(nameDirectory, s);
if (!f.exists()) {
nameDirectory = DataUtils.getAssetsDir("backgrounds");
f = new File(nameDirectory, s);
}
if (f.exists()) return f.getPath();
return null;
}
}
|
gpl-3.0
|
byte-foundry/prototypo.js
|
src/Utils.js
|
20655
|
var plumin = require('plumin.js'),
DepTree = require('deptree'),
cloneDeep = require('lodash.clonedeep'),
filter = require('lodash.filter'),
assign = require('lodash.assign'),
updateUtils = require('./updateUtils.js');
var paper = plumin.paper,
Utils = updateUtils,
_ = {
cloneDeep: cloneDeep,
assign: assign
};
// convert the glyph source from the ufo object model to the paper object model
// this is the inverse operation done by jsufonify
Utils.ufoToPaper = function( src ) {
if ( src.parameter ) {
src.parameters = src.parameter;
delete src.parameter;
}
if ( src.anchor ) {
src.anchors = src.anchor;
delete src.anchor;
}
if ( src.outline && src.outline.contour ) {
src.contours = src.outline.contour;
delete src.outline.contour;
}
if ( src.contours ) {
src.contours.forEach(function(contour) {
if ( contour.point ) {
contour.nodes = contour.point;
delete contour.point;
}
});
}
if ( src.outline && src.outline.component ) {
src.components = src.outline.component;
src.components.forEach(function(component) {
if ( component.anchor ) {
component.parentAnchors = component.anchor;
delete component.anchor;
}
if ( component.parameter ) {
component.parentParameters = component.parameter;
delete component.parameter;
}
});
delete src.outline.component;
}
delete src.outline;
if ( src.lib && src.lib.transforms ) {
src.transforms = src.lib.transforms;
delete src.lib.transforms;
}
if ( src.lib && src.lib.transformOrigin ) {
src.transformOrigin = src.lib.transformOrigin;
delete src.lib.transformOrigin;
}
if ( src.lib && src.lib.parameters ) {
src.parameters = src.lib.parameters;
delete src.lib.parameters;
}
if ( src.lib && src.lib.solvingOrder ) {
src.solvingOrder = src.lib.solvingOrder;
delete src.lib.solvingOrder;
}
return src;
};
Utils.fontFromSrc = function( src ) {
// TODO: this, block is only here for backward compat
// and should be removed at some point in the future
if ( !src.fontinfo ) {
src.fontinfo = src.info;
}
var font = new paper.Font( _.assign({}, src.fontinfo, {
// The font needs to be initialized with valid ascender/descender values
ascender: 1,
descender: -1
}) );
font.src = Utils.ufoToPaper( src );
var filteredSrc = _.assign( {}, src );
delete filteredSrc.controls;
delete filteredSrc.presets;
delete filteredSrc.glyphs;
Utils.createUpdaters( filteredSrc, 'font_' + src.fontinfo.familyName );
font.parameters = {};
Utils.mergeStatic( font.parameters, font.src.parameters );
// solvingOrder might be already available (if this is a subcomponent,
// or precomputed in a worker)
font.solvingOrder = font.src.solvingOrder;
if ( !font.solvingOrder ) {
font.solvingOrder = filteredSrc.solvingOrder =
Utils.solveDependencyTree( font, filteredSrc );
}
return font;
};
// create Glyph instance and all its child items: anchors, contours
// and components
// var wmm = typeof WeakMap === 'function' && new WeakMap();
Utils.glyphFromSrc = function( src, fontSrc, naive, embed ) {
var glyph = new paper.Glyph({
name: src.name,
unicode: src.unicode
});
// Clone glyph src to allow altering it without impacting components srcs.
glyph.src = _.cloneDeep( src );
// turn ._operation strings to ._updaters functions
// TODO: restore sourceURL pragma for debugging.
// this should impact the way results are memoized
Utils.createUpdaters( glyph.src/*, 'glyphs/glyph_' + name*/ );
Utils.mergeStatic( glyph, glyph.src );
// this will be used to hold local parameters that will be merged with
// the font parameters
glyph.parameters = {};
Utils.mergeStatic( glyph.parameters, glyph.src.parameters );
// solvingOrder might be already available (if this is a subcomponent,
// or precomputed in a worker)
glyph.solvingOrder = glyph.src.solvingOrder;
(glyph.src.anchors || []).forEach(function(anchorSrc) {
var anchor = new paper.Node();
anchor.src = anchorSrc;
Utils.mergeStatic( anchor, anchorSrc );
glyph.addAnchor( anchor );
});
(glyph.src.contours || []).forEach(function(contourSrc, contourIdx) {
var contour = new paper.Path();
contour.src = contourSrc;
Utils.mergeStatic( contour, contourSrc );
glyph.addContour( contour );
// TODO: handle oncurve/offcurve points
contourSrc.nodes.forEach(function(nodeSrc, nodeIdx) {
var node = new paper.Node();
node.src = nodeSrc;
Utils.mergeStatic( node, nodeSrc );
node.contourIdx = contourIdx;
node.nodeIdx = nodeIdx;
contour.add( node );
});
});
if ( !glyph.src.components ) {
return glyph;
}
glyph.componentLists = {};
// components can only be embedded once all glyphs have been generated
// from source
glyph.embedComponents = function() {
glyph.src.components.forEach(function(componentSrc) {
if (Array.isArray(componentSrc.base)) {
glyph.componentLists[componentSrc.id] = componentSrc.base;
Utils.selectGlyphComponent(
glyph,
componentSrc,
componentSrc.base[0],
fontSrc,
naive,
componentSrc.id);
} else {
Utils.selectGlyphComponent(
glyph,
componentSrc,
componentSrc.base,
fontSrc,
naive);
}
});
delete glyph.embedComponents;
};
if ( embed ) {
glyph.embedComponents();
}
return glyph;
};
Utils.selectGlyphComponent = function(
glyph,
componentSrc,
componentName,
fontSrc,
naive,
id,
index) {
var component = Utils.glyphFromSrc(
fontSrc.glyphs[componentName],
fontSrc,
naive,
// components' subcomponents can be embedded immediatly
true
);
component.parentParameters = {};
Utils.mergeStatic(
component.parentParameters,
componentSrc.parentParameters
);
naive.annotator( component );
component.componentId = id;
component.chosen = componentName;
component.multiple = Array.isArray(componentSrc.base);
if (index === undefined) {
glyph.addComponent( component);
} else {
if (glyph.components[index].optionPoint) {
glyph.components[index].optionPoint.remove();
}
glyph.components[index].replaceWith(component);
}
(componentSrc.parentAnchors || []).forEach(function(anchorSrc) {
var anchor = new paper.Node();
anchor.src = anchorSrc;
Utils.mergeStatic( anchor, anchorSrc );
component.addParentAnchor( anchor );
});
}
// build a full cursor from arguments
// adds 'contours' and 'nodes' automagically when arguments start with a number
Utils.cursor = function() {
var cursor = [];
for ( var i = -1; ++i < arguments.length; ) {
if ( i === 0 && typeof arguments[0] === 'number' ) {
cursor.push( 'contours' );
}
if ( i === 1 && typeof arguments[0] === 'number' ) {
cursor.push( 'nodes' );
}
cursor.push( arguments[i] );
}
return cursor.join('.');
};
Utils.propFromCursor = function( cursor, context, length ) {
if ( length === undefined ) {
length = cursor.length;
}
for ( var i = -1; ++i < length; ) {
if (context === undefined) {
return undefined;
}
context = context[ cursor[i] ];
}
return context;
};
Utils.mergeStatic = function( obj, src ) {
for ( var i in src ) {
if ( typeof src[i] !== 'object' ) {
obj[i] = src[i];
// props that have empty dependencies and params are static
} else if (
src[i]._dependencies && src[i]._dependencies.length === 0 &&
( !src[i]._parameters || src[i]._parameters.length === 0 ) &&
src[i]._updaters
) {
obj[i] = src[i]._updaters[0].apply(
obj,
[ null, null, null, null, Utils ]
);
delete src[i];
}
}
};
Utils.createUpdaters = function( leaf, path ) {
if ( leaf.constructor === Object && leaf._operation ) {
leaf._updaters = [ Utils.createUpdater( leaf, path ) ];
} else if ( leaf.constructor === Object ) {
for ( var i in leaf ) {
Utils.createUpdaters( leaf[i], path + '.' + i );
}
} else if ( leaf.constructor === Array ) {
leaf.forEach(function(child, j) {
Utils.createUpdaters( child, path + '.' + j );
});
}
};
Utils.updaterCache = {};
Utils.createUpdater = function( leaf/*, path*/ ) {
var sOperation = leaf._operation.toString(),
cacheKey = ( leaf.parameters || [] ).join() + '#' + sOperation;
if ( cacheKey in Utils.updaterCache ) {
return Utils.updaterCache[ cacheKey ];
}
Utils.updaterCache[ cacheKey ] = Function.apply( null, [
'propName', 'contours', 'anchors', 'parentAnchors', 'Utils'
]
.concat( leaf._parameters || [] )
.concat(
( typeof leaf._operation === 'string' &&
leaf._operation.indexOf('return ') === -1 ?
'return ' : ''
) +
// The operation might be wrapped in a function (e.g. multi-
// line code for debugging purpose). In this case, return
// must be explicit
sOperation
// [\s\S] need to be used instead of . because
// javascript doesn't have a dotall flag (s)
.replace(/^function\s*\(\)\s*\{([\s\S]*?)\}$/, '$1')
.trim()/* +
// add sourceURL pragma to help debugging
// TODO: restore sourceURL pragma if it proves necessary
'\n\n//# sourceURL=' + path*/
) );
return Utils.updaterCache[ cacheKey ];
};
Utils.solveDependencyTree = function( leaf, src ) {
var depTree = Utils.dependencyTree( src || leaf.src, null ),
order = depTree.resolve().map(function( cursor ) {
return { cursor: cursor.split('.') };
}),
simplified = Utils.simplifyResolutionOrder( leaf, order );
return simplified;
};
Utils.dependencyTree = function( parentSrc, cursor, depTree ) {
if ( !depTree ) {
depTree = new DepTree();
}
Object.keys( parentSrc ).forEach(function( i ) {
// don't inspect local parameters, private properties and non-object
if ( i === 'parameters' || i.indexOf('_') === 0 ||
typeof parentSrc[i] !== 'object' ) {
return;
}
var leafSrc = parentSrc[i],
currCursor = cursor ? cursor + '.' + i : i;
if ( ( leafSrc._updaters && leafSrc._updaters.length ) ||
( leafSrc._dependencies && leafSrc._dependencies.length ) ) {
depTree.add( currCursor,
leafSrc._dependencies.filter(function(dep) {
// parentAnchors are always here when you need them
return !/^parentAnchors/.test(dep);
})
);
}
if ( !leafSrc._operation ) {
Utils.dependencyTree( leafSrc, currCursor, depTree );
}
});
return depTree;
};
// Simplify resolution order by removing cursors that don't point to objects
// with updater functions
Utils.simplifyResolutionOrder = function( leaf, depTree ) {
return depTree.filter(function( cursor ) {
var src = Utils.propFromCursor( cursor.cursor, leaf.src );
return src && src._updaters;
});
};
var rdeg = /deg$/;
Utils.transformsToMatrix = function( transforms, origin ) {
var prev = new Float32Array(6),
curr = new Float32Array(6),
rslt = new Float32Array([ 1, 0, 0, 1, 0, 0 ]);
if ( origin && Array.isArray( origin ) ) {
transforms.unshift([ 'translate', origin[0], origin[1] ]);
transforms.push([ 'translate', -origin[0], -origin[1] ]);
} else if ( origin ) {
transforms.unshift([ 'translate', origin.x, origin.y ]);
transforms.push([ 'translate', -origin.x, -origin.y ]);
}
transforms.forEach(function( transform ) {
curr[0] = curr[3] = 1;
curr[1] = curr[2] = curr[4] = curr[5] = 0;
// convert degrees to radian
for ( var i = 1; i < transform.length; i++ ) {
if ( transform[i] && typeof transform[i] === 'string' &&
rdeg.test(transform[i]) ) {
transform[i] = parseFloat(transform[i]) * ( Math.PI * 2 / 360 );
}
}
switch ( transform[0] ) {
case 'translateX':
curr[4] = transform[1];
break;
case 'translateY':
curr[5] = transform[1];
break;
case 'translate':
curr[4] = transform[1];
curr[5] = transform[2] || 0;
break;
case 'rotate':
curr[0] = Math.cos( transform[1] );
curr[1] = Math.sin( transform[1] );
curr[2] = -curr[1];
curr[3] = curr[0];
break;
case 'scaleX':
curr[0] = transform[1];
break;
case 'scaleY':
curr[3] = transform[1];
break;
case 'scale':
curr[0] = transform[1];
curr[3] = transform.length > 2 ? transform[2] : transform[1];
break;
case 'skewX':
// stop parsing transform when encountering skewX(90)
// see http://stackoverflow.com/questions/21094958/how-to-deal-with-infinity-in-a-2d-matrix
transform[1] = transform[1] % ( 2 * Math.PI );
if ( transform[1] === Math.PI / 2 ||
transform[1] === -Math.PI / 2 ) {
return rslt;
}
curr[2] = Math.tan( transform[1] );
break;
case 'skewY':
transform[1] = transform[1] % ( 2 * Math.PI );
if ( transform[1] === Math.PI / 2 ||
transform[1] === -Math.PI / 2 ) {
return rslt;
}
curr[1] = Math.tan( transform[1] );
break;
case 'matrix':
curr[0] = transform[1];
curr[1] = transform[2];
curr[2] = transform[3];
curr[3] = transform[4];
curr[4] = transform[5];
curr[5] = transform[6];
break;
}
prev[0] = rslt[0];
prev[1] = rslt[1];
prev[2] = rslt[2];
prev[3] = rslt[3];
prev[4] = rslt[4];
prev[5] = rslt[5];
rslt[0] = prev[0] * curr[0] + prev[2] * curr[1];
rslt[1] = prev[1] * curr[0] + prev[3] * curr[1];
rslt[2] = ( prev[0] * curr[2] || 0 ) + prev[2] * curr[3];
rslt[3] = ( prev[1] * curr[2] || 0 ) + prev[3] * curr[3];
rslt[4] = prev[0] * curr[4] + prev[2] * curr[5] + prev[4];
rslt[5] = prev[1] * curr[4] + prev[3] * curr[5] + prev[5];
});
return new paper.Matrix(
rslt[0],
rslt[1],
rslt[2],
rslt[3],
rslt[4],
rslt[5]
);
};
Utils.updateParameters = function( leaf, params ) {
var paramsToUpdate = (leaf.src && leaf.src.parameters) || [];
if (leaf.parent && leaf.parent.src) {
paramsToUpdate = _.assign([], leaf.parent.src.parameters, paramsToUpdate);
}
Object.keys( ( leaf.src && paramsToUpdate ) || [] )
.forEach(function( name ) {
var src = paramsToUpdate[name];
params[name] = src._updaters ?
src._updaters[0].apply( null, [
name, [], [], leaf.parentAnchors, Utils
].concat(
( src._parameters || [] ).map(function(_name) {
return params[_name];
})
)) :
src;
});
};
Utils.updateIndividualParameters = function( leaf, params ) {
Object.keys( ( leaf.src && leaf.src.parameters ) || [] )
.forEach(function( name ) {
var src = leaf.src.parameters[name];
if ( params['indiv_group_param'] ) {
Object.keys(params['indiv_group_param'])
.forEach(function( groupName ) {
var needed = false;
var group = params['indiv_group_param'][groupName];
function handleGroup(_name) {
return group[_name + '_rel'] ?
( group[_name + '_rel'].state === 'relative' ?
group[_name + '_rel'].value * params[_name] :
group[_name + '_rel'].value + params[_name]
) : params[_name];
}
if ( src._parameters ) {
src._parameters.forEach(function( parameter ) {
needed = needed || group[parameter + '_rel'];
});
if ( needed ) {
group[name] = src._updaters ?
src._updaters[0].apply( null, [
name, [], [], leaf.parentAnchors, Utils
].concat(
( src._parameters || [] )
.map(handleGroup)
)) :
src;
}
}
});
}
});
};
Utils.updateProperties = function( leaf, params, erroredPreviously ) {
if ( !leaf.solvingOrder ) {
return;
}
var errored;
// don't use forEach here as we might add items to the array during the loop
for ( var i = 0; i < leaf.solvingOrder.length; i++ ) {
var _cursor = leaf.solvingOrder[i],
cursor = _cursor.cursor,
propName = cursor[ cursor.length - 1 ],
src = _cursor.src || ( _cursor.src =
Utils.propFromCursor( cursor, leaf.src ) ),
obj = _cursor.obj || ( _cursor.obj =
Utils.propFromCursor( cursor, leaf, cursor.length - 1 ) ),
// TODO: one day we could allow multiple _updaters
result;
if ( src && src._updaters ) {
try {
result = src._updaters[0].apply(
obj,
[
propName, leaf.contours, leaf.anchors,
leaf.parentAnchors, Utils
].concat(
( src._parameters || [] ).map(function(_name) {
if ( !(_name in params) ) {
/* #if dev */
/* eslint-disable no-console */
console.warn(
'undefined parameter',
_name,
'used in property',
cursor.join('.'),
'from component',
leaf.name
);
/* eslint-enable no-console */
/* #end */
}
return params[_name];
})
)
);
if ( typeof result === 'number' && isNaN(result) ) {
/* #if dev */
/* eslint-disable no-console */
console.warn(
'NaN returned by property',
cursor.join('.'),
'from component',
leaf.name
);
/* eslint-enable no-console */
/* #end */
}
} catch (e) {
/* #if dev */
/* eslint-disable no-console */
console.warn(
'Could not update property',
cursor.join('.'),
'from component',
leaf.name,
e
);
/* eslint-enable no-console */
/* #end */
// add the failing properties at the end of the solvingOrder
leaf.solvingOrder.push(_cursor);
errored = true;
}
}
// Assume that updaters returning undefined have their own
// assignment logic
if ( result !== undefined ) {
if (params.manualChanges && params.manualChanges.cursors) {
var cursorName = cursor.join('.');
var changes = params.manualChanges.cursors[cursorName];
if (typeof changes === 'number') {
if (typeof result === 'string') {
result = (parseFloat(result) + changes / Math.PI * 180) + 'deg';
} else if (typeof result === 'number') {
result += changes;
}
} else if (typeof changes === 'object') {
Object.keys(changes).forEach(key => {
if (result.hasOwnProperty(key)) {
if (key !== 'width') {
if (typeof result[key] === 'string') {
result[key] = (parseFloat(result[key]) + changes[key] / Math.PI * 180) + 'deg';
} else if (typeof result[key] === 'number') {
result[key] += changes[key];
}
} else {
result[key] *= 1 + changes[key];
}
}
})
}
delete params.manualChanges.cursors[cursorName];
}
obj[propName] = result;
}
}
var cursorKeys = params.manualChanges && params.manualChanges.cursors ? Object.keys(params.manualChanges.cursors) : [];
var validCursor = filter(cursorKeys, function(cursorString) {
var cursor = cursorString.split('.');
var tmpObj = Utils.propFromCursor( cursor, leaf, cursor.length - 1 );
return tmpObj !== undefined;
});
if (validCursor.length > 0) {
for (i = 0; i < validCursor.length; i++) {
var cursorKeyArray = validCursor[i].split('.');
var tmpObj = Utils.propFromCursor( cursorKeyArray, leaf, cursorKeyArray.length - 1 );
var tmpSrc;
if (tmpObj.oldUpdaters && tmpObj.oldUpdaters[cursorKeyArray[cursorKeyArray.length - 1]]) {
tmpSrc = tmpObj.oldUpdaters[cursorKeyArray[cursorKeyArray.length - 1]];
} else {
tmpSrc = {
_updaters: [ Utils.createUpdater({
_operation: JSON.stringify(tmpObj[cursorKeyArray[cursorKeyArray.length - 1]] || 0),
}) ],
};
tmpObj.oldUpdaters = tmpObj.oldUpdaters || {};
tmpObj.oldUpdaters[cursorKeyArray[cursorKeyArray.length - 1]] = tmpSrc;
}
var newCursor = {
cursor: cursorKeyArray,
obj: tmpObj,
src: tmpSrc,
manual: true,
};
leaf.solvingOrder.unshift(newCursor);
params.manualChanges.dirty--;
}
errored = true;
erroredPreviously = false;
}
// If one update errored, we're going to try once more, hoping things will
// get resolved on the second pass.
if ( errored && !erroredPreviously ) {
Utils.updateProperties( leaf, params, true );
// any error on the second try will cause it to throw
} else if ( errored && erroredPreviously ) {
throw 'Too much update errors, giving up.';
}
};
// The ascender and descender properties must be set to their maximum
// values accross the individualized params groups
Utils.updateXscenderProperties = function( font, params ) {
if ( params['indiv_group_param'] ) {
var xscenderProperties = [
'ascender',
'descender',
'cap-height',
'descendent-height'
];
xscenderProperties.forEach(function( name ) {
var src = font.src.fontinfo[ name ];
Object.keys( params['indiv_group_param'] )
.forEach(function( groupName ) {
var group = params['indiv_group_param'][groupName];
var sign = font.ot[name] > 0 ? 1 : -1;
font.ot[ name ] = sign * Math.max( Math.abs(font.ot[ name ]),
Math.abs(src._updaters[0].apply(
font.ot,
[
name, null, null, null, Utils
].concat(
( src._parameters || [] ).map(function(_name) {
return group[_name] || params[_name];
})
)
))
);
});
});
}
}
module.exports = Utils;
|
gpl-3.0
|
boriel/zxbasic
|
src/arch/z80/backend/_16bit.py
|
31574
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# --------------------------------------------------------------
# Copyleft (k) 2008, by Jose M. Rodriguez-Rosa
# (a.k.a. Boriel, http://www.boriel.com)
#
# This module contains 16 bit boolean, arithmetic and
# comparison intermediate-code translations
# --------------------------------------------------------------
from typing import List
from src.arch.z80.backend.runtime import Labels as RuntimeLabel
from src.arch.z80.backend.common import is_int, log2, is_2n, _int_ops, tmp_label, runtime_call, Quad
from src.arch.z80.backend._8bit import _8bit_oper
# -----------------------------------------------------
# 16 bits operands
# -----------------------------------------------------
def int16(op):
"""Returns a 16 bit operand converted to 16 bits unsigned int.
Negative numbers are returned in 2 complement.
"""
return int(op) & 0xFFFF
def _16bit_oper(op1, op2=None, reversed=False):
"""Returns pop sequence for 16 bits operands
1st operand in HL, 2nd operand in DE
For subtraction, division, etc. you can swap operators extraction order
by setting reversed to True
"""
output = []
if op1 is not None:
op1 = str(op1) # always to str
if op2 is not None:
op2 = str(op2) # always to str
if op2 is not None and reversed:
op1, op2 = op2, op1
op = op1
indirect = op[0] == "*"
if indirect:
op = op[1:]
immediate = op[0] == "#"
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append("ld hl, (%i)" % op)
else:
output.append("ld hl, %i" % int16(op))
else:
if immediate:
if indirect:
output.append("ld hl, (%s)" % op)
else:
output.append("ld hl, %s" % op)
else:
if op[0] == "_":
output.append("ld hl, (%s)" % op)
else:
output.append("pop hl")
if indirect:
output.append("ld a, (hl)")
output.append("inc hl")
output.append("ld h, (hl)")
output.append("ld l, a")
if op2 is None:
return output
if not reversed:
tmp = output
output = []
op = op2
indirect = op[0] == "*"
if indirect:
op = op[1:]
immediate = op[0] == "#"
if immediate:
op = op[1:]
if is_int(op):
op = int(op)
if indirect:
output.append("ld de, (%i)" % op)
else:
output.append("ld de, %i" % int16(op))
else:
if immediate:
output.append("ld de, %s" % op)
else:
if op[0] == "_":
output.append("ld de, (%s)" % op)
else:
output.append("pop de")
if indirect:
output.append(runtime_call(RuntimeLabel.LOAD_DE_DE)) # DE = (DE)
if not reversed:
output.extend(tmp)
return output
# -----------------------------------------------------
# Arithmetic operations
# -----------------------------------------------------
def _add16(ins: Quad) -> List[str]:
"""Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A
* If any of the operands is < 4, then
INC is used
* If any of the operands is > (65531) (-4), then
DEC is used
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
op2 = int16(op2)
output = _16bit_oper(op1)
if op2 == 0:
output.append("push hl")
return output # ADD HL, 0 => NOTHING
if op2 < 4:
output.extend(["inc hl"] * op2) # ADD HL, 2 ==> inc hl; inc hl
output.append("push hl")
return output
if op2 > 65531: # (between -4 and 0)
output.extend(["dec hl"] * (0x10000 - op2))
output.append("push hl")
return output
output.append("ld de, %i" % op2)
output.append("add hl, de")
output.append("push hl")
return output
if op2[0] == "_": # stack optimization
op1, op2 = op2, op1
output = _16bit_oper(op1, op2)
output.append("add hl, de")
output.append("push hl")
return output
def _sub16(ins: Quad) -> List[str]:
"""Pops last 2 words from the stack and subtract them.
Then push the result onto the stack. Top of the stack is
subtracted Top -1
Optimizations:
* If 2nd op is ZERO,
then do NOTHING: A - 0 = A
* If any of the operands is < 4, then
DEC is used
* If any of the operands is > 65531 (-4..-1), then
INC is used
"""
op1, op2 = tuple(ins.quad[2:4])
if is_int(op2):
op = int16(op2)
output = _16bit_oper(op1)
if op == 0:
output.append("push hl")
return output
if op < 4:
output.extend(["dec hl"] * op)
output.append("push hl")
return output
if op > 65531:
output.extend(["inc hl"] * (0x10000 - op))
output.append("push hl")
return output
output.append("ld de, -%i" % op)
output.append("add hl, de")
output.append("push hl")
return output
if op2[0] == "_": # Optimization when 2nd operand is an id
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _16bit_oper(op1, op2, rev)
output.append("or a")
output.append("sbc hl, de")
output.append("push hl")
return output
def _mul16(ins: Quad) -> List[str]:
"""Multiplies tow last 16bit values on top of the stack and
and returns the value on top of the stack
Optimizations:
* If any of the ops is ZERO,
then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0
* If any ot the ops is ONE, do NOTHING
A * 1 = 1 * A = A
* If B is 2^n and B < 16 => Shift Right n
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None: # If any of the operands is constant
op1, op2 = _int_ops(op1, op2) # put the constant one the 2nd
output = _16bit_oper(op1)
if op2 == 0: # A * 0 = 0 * A = 0
if op1[0] in ("_", "$"):
output = [] # Optimization: Discard previous op if not from the stack
output.append("ld hl, 0")
output.append("push hl")
return output
if op2 == 1: # A * 1 = 1 * A == A => Do nothing
output.append("push hl")
return output
if op2 == 0xFFFF: # This is the same as (-1)
output.append(runtime_call(RuntimeLabel.NEGHL))
output.append("push hl")
return output
if is_2n(op2) and log2(op2) < 4:
output.extend(["add hl, hl"] * int(log2(op2)))
output.append("push hl")
return output
output.append("ld de, %i" % op2)
else:
if op2[0] == "_": # stack optimization
op1, op2 = op2, op1
output = _16bit_oper(op1, op2)
output.append(runtime_call(RuntimeLabel.MUL16_FAST)) # Immediate
output.append("push hl")
return output
def _divu16(ins: Quad) -> List[str]:
"""Divides 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op1) and int(op1) == 0: # 0 / A = 0
if op2[0] in ("_", "$"):
output = [] # Optimization: Discard previous op if not from the stack
else:
output = _16bit_oper(op2) # Normalize stack
output.append("ld hl, 0")
output.append("push hl")
return output
if is_int(op2):
op = int16(op2)
output = _16bit_oper(op1)
if op2 == 0: # A * 0 = 0 * A = 0
if op1[0] in ("_", "$"):
output = [] # Optimization: Discard previous op if not from the stack
output.append("ld hl, 0")
output.append("push hl")
return output
if op == 1:
output.append("push hl")
return output
if op == 2:
output.append("srl h")
output.append("rr l")
output.append("push hl")
return output
output.append("ld de, %i" % op)
else:
if op2[0] == "_": # Optimization when 2nd operand is an id
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _16bit_oper(op1, op2, rev)
output.append(runtime_call(RuntimeLabel.DIVU16))
output.append("push hl")
return output
def _divi16(ins: Quad) -> List[str]:
"""Divides 2 16bit signed integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is -1 then
do NEG
* If 2nd op is 2 then
Shift Right Arithmetic
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op1) and int(op1) == 0: # 0 / A = 0
if op2[0] in ("_", "$"):
output = [] # Optimization: Discard previous op if not from the stack
else:
output = _16bit_oper(op2) # Normalize stack
output.append("ld hl, 0")
output.append("push hl")
return output
if is_int(op2):
op = int16(op2)
output = _16bit_oper(op1)
if op == 1:
output.append("push hl")
return output
if op == -1:
output.append(runtime_call(RuntimeLabel.NEGHL)) # TODO: Is this ever used?
output.append("push hl")
return output
if op == 2:
output.append("sra h")
output.append("rr l")
output.append("push hl")
return output
output.append("ld de, %i" % op)
else:
if op2[0] == "_": # Optimization when 2nd operand is an id
rev = True
op1, op2 = op2, op1
else:
rev = False
output = _16bit_oper(op1, op2, rev)
output.append(runtime_call(RuntimeLabel.DIVI16))
output.append("push hl")
return output
def _modu16(ins: Quad) -> List[str]:
"""Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1 => Return 0
* If 2nd operand = 2^n => do AND (2^n - 1)
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int16(op2)
output = _16bit_oper(op1)
if op2 == 1:
if op2[0] in ("_", "$"):
output = [] # Optimization: Discard previous op if not from the stack
output.append("ld hl, 0")
output.append("push hl")
return output
if is_2n(op2):
k = op2 - 1
if op2 > 255: # only affects H
output.append("ld a, h")
output.append("and %i" % (k >> 8))
output.append("ld h, a")
else:
output.append("ld h, 0") # High part goes 0
output.append("ld a, l")
output.append("and %i" % (k % 0xFF))
output.append("ld l, a")
output.append("push hl")
return output
output.append("ld de, %i" % op2)
else:
output = _16bit_oper(op1, op2)
output.append(runtime_call(RuntimeLabel.MODU16))
output.append("push hl")
return output
def _modi16(ins: Quad) -> List[str]:
"""Reminder of div 2 16bit signed integers. The result is pushed onto the stack.
Optimizations:
* If 2nd operand is 1 => Return 0
* If 2nd operand = 2^n => do AND (2^n - 1)
"""
op1, op2 = tuple(ins.quad[2:])
if is_int(op2):
op2 = int16(op2)
output = _16bit_oper(op1)
if op2 == 1:
if op1 in ("_", "$"):
output = [] # Optimization: Discard previous op if not from the stack
output.append("ld hl, 0")
output.append("push hl")
return output
if is_2n(op2):
k = op2 - 1
if op2 > 255: # only affects H
output.append("ld a, h")
output.append("and %i" % (k >> 8))
output.append("ld h, a")
else:
output.append("ld h, 0") # High part goes 0
output.append("ld a, l")
output.append("and %i" % (k % 0xFF))
output.append("ld l, a")
output.append("push hl")
return output
output.append("ld de, %i" % op2)
else:
output = _16bit_oper(op1, op2)
output.append(runtime_call(RuntimeLabel.MODI16))
output.append("push hl")
return output
def _ltu16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append("or a")
output.append("sbc hl, de")
output.append("sbc a, a")
output.append("push af")
return output
def _lti16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit signed version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append(runtime_call(RuntimeLabel.LTI16))
output.append("push af")
return output
def _gtu16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True)
output.append("or a")
output.append("sbc hl, de")
output.append("sbc a, a")
output.append("push af")
return output
def _gti16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand > 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit signed version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True)
output.append(runtime_call(RuntimeLabel.LTI16))
output.append("push af")
return output
def _leu16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True)
output.append("or a")
output.append("sbc hl, de") # Carry if A > B
output.append("ccf") # Negates the result => Carry if A <= B
output.append("sbc a, a")
output.append("push af")
return output
def _lei16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit signed version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append(runtime_call(RuntimeLabel.LEI16))
output.append("push af")
return output
def _geu16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append("or a")
output.append("sbc hl, de")
output.append("ccf")
output.append("sbc a, a")
output.append("push af")
return output
def _gei16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand >= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit signed version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True)
output.append(runtime_call(RuntimeLabel.LEI16))
output.append("push af")
return output
def _eq16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand == 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit un/signed version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append(runtime_call(RuntimeLabel.EQ16))
output.append("push af")
return output
def _ne16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand != 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit un/signed version
"""
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append("or a") # Resets carry flag
output.append("sbc hl, de")
output.append("ld a, h")
output.append("or l")
output.append("push af")
return output
def _or16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand OR (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
the other operand
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
if op2 == 0:
output = _16bit_oper(op1)
output.append("ld a, h")
output.append("or l") # Convert x to Boolean
output.append("push af")
return output # X or False = X
output = _16bit_oper(op1)
output.append("ld a, 0FFh") # X or True = True
output.append("push af")
return output
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append("ld a, h")
output.append("or l")
output.append("or d")
output.append("or e")
output.append("push af")
return output
def _bor16(ins: Quad) -> List[str]:
"""Pops top 2 operands out of the stack, and performs
1st operand OR (bitwise) 2nd operand (top of the stack),
pushes result (16 bit in HL).
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
the other operand
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _16bit_oper(op1)
if op2 == 0: # X | 0 = X
output.append("push hl")
return output
if op2 == 0xFFFF: # X & 0xFFFF = 0xFFFF
output.append("ld hl, 0FFFFh")
output.append("push hl")
return output
output = _16bit_oper(op1, op2)
output.append(runtime_call(RuntimeLabel.BOR16))
output.append("push hl")
return output
def _xor16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand XOR (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
the other operand
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _16bit_oper(op1)
if op2 == 0: # X xor False = X
output.append("ld a, h")
output.append("or l")
output.append("push af")
return output
# X xor True = NOT X
output.append("ld a, h")
output.append("or l")
output.append("sub 1")
output.append("sbc a, a")
output.append("push af")
return output
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append(runtime_call(RuntimeLabel.XOR16))
output.append("push af")
return output
def _bxor16(ins: Quad) -> List[str]:
"""Pops top 2 operands out of the stack, and performs
1st operand XOR (bitwise) 2nd operand (top of the stack),
pushes result (16 bit in HL).
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
the other operand
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _16bit_oper(op1)
if op2 == 0: # X ^ 0 = X
output.append("push hl")
return output
if op2 == 0xFFFF: # X ^ 0xFFFF = bNOT X
output.append(runtime_call(RuntimeLabel.NEGHL))
output.append("push hl")
return output
output = _16bit_oper(op1, op2)
output.append(runtime_call(RuntimeLabel.BXOR16))
output.append("push hl")
return output
def _and16(ins: Quad) -> List[str]:
"""Compares & pops top 2 operands out of the stack, and checks
if the 1st operand AND (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
the other operand
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
output = _16bit_oper(op1)
if op2 != 0:
output.append("ld a, h")
output.append("or l")
output.append("push af")
return output # X and True = X
output = _16bit_oper(op1)
output.append("xor a") # X and False = False
output.append("push af")
return output
output = _16bit_oper(op1, op2)
output.append(runtime_call(RuntimeLabel.AND16))
output.append("push af")
return output
def _band16(ins: Quad) -> List[str]:
"""Pops top 2 operands out of the stack, and performs
1st operand AND (bitwise) 2nd operand (top of the stack),
pushes result (16 bit in HL).
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
the other operand
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
if op2 == 0xFFFF: # X & 0xFFFF = X
return []
if op2 == 0: # X & 0 = 0
output = _16bit_oper(op1)
output.append("ld hl, 0")
output.append("push hl")
return output
output = _16bit_oper(op1, op2)
output.append(runtime_call(RuntimeLabel.BAND16))
output.append("push hl")
return output
def _not16(ins: Quad) -> List[str]:
"""Negates top (Logical NOT) of the stack (16 bits in HL)"""
output = _16bit_oper(ins.quad[2])
output.append("ld a, h")
output.append("or l")
output.append("sub 1")
output.append("sbc a, a")
output.append("push af")
return output
def _bnot16(ins: Quad) -> List[str]:
"""Negates top (Bitwise NOT) of the stack (16 bits in HL)"""
output = _16bit_oper(ins.quad[2])
output.append(runtime_call(RuntimeLabel.BNOT16))
output.append("push hl")
return output
def _neg16(ins: Quad) -> List[str]:
"""Negates top of the stack (16 bits in HL)"""
output = _16bit_oper(ins.quad[2])
output.append(runtime_call(RuntimeLabel.NEGHL))
output.append("push hl")
return output
def _abs16(ins: Quad) -> List[str]:
"""Absolute value of top of the stack (16 bits in HL)"""
output = _16bit_oper(ins.quad[2])
output.append(runtime_call(RuntimeLabel.ABS16))
output.append("push hl")
return output
def _shru16(ins: Quad) -> List[str]:
"""Logical right shift 16bit unsigned integer.
The result is pushed onto the stack.
Optimizations:
* If 2nd op is 0 then
do nothing
* If 2nd op is 1
Shift Right Arithmetic
"""
op1, op2 = tuple(ins.quad[2:])
label = tmp_label()
label2 = tmp_label()
if is_int(op2):
op = int16(op2)
if op == 0:
return []
output = _16bit_oper(op1)
if op == 1:
output.append("srl h")
output.append("rr l")
output.append("push hl")
return output
output.append("ld b, %i" % op)
else:
output = _8bit_oper(op2)
output.append("ld b, a")
output.extend(_16bit_oper(op1))
output.append("or a")
output.append("jr z, %s" % label2)
output.append("%s:" % label)
output.append("srl h")
output.append("rr l")
output.append("djnz %s" % label)
output.append("%s:" % label2)
output.append("push hl")
return output
def _shri16(ins: Quad) -> List[str]:
"""Arithmetical right shift 16bit signed integer.
The result is pushed onto the stack.
Optimizations:
* If 2nd op is 0 then
do nothing
* If 2nd op is 1
Shift Right Arithmetic
"""
op1, op2 = tuple(ins.quad[2:])
label = tmp_label()
label2 = tmp_label()
if is_int(op2):
op = int16(op2)
if op == 0:
return []
output = _16bit_oper(op1)
if op == 1:
output.append("srl h")
output.append("rr l")
output.append("push hl")
return output
output.append("ld b, %i" % op)
else:
output = _8bit_oper(op2)
output.append("ld b, a")
output.extend(_16bit_oper(op1))
output.append("or a")
output.append("jr z, %s" % label2)
output.append("%s:" % label)
output.append("sra h")
output.append("rr l")
output.append("djnz %s" % label)
output.append("%s:" % label2)
output.append("push hl")
return output
def _shl16(ins: Quad) -> List[str]:
"""Logical/aritmetical left shift 16bit (un)signed integer.
The result is pushed onto the stack.
Optimizations:
* If 2nd op is 0 then
do nothing
* If 2nd op is lower than 6
unroll lop
"""
op1, op2 = tuple(ins.quad[2:])
label = tmp_label()
label2 = tmp_label()
if is_int(op2):
op = int16(op2)
if op == 0:
return []
output = _16bit_oper(op1)
if op < 6:
output.extend(["add hl, hl"] * op)
output.append("push hl")
return output
output.append("ld b, %i" % op)
else:
output = _8bit_oper(op2)
output.append("ld b, a")
output.extend(_16bit_oper(op1))
output.append("or a")
output.append("jr z, %s" % label2)
output.append("%s:" % label)
output.append("add hl, hl")
output.append("djnz %s" % label)
output.append("%s:" % label2)
output.append("push hl")
return output
def _load16(ins: Quad) -> List[str]:
"""Loads a 16 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _16bit_oper(ins.quad[2])
output.append("push hl")
return output
def _store16(ins: Quad) -> List[str]:
"""Stores 2nd operand content into address of 1st operand.
store16 a, x => *(&a) = x
Use '*' for indirect store on 1st operand.
"""
output = _16bit_oper(ins.quad[2])
value = ins.quad[1]
indirect = False
try:
if value[0] == "*":
indirect = True
value = value[1:]
value = int(value) & 0xFFFF
if indirect:
output.append("ex de, hl")
output.append("ld hl, (%s)" % str(value))
output.append("ld (hl), e")
output.append("inc hl")
output.append("ld (hl), d")
else:
output.append("ld (%s), hl" % str(value))
except ValueError:
if value[0] in "_.":
if indirect:
output.append("ex de, hl")
output.append("ld hl, (%s)" % str(value))
output.append("ld (hl), e")
output.append("inc hl")
output.append("ld (hl), d")
else:
output.append("ld (%s), hl" % str(value))
elif value[0] == "#":
value = value[1:]
if indirect:
output.append("ex de, hl")
output.append("ld hl, (%s)" % str(value))
output.append("ld (hl), e")
output.append("inc hl")
output.append("ld (hl), d")
else:
output.append("ld (%s), hl" % str(value))
else:
output.append("ex de, hl")
if indirect:
output.append("pop hl")
output.append("ld a, (hl)")
output.append("inc hl")
output.append("ld h, (hl)")
output.append("ld l, a")
else:
output.append("pop hl")
output.append("ld (hl), e")
output.append("inc hl")
output.append("ld (hl), d")
return output
def _jzero16(ins: Quad) -> List[str]:
"""Jumps if top of the stack (16bit) is 0 to arg(1)"""
value = ins.quad[1]
if is_int(value):
if int(value) == 0:
return ["jp %s" % str(ins.quad[2])] # Always true
else:
return []
output = _16bit_oper(value)
output.append("ld a, h")
output.append("or l")
output.append("jp z, %s" % str(ins.quad[2]))
return output
def _jgezerou16(ins: Quad) -> List[str]:
"""Jumps if top of the stack (16bit) is >= 0 to arg(1)
Always TRUE for unsigned
"""
output = []
value = ins.quad[1]
if not is_int(value):
output = _16bit_oper(value)
output.append("jp %s" % str(ins.quad[2]))
return output
def _jgezeroi16(ins: Quad) -> List[str]:
"""Jumps if top of the stack (16bit) is >= 0 to arg(1)"""
value = ins.quad[1]
if is_int(value):
if int(value) >= 0:
return ["jp %s" % str(ins.quad[2])] # Always true
else:
return []
output = _16bit_oper(value)
output.append("add hl, hl") # Puts sign into carry
output.append("jp nc, %s" % str(ins.quad[2]))
return output
def _ret16(ins: Quad) -> List[str]:
"""Returns from a procedure / function a 16bits value"""
output = _16bit_oper(ins.quad[1])
output.append("#pragma opt require hl")
output.append("jp %s" % str(ins.quad[2]))
return output
def _param16(ins: Quad) -> List[str]:
"""Pushes 16bit param into the stack"""
output = _16bit_oper(ins.quad[1])
output.append("push hl")
return output
def _fparam16(ins: Quad) -> List[str]:
"""Passes a word as a __FASTCALL__ parameter.
This is done by popping out of the stack for a
value, or by loading it from memory (indirect)
or directly (immediate)
"""
return _16bit_oper(ins.quad[1])
def _jnzero16(ins: Quad) -> List[str]:
"""Jumps if top of the stack (16bit) is != 0 to arg(1)"""
value = ins.quad[1]
if is_int(value):
if int(value) != 0:
return ["jp %s" % str(ins.quad[2])] # Always true
else:
return []
output = _16bit_oper(value)
output.append("ld a, h")
output.append("or l")
output.append("jp nz, %s" % str(ins.quad[2]))
return output
|
gpl-3.0
|
lighthouse64/Random-Dungeon
|
src/com/lh64/randomdungeon/items/rings/RingOfThorns.java
|
1757
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.lh64.randomdungeon.items.rings;
import com.lh64.randomdungeon.Badges;
import com.lh64.randomdungeon.actors.hero.Hero;
import com.lh64.randomdungeon.items.Item;
public class RingOfThorns extends Ring {
{
name = "Ring of Thorns";
}
@Override
protected RingBuff buff( ) {
return new Thorns();
}
@Override
public Item random() {
level( +1 );
return this;
}
@Override
public boolean doPickUp( Hero hero ) {
identify();
Badges.validateRingOfThorns();
Badges.validateItemLevelAquired( this );
return super.doPickUp(hero);
}
@Override
public boolean isUpgradable() {
return false;
}
@Override
public void use() {
// Do nothing (it can't degrade)
}
@Override
public String desc() {
return isKnown() ?
"Though this ring doesn't provide real thorns, an enemy that attacks you " +
"will itself be wounded by a fraction of the damage that it inflicts. " +
"Upgrading this ring won't give any additional bonuses." :
super.desc();
}
public class Thorns extends RingBuff {
}
}
|
gpl-3.0
|
jackbergus/Amppercent7
|
src/my/amppercent/adapters/AdapterIM.java
|
2981
|
package my.amppercent.adapters;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import my.amppercent.project.R;
import my.amppercent.remoteservice.IBinding;
import my.amppercent.remoteservice.IntentManage;
/**
* Adattatore per la visualizzazione della lista di Intent per la
* visualizzazione delle richieste di download
*
* @author jack
*
*/
public class AdapterIM extends AdapterElems<IntentManage> {
private IBinding service;
public AdapterIM(Context context, int resource, int textViewResourceId,
IntentManage[] objects) {
super(context, resource, textViewResourceId, objects);
}
public AdapterIM(Context context, int resource, int textViewResourceId,
List<IntentManage> objects) {
super(context, resource, textViewResourceId, objects);
}
public static AdapterIM ArrayNullInit(Context context, int resource,
int textViewResourceId, IntentManage[] objects) {
if ((objects == null) || (objects.length == 0)) {
return new AdapterIM(context, resource, textViewResourceId,
new LinkedList<IntentManage>());
} else {
List<IntentManage> im = new LinkedList<IntentManage>();
for (IntentManage x : objects)
im.add(x);
return new AdapterIM(context, resource, textViewResourceId, im);
}
}
public void setService(IBinding s) {
this.service = s;
}
public void remove(IntentManage x) {
super.remove(x);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
final IntentManage im = getItem(position);
final TextView from = (TextView) row.findViewById(R.id.To_or_From_text);
final TextView file = (TextView) row.findViewById(R.id.File_name);
final Button ok = (Button) row.findViewById(R.id.Download_button_file);
final Button ko = (Button) row.findViewById(R.id.Decline_button_file);
file.setText(im.second_argument);
from.setText(im.first_argument);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (service != null) {
try {
ok.setEnabled(false);
boolean result = service.handleFileRequest(im.connid,
im.passwo, true, im.getId(), im.second_argument);
if (result) {
Log.d("result", "ok");
ko.setEnabled(false);
}
im.handled = true;
remove(im);
} catch (Throwable e) {
}
}
}
});
ko.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (service != null) {
try {
ok.setEnabled(false);
service.handleFileRequest(im.connid, im.passwo, true,
im.getId(), im.second_argument);
ko.setEnabled(false);
im.handled = true;
remove(im);
} catch (Throwable e) {
}
}
}
});
return row;
}
}
|
gpl-3.0
|
FabLab-LaCote/avionmake
|
typings/tsd.d.ts
|
731
|
/// <reference path="angularjs/angular-sanitize.d.ts" />
/// <reference path="angularjs/angular-cookies.d.ts" />
/// <reference path="angularjs/angular-route.d.ts" />
/// <reference path="angularjs/angular-resource.d.ts" />
/// <reference path="angularjs/angular-mocks.d.ts" />
/// <reference path="jasmine/jasmine.d.ts" />
/// <reference path="jquery/jquery.d.ts" />
/// <reference path="angularjs/angular.d.ts" />
/// <reference path="angular-translate/angular-translate.d.ts" />
/// <reference path="angular-material/angular-material.d.ts" />
/// <reference path="webrtc/MediaStream.d.ts" />
/// <reference path="dat-gui/dat-gui.d.ts" />
/// <reference path="raphael/raphael.d.ts" />
/// <reference path="threejs/three.d.ts" />
|
gpl-3.0
|
bsmr-games/lipsofsuna
|
src/lipsofsuna/extension/image/image-compress.cpp
|
3072
|
/* Lips of Suna
* Copyright© 2007-2010 Lips of Suna development team.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
/**
* \addtogroup LIImg Image
* @{
* \addtogroup LIImgCompress Compress
* @{
*/
#ifdef HAVE_SQUISH
#include <squish.h>
#include "ddstool-compress.h"
/**
* \brief Compresses RGBA pixel data to DXT5 bytes.
* \param pixels RGBA pixels to compress.
* \param width Width.
* \param height Height.
* \param type DXT format number.
* \param result Return location for compressed data.
*/
void liimg_compress_compress (
const void* pixels,
int width,
int height,
int type,
void* result)
{
int flags;
switch (type)
{
case 1: flags = squish::kColourClusterFit | squish::kDxt1; break;
case 3: flags = squish::kColourClusterFit | squish::kDxt3; break;
default: flags = squish::kColourClusterFit | squish::kDxt5; break;
}
squish::CompressImage ((squish::u8*) pixels, width, height, result, flags);
}
/**
* \brief Uncompresses DXT5 bytes to RGBA pixel data.
* \param pixels DXT5 bytes to uncompress.
* \param width Width.
* \param height Height.
* \param type DXT format number.
* \param result Return location for uncompressed pixels.
*/
void liimg_compress_uncompress (
const void* pixels,
int width,
int height,
int type,
void* result)
{
int flags;
switch (type)
{
case 1: flags = squish::kColourClusterFit | squish::kDxt1; break;
case 3: flags = squish::kColourClusterFit | squish::kDxt3; break;
default: flags = squish::kColourClusterFit | squish::kDxt5; break;
}
squish::DecompressImage ((squish::u8*) result, width, height, pixels, flags);
}
/**
* \brief Gets storage requirements for compressed pixel data.
* \param width Width.
* \param height Height.
* \param type DXT format number.
* \return Number of bytes.
*/
int liimg_compress_storage (
int width,
int height,
int type)
{
int flags;
switch (type)
{
case 1: flags = squish::kColourClusterFit | squish::kDxt1; break;
case 3: flags = squish::kColourClusterFit | squish::kDxt3; break;
default: flags = squish::kColourClusterFit | squish::kDxt5; break;
}
return squish::GetStorageRequirements(width, height, flags);
}
#endif
/** @} */
/** @} */
|
gpl-3.0
|
oicr-gsi/niassa
|
seqware-pipeline/src/main/java/net/sourceforge/seqware/pipeline/plugins/ProcessingDataStructure2Dot.java
|
3911
|
package net.sourceforge.seqware.pipeline.plugins;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import joptsimple.ArgumentAcceptingOptionSpec;
import net.sourceforge.seqware.common.module.ReturnValue;
import net.sourceforge.seqware.common.module.ReturnValue.ExitStatus;
import net.sourceforge.seqware.common.util.Rethrow;
import net.sourceforge.seqware.pipeline.plugin.Plugin;
import net.sourceforge.seqware.pipeline.plugin.PluginInterface;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.openide.util.lookup.ServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ServiceProvider(service = PluginInterface.class)
public class ProcessingDataStructure2Dot extends Plugin {
private final Logger logger = LoggerFactory.getLogger(ProcessingDataStructure2Dot.class);
private final ArgumentAcceptingOptionSpec<String> processingSWIDSpec;
private final ArgumentAcceptingOptionSpec<String> outputFileSpec;
public ProcessingDataStructure2Dot() {
super();
this.processingSWIDSpec = parser.accepts("parent-accession", "The SWID of the processing").withRequiredArg().ofType(String.class)
.required().describedAs("The SWID of the processing.");
this.outputFileSpec = parser.accepts("output-file", "Optional: file name").withRequiredArg().ofType(String.class)
.describedAs("Output File Name").defaultsTo("output.dot");
}
@Override
public ReturnValue init() {
return new ReturnValue();
}
@Override
public ReturnValue do_test() {
return new ReturnValue();
}
@Override
public ReturnValue do_run() {
String swAccession = options.valueOf(processingSWIDSpec);
String outputFile = options.valueOf(outputFileSpec);
String output = metadata.getProcessingRelations(swAccession);
if (output == null) {
logger.error("Could not find processing event, please check that this is a valid processing SWID");
return new ReturnValue(ExitStatus.INVALIDPARAMETERS);
}
System.out.println("Writing dot file to " + outputFile);
try (Writer writer = new BufferedWriter(new FileWriter(outputFile))) {
writer.write(output);
} catch (IOException e) {
throw Rethrow.rethrow(e);
}
return new ReturnValue();
}
@Override
public String get_description() {
return "This plugin will take in a sw_accession of a processing, and translate the hierarchy of the processing relationship into dot format";
}
@Override
public ReturnValue clean_up() {
return new ReturnValue();
}
private class DotNode {
private final List<DotNode> children;
private final String processingId;
public DotNode(String pid) {
this.children = new ArrayList<>();
this.processingId = pid;
}
public void addChild(DotNode node) {
if (!this.children.contains(node)) this.children.add(node);
}
@Override
public String toString() {
return this.processingId;
}
public List<DotNode> getChildren() {
return this.children;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DotNode == false) return false;
if (obj == this) return true;
DotNode rhs = (DotNode) obj;
return new EqualsBuilder().appendSuper(super.equals(obj)).append(this.processingId, rhs.processingId).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37).append(this.processingId).toHashCode();
}
}
}
|
gpl-3.0
|
FlowsenAusMonotown/projectforge
|
projectforge-business/src/main/java/org/projectforge/business/gantt/GanttObjectType.java
|
1626
|
/////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2014 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition 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.
//
// This community edition is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.business.gantt;
import org.projectforge.common.i18n.I18nEnum;
public enum GanttObjectType implements I18nEnum
{
ACTIVITY("activity"), SUMMARY("summary"), MILESTONE("milestone");
private String key;
public boolean isIn(final GanttObjectType... types)
{
for (final GanttObjectType type : types) {
if (this == type) {
return true;
}
}
return false;
}
/**
* The key will be used e. g. for i18n.
*/
public String getKey()
{
return key;
}
public String getI18nKey()
{
return "gantt.objectType." + key;
}
GanttObjectType(final String key)
{
this.key = key;
}
}
|
gpl-3.0
|
dacrybabysuck/darkstar
|
scripts/zones/Bostaunieux_Oubliette/IDs.lua
|
3077
|
-----------------------------------
-- Area: Bostaunieux_Oubliette
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.BOSTAUNIEUX_OUBLIETTE] =
{
text =
{
CONQUEST_BASE = 0, -- Tallying conquest results...
ITEM_CANNOT_BE_OBTAINED = 6541, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6547, -- Obtained: <item>.
GIL_OBTAINED = 6548, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6550, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6561, -- There is nothing out of the ordinary here.
FISHING_MESSAGE_OFFSET = 7208, -- You can't fish here.
CHUMIA_DIALOG = 7308, -- Welcome to Bostaunieux Oubliette...
SEEMS_LOCKED = 7310, -- It seems to be locked.
SPIRAL_HELL_LEARNED = 7417, -- You have learned the weapon skill Spiral Hell!
SENSE_OMINOUS_PRESENCE = 7418, -- You sense an ominous presence...
REGIME_REGISTERED = 9532, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 10622, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
PLAYER_OBTAINS_ITEM = 10584, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 10585, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 10586, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 10587, -- You already possess that temporary item.
NO_COMBINATION = 10592, -- You were unable to enter a combination.
},
mob =
{
SEWER_SYRUP_PH =
{
[17461305] = 17461307, -- -19.000 1.000 -173.000
[17461306] = 17461307, -- -20.000 1.000 -148.000
},
SHII_PH =
{
[17461311] = 17461315, -- -59.000 0.941 -149.000
[17461334] = 17461315, -- -64.000 -0.500 -144.000
[17461277] = 17461315, -- -65.000 -1.000 -137.000
[17461309] = 17461315, -- -64.000 0.950 -132.000
[17461312] = 17461315, -- -53.000 -0.500 -137.000
[17461308] = 17461315, -- -57.000 0.998 -135.000
},
ARIOCH_PH =
{
[17461322] = 17461433, -- -259 0.489 -188
},
MANES_PH =
{
[17461469] = 17461471,
[17461470] = 17461471,
[17461476] = 17461471,
[17461477] = 17461471,
},
DREXERION_THE_CONDEMNED = 17461338,
PHANDURON_THE_CONDEMNED = 17461343,
BLOODSUCKER = 17461478,
BODACH = 17461479,
},
npc =
{
CASKET_BASE = 17461487,
},
}
return zones[dsp.zone.BOSTAUNIEUX_OUBLIETTE]
|
gpl-3.0
|
Niky4000/UsefulUtils
|
projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/SynchronizedStatement.java
|
7640
|
/*******************************************************************************
* Copyright (c) 2000, 2011, 2015 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Carmi Grushko - Bug 465048 - Binding is null for class literals in synchronized blocks
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.ast;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.codegen.*;
import org.eclipse.jdt.internal.compiler.flow.*;
import org.eclipse.jdt.internal.compiler.impl.Constant;
import org.eclipse.jdt.internal.compiler.lookup.*;
public class SynchronizedStatement extends SubRoutineStatement {
public Expression expression;
public Block block;
public BlockScope scope;
public LocalVariableBinding synchroVariable;
static final char[] SecretLocalDeclarationName = " syncValue".toCharArray(); //$NON-NLS-1$
// for local variables table attributes
int preSynchronizedInitStateIndex = -1;
int mergedSynchronizedInitStateIndex = -1;
public SynchronizedStatement(
Expression expression,
Block statement,
int s,
int e) {
this.expression = expression;
this.block = statement;
this.sourceEnd = e;
this.sourceStart = s;
}
@Override
public FlowInfo analyseCode(
BlockScope currentScope,
FlowContext flowContext,
FlowInfo flowInfo) {
this.preSynchronizedInitStateIndex =
currentScope.methodScope().recordInitializationStates(flowInfo);
// TODO (philippe) shouldn't it be protected by a check whether reachable statement ?
// mark the synthetic variable as being used
this.synchroVariable.useFlag = LocalVariableBinding.USED;
// simple propagation to subnodes
flowInfo =
this.block.analyseCode(
this.scope,
new InsideSubRoutineFlowContext(flowContext, this),
this.expression.analyseCode(this.scope, flowContext, flowInfo));
this.mergedSynchronizedInitStateIndex =
currentScope.methodScope().recordInitializationStates(flowInfo);
// optimizing code gen
if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0) {
this.bits |= ASTNode.BlockExit;
}
return flowInfo;
}
@Override
public boolean isSubRoutineEscaping() {
return false;
}
/**
* Synchronized statement code generation
*
* @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope
* @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream
*/
@Override
public void generateCode(BlockScope currentScope, CodeStream codeStream) {
if ((this.bits & IsReachable) == 0) {
return;
}
// in case the labels needs to be reinitialized
// when the code generation is restarted in wide mode
this.anyExceptionLabel = null;
int pc = codeStream.position;
// generate the synchronization expression
this.expression.generateCode(this.scope, codeStream, true);
if (this.block.isEmptyBlock()) {
switch(this.synchroVariable.type.id) {
case TypeIds.T_long :
case TypeIds.T_double :
codeStream.dup2();
break;
default :
codeStream.dup();
break;
}
// only take the lock
codeStream.monitorenter();
codeStream.monitorexit();
if (this.scope != currentScope) {
codeStream.exitUserScope(this.scope);
}
} else {
// enter the monitor
codeStream.store(this.synchroVariable, true);
codeStream.addVariable(this.synchroVariable);
codeStream.monitorenter();
// generate the body of the synchronized block
enterAnyExceptionHandler(codeStream);
this.block.generateCode(this.scope, codeStream);
if (this.scope != currentScope) {
// close all locals defined in the synchronized block except the secret local
codeStream.exitUserScope(this.scope, this.synchroVariable);
}
BranchLabel endLabel = new BranchLabel(codeStream);
if ((this.bits & ASTNode.BlockExit) == 0) {
codeStream.load(this.synchroVariable);
codeStream.monitorexit();
exitAnyExceptionHandler();
codeStream.goto_(endLabel);
enterAnyExceptionHandler(codeStream);
}
// generate the body of the exception handler
codeStream.pushExceptionOnStack(this.scope.getJavaLangThrowable());
if (this.preSynchronizedInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(currentScope, this.preSynchronizedInitStateIndex);
}
placeAllAnyExceptionHandler();
codeStream.load(this.synchroVariable);
codeStream.monitorexit();
exitAnyExceptionHandler();
codeStream.athrow();
// May loose some local variable initializations : affecting the local variable attributes
if (this.mergedSynchronizedInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(currentScope, this.mergedSynchronizedInitStateIndex);
codeStream.addDefinitelyAssignedVariables(currentScope, this.mergedSynchronizedInitStateIndex);
}
if (this.scope != currentScope) {
codeStream.removeVariable(this.synchroVariable);
}
if ((this.bits & ASTNode.BlockExit) == 0) {
endLabel.place();
}
}
codeStream.recordPositionsFrom(pc, this.sourceStart);
}
/**
* @see SubRoutineStatement#generateSubRoutineInvocation(BlockScope, CodeStream, Object, int, LocalVariableBinding)
*/
@Override
public boolean generateSubRoutineInvocation(BlockScope currentScope, CodeStream codeStream, Object targetLocation, int stateIndex, LocalVariableBinding secretLocal) {
codeStream.load(this.synchroVariable);
codeStream.monitorexit();
exitAnyExceptionHandler();
return false;
}
@Override
public void resolve(BlockScope upperScope) {
// special scope for secret locals optimization.
this.scope = new BlockScope(upperScope);
TypeBinding type = this.expression.resolveType(this.scope);
if (type != null) {
switch (type.id) {
case T_boolean :
case T_char :
case T_float :
case T_double :
case T_byte :
case T_short :
case T_int :
case T_long :
this.scope.problemReporter().invalidTypeToSynchronize(this.expression, type);
break;
case T_void :
this.scope.problemReporter().illegalVoidExpression(this.expression);
break;
case T_null :
this.scope.problemReporter().invalidNullToSynchronize(this.expression);
break;
}
//continue even on errors in order to have the TC done into the statements
this.synchroVariable = new LocalVariableBinding(SecretLocalDeclarationName, type, ClassFileConstants.AccDefault, false);
this.scope.addLocalVariable(this.synchroVariable);
this.synchroVariable.setConstant(Constant.NotAConstant); // not inlinable
this.expression.computeConversion(this.scope, type, type);
}
this.block.resolveUsing(this.scope);
}
@Override
public StringBuffer printStatement(int indent, StringBuffer output) {
printIndent(indent, output);
output.append("synchronized ("); //$NON-NLS-1$
this.expression.printExpression(0, output).append(')');
output.append('\n');
return this.block.printStatement(indent + 1, output);
}
@Override
public void traverse(ASTVisitor visitor, BlockScope blockScope) {
if (visitor.visit(this, blockScope)) {
this.expression.traverse(visitor, this.scope);
this.block.traverse(visitor, this.scope);
}
visitor.endVisit(this, blockScope);
}
@Override
public boolean doesNotCompleteNormally() {
return this.block.doesNotCompleteNormally();
}
@Override
public boolean completesByContinue() {
return this.block.completesByContinue();
}
}
|
gpl-3.0
|
lveci/nest
|
beam/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/layermanager/layersrc/wms/WmsLayerType.java
|
10444
|
/*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.beam.visat.toolviews.layermanager.layersrc.wms;
import com.bc.ceres.binding.*;
import com.bc.ceres.binding.dom.DomConverter;
import com.bc.ceres.binding.dom.DomElement;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.LayerTypeRegistry;
import com.bc.ceres.glayer.annotations.LayerTypeMetadata;
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.glevel.MultiLevelSource;
import com.bc.ceres.glevel.support.DefaultMultiLevelModel;
import com.bc.ceres.glevel.support.DefaultMultiLevelSource;
import org.esa.beam.framework.datamodel.RasterDataNode;
import org.esa.beam.jai.ImageManager;
import org.geotools.data.ows.CRSEnvelope;
import org.geotools.data.ows.StyleImpl;
import org.geotools.data.wms.WebMapServer;
import org.geotools.data.wms.request.GetMapRequest;
import org.geotools.data.wms.response.GetMapResponse;
import org.geotools.ows.ServiceException;
import javax.imageio.ImageIO;
import javax.media.jai.PlanarImage;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
/**
* Layer type for layer that displays images coming from an OGC WMS.
*
* @author Marco Peters
* @version $ Revision $ Date $
* @since BEAM 4.6
*/
@LayerTypeMetadata(name = "WmsLayerType",
aliasNames = {"org.esa.beam.visat.toolviews.layermanager.layersrc.wms.WmsLayerType"})
public class WmsLayerType extends ImageLayer.Type {
public static final String PROPERTY_NAME_RASTER = "raster";
public static final String PROPERTY_NAME_URL = "serverUrl";
public static final String PROPERTY_NAME_LAYER_INDEX = "layerIndex";
public static final String PROPERTY_NAME_CRS_ENVELOPE = "crsEnvelope";
public static final String PROPERTY_NAME_STYLE_NAME = "styleName";
public static final String PROPERTY_NAME_IMAGE_SIZE = "imageSize";
@Override
public Layer createLayer(LayerContext ctx, PropertySet configuration) {
final WebMapServer mapServer;
try {
mapServer = getWmsServer(configuration);
} catch (Exception e) {
final String message = String.format("Not able to access Web Mapping Server: %s",
configuration.getValue(WmsLayerType.PROPERTY_NAME_URL));
throw new RuntimeException(message, e);
}
final int layerIndex = (Integer) configuration.getValue(WmsLayerType.PROPERTY_NAME_LAYER_INDEX);
final org.geotools.data.ows.Layer wmsLayer = getLayer(mapServer, layerIndex);
final MultiLevelSource multiLevelSource = createMultiLevelSource(configuration, mapServer, wmsLayer);
final ImageLayer.Type imageLayerType = LayerTypeRegistry.getLayerType(ImageLayer.Type.class);
final PropertySet config = imageLayerType.createLayerConfig(ctx);
config.setValue(ImageLayer.PROPERTY_NAME_MULTI_LEVEL_SOURCE, multiLevelSource);
config.setValue(ImageLayer.PROPERTY_NAME_BORDER_SHOWN, false);
final ImageLayer wmsImageLayer = new ImageLayer(this, multiLevelSource, config);
wmsImageLayer.setName(wmsLayer.getName());
return wmsImageLayer;
}
@Override
public PropertySet createLayerConfig(LayerContext ctx) {
final PropertyContainer template = new PropertyContainer();
template.addProperty(Property.create(PROPERTY_NAME_RASTER, RasterDataNode.class));
template.addProperty(Property.create(PROPERTY_NAME_URL, URL.class));
template.addProperty(Property.create(PROPERTY_NAME_LAYER_INDEX, Integer.class));
template.addProperty(Property.create(PROPERTY_NAME_STYLE_NAME, String.class));
template.addProperty(Property.create(PROPERTY_NAME_IMAGE_SIZE, Dimension.class));
template.addProperty(Property.create(PROPERTY_NAME_CRS_ENVELOPE, CRSEnvelope.class));
template.getDescriptor(PROPERTY_NAME_CRS_ENVELOPE).setDomConverter(new CRSEnvelopeDomConverter());
return template;
}
@SuppressWarnings({"unchecked"})
private static DefaultMultiLevelSource createMultiLevelSource(PropertySet configuration,
WebMapServer wmsServer,
org.geotools.data.ows.Layer layer) {
DefaultMultiLevelSource multiLevelSource;
final String styleName = (String) configuration.getValue(WmsLayerType.PROPERTY_NAME_STYLE_NAME);
final Dimension size = (Dimension) configuration.getValue(WmsLayerType.PROPERTY_NAME_IMAGE_SIZE);
try {
List<StyleImpl> styleList = layer.getStyles();
StyleImpl style = null;
if (!styleList.isEmpty()) {
style = styleList.get(0);
for (StyleImpl currentstyle : styleList) {
if (currentstyle.getName().equals(styleName)) {
style = currentstyle;
}
}
}
CRSEnvelope crsEnvelope = (CRSEnvelope) configuration.getValue(WmsLayerType.PROPERTY_NAME_CRS_ENVELOPE);
GetMapRequest mapRequest = wmsServer.createGetMapRequest();
mapRequest.addLayer(layer, style);
mapRequest.setTransparent(true);
mapRequest.setDimensions(size.width, size.height);
mapRequest.setSRS(crsEnvelope.getEPSGCode()); // e.g. "EPSG:4326" = Geographic CRS
mapRequest.setBBox(crsEnvelope);
mapRequest.setFormat("image/png");
final PlanarImage image = PlanarImage.wrapRenderedImage(downloadWmsImage(mapRequest, wmsServer));
RasterDataNode raster = (RasterDataNode) configuration.getValue(WmsLayerType.PROPERTY_NAME_RASTER);
final int sceneWidth = raster.getSceneRasterWidth();
final int sceneHeight = raster.getSceneRasterHeight();
AffineTransform i2mTransform = ImageManager.getImageToModelTransform(raster.getGeoCoding());
i2mTransform.scale((double) sceneWidth / image.getWidth(), (double) sceneHeight / image.getHeight());
final Rectangle2D bounds = DefaultMultiLevelModel.getModelBounds(i2mTransform, image);
final DefaultMultiLevelModel multiLevelModel = new DefaultMultiLevelModel(1, i2mTransform, bounds);
multiLevelSource = new DefaultMultiLevelSource(image, multiLevelModel);
} catch (Exception e) {
throw new IllegalStateException(String.format("Failed to access WMS: %s", configuration.getValue(
WmsLayerType.PROPERTY_NAME_URL)), e);
}
return multiLevelSource;
}
private static org.geotools.data.ows.Layer getLayer(WebMapServer server, int layerIndex) {
return server.getCapabilities().getLayerList().get(layerIndex);
}
private static WebMapServer getWmsServer(PropertySet configuration) throws IOException, ServiceException {
return new WebMapServer((URL) configuration.getValue(WmsLayerType.PROPERTY_NAME_URL));
}
private static BufferedImage downloadWmsImage(GetMapRequest mapRequest, WebMapServer wms) throws IOException,
ServiceException {
GetMapResponse mapResponse = wms.issueRequest(mapRequest);
InputStream inputStream = mapResponse.getInputStream();
try {
return ImageIO.read(inputStream);
} finally {
inputStream.close();
}
}
private static class CRSEnvelopeDomConverter implements DomConverter {
private static final String SRS_NAME = "srsName";
private static final String MIN_X = "minX";
private static final String MIN_Y = "minY";
private static final String MAX_X = "maxX";
private static final String MAX_Y = "maxY";
@Override
public Class<?> getValueType() {
return CRSEnvelope.class;
}
@Override
public Object convertDomToValue(DomElement parentElement, Object value) throws ConversionException,
ValidationException {
try {
String srsName = parentElement.getChild(SRS_NAME).getValue();
double minX = Double.parseDouble(parentElement.getChild(MIN_X).getValue());
double minY = Double.parseDouble(parentElement.getChild(MIN_Y).getValue());
double maxX = Double.parseDouble(parentElement.getChild(MAX_X).getValue());
double maxY = Double.parseDouble(parentElement.getChild(MAX_Y).getValue());
value = new CRSEnvelope(srsName, minX, minY, maxX, maxY);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
return value;
}
@Override
public void convertValueToDom(Object value, DomElement parentElement) throws ConversionException {
CRSEnvelope crsEnvelope = (CRSEnvelope) value;
DomElement srsName = parentElement.createChild(SRS_NAME);
srsName.setValue(crsEnvelope.getSRSName());
DomElement minX = parentElement.createChild(MIN_X);
minX.setValue(Double.toString(crsEnvelope.getMinX()));
DomElement minY = parentElement.createChild(MIN_Y);
minY.setValue(Double.toString(crsEnvelope.getMinY()));
DomElement maxX = parentElement.createChild(MAX_X);
maxX.setValue(Double.toString(crsEnvelope.getMaxX()));
DomElement maxY = parentElement.createChild(MAX_Y);
maxY.setValue(Double.toString(crsEnvelope.getMaxY()));
}
}
}
|
gpl-3.0
|
Nuke928/NSPkgMgr
|
NSPkgMgr/CommandSync.cs
|
1350
|
/*
===============================================================================
NSPkgMgr
Copyright (C) 2014 Gian Sass
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
===============================================================================
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSPkgMgr
{
/// <summary>
/// Command for updating the package list
/// </summary>
class CommandSync : Command
{
public CommandSync()
{
Name = "sync";
}
public override void Execute()
{
PackageManager.UpdatePackageList();
base.Execute();
}
}
}
|
gpl-3.0
|
grfraser/codebuddies
|
client/templates/status/update-status.js
|
4528
|
//Initialize character counter value
var workingCounterValue = 140;
var learnedCounterValue = 140;
var maxChars = 140;
Template.updateStatus.helpers({
isWorking: function(type) {
return type == 'working';
},
characterCount: workingCounterValue
});
Template.updateStatus.helpers({
hasLearned: function(type) {
return type == 'learned';
},
learnedCharacterCount: learnedCounterValue
});
Template.updateStatus.events({
//Track text for character counting
'keyup #working-text': function(event) {
//Check value and if 140 characters have been typed, the user can't type anymore
var currentLength = $("#working-text").val().length;
workingCounterValue = maxChars - currentLength;
//console.log(workingCounterValue);
$('.charactersLeft').text(workingCounterValue);
},
'keyup #learned-text': function(event) {
//Check value and if 140 characters have been typed, the user can't type anymore
var currentLength = $("#learned-text").val().length;
learnedCounterValue = maxChars - currentLength;
$('.learnedCharactersLeft').text(learnedCounterValue);
},
//3 Buttons
'click #update-working-btn': function(event) {
var currentStatus = $('#working-text').val();
if ($.trim(currentStatus) == '') {
$('#topic').focus();
sweetAlert({
title: TAPi18n.__("Working can't be empty"),
confirmButtonText: TAPi18n.__("ok"),
type: 'error'
});
return;
}
Meteor.call('setUserStatus', currentStatus, function(error, result) {});
$('#working-text').val('');
$('.charactersLeft').text(140);
},
'click #update-learned-btn': function(event) {
if (!Meteor.userId()) {
sweetAlert({
imageUrl: '/images/slack-signin-example.jpg',
imageSize: '140x120',
showCancelButton: true,
title: TAPi18n.__("you_are_almost_there"),
html: TAPi18n.__("continue_popup_text"),
confirmButtonText: TAPi18n.__("sign_in_with_slack"),
cancelButtonText: TAPi18n.__("not_now")
},
function(){
var options = {
requestPermissions: ['identify', 'users:read']
};
Meteor.loginWithSlack(options);
});
} else {
var learningStatus = $('#learned-text').val();
if ($.trim(learningStatus) == '') {
$('#topic').focus();
sweetAlert({
title: TAPi18n.__("Accomplishment can't be empty"),
confirmButtonText: TAPi18n.__("ok"),
type: 'error'
});
return;
}
var data = {
user_id: Meteor.userId(),
username: Meteor.user().username,
title: learningStatus,
hangout_id: 'homepage'
}
Meteor.call("addLearning", data, function(error, result) {});
$('#learned-text').val('');
$('.learnedCharactersLeft').text(140);
}
},
'click .btn-hangout-status': function(event) {
var currentType = $(event.currentTarget).attr('data-type');
if (currentType !== undefined)
Meteor.call("setHangoutStatus", currentType, function(error, result) {});
},
'click .btn-hangout-status': function(event) {
var currentType = $(event.currentTarget).attr('data-type');
if (currentType !== undefined) {
Meteor.call("setHangoutStatus", currentType, function(error, result) {});
var bgColor;
switch (currentType) {
case "silent":
bgColor = "#c9302c";
break;
case "teaching":
bgColor = "#ec971f";
break;
case "collaboration":
bgColor = "#449d44";
break;
default: break;
}
$(".btn-hangout-status").each(function(index) {
$(this).css("background-color","");
});
$(event.currentTarget).css("background-color",bgColor);
}
}
});
Template.updateStatus.rendered = function() {
$('[data-toggle=tooltip]').tooltip()
};
|
gpl-3.0
|
zendawg/OpenEyes
|
protected/migrations/m120307_172115_remove_site_element_type_and_possible_element_type_tables.php
|
256
|
<?php
class m120307_172115_remove_site_element_type_and_possible_element_type_tables extends CDbMigration
{
public function up()
{
$this->dropTable('site_element_type');
$this->dropTable('possible_element_type');
}
public function down()
{
}
}
|
gpl-3.0
|
mganeva/mantid
|
qt/python/mantidqt/widgets/workspacedisplay/test/test_data_copier.py
|
7071
|
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
# This file is part of the mantid workbench.
from unittest import TestCase
from mantid.py3compat.mock import Mock, patch
from qtpy.QtWidgets import QMessageBox
from mantidqt.widgets.workspacedisplay.data_copier import DataCopier
from mantidqt.utils.testing.mocks.mock_qt import MockQClipboard, MockQModelIndex, \
MockQSelectionModel, MockQStatusBar, MockQTableView
from mantidqt.widgets.workspacedisplay.user_notifier import UserNotifier
from mantidqt.widgets.workspacedisplay.table.view import TableWorkspaceDisplayView
class DataCopierTest(TestCase):
show_mouse_toast_package = 'mantidqt.widgets.workspacedisplay.user_notifier.UserNotifier.show_mouse_toast'
copy_to_clipboard_package = 'mantidqt.widgets.workspacedisplay.data_copier.DataCopier.copy_to_clipboard'
def assertNotCalled(self, mock):
self.assertEqual(0, mock.call_count)
def setUp(self):
self.mock_status_bar = MockQStatusBar()
self.mock_clipboard = MockQClipboard()
self.mock_clipboard.setText = Mock()
self.data_copier = DataCopier(self.mock_status_bar)
mock_selection_model = MockQSelectionModel(has_selection=True)
mock_selection_model.selectedRows = Mock(
return_value=[MockQModelIndex(1, 1), MockQModelIndex(2, 2), MockQModelIndex(3, 3)])
mock_selection_model.selectedColumns = Mock(
return_value=[MockQModelIndex(1, 1), MockQModelIndex(2, 2), MockQModelIndex(3, 3)])
self.table = Mock(spec=TableWorkspaceDisplayView)
self.table.mock_selection_model = mock_selection_model
@patch(show_mouse_toast_package)
@patch(copy_to_clipboard_package)
def test_action_copy_spectrum_values(self, mock_copy, mock_show_mouse_toast):
mock_table = MockQTableView()
# two rows are selected in different positions
mock_indexes = [MockQModelIndex(0, 1), MockQModelIndex(3, 1)]
mock_table.mock_selection_model.selectedRows = Mock(return_value=mock_indexes)
mock_read = Mock(return_value=[43, 99])
expected_string = "43\t99\n43\t99"
self.data_copier.copy_spectrum_values(mock_table, mock_read)
mock_table.selectionModel.assert_called_once_with()
mock_table.mock_selection_model.hasSelection.assert_called_once_with()
mock_copy.assert_called_once_with(expected_string)
mock_show_mouse_toast.assert_called_once_with(UserNotifier.COPY_SUCCESSFUL_MESSAGE)
@patch(show_mouse_toast_package)
@patch(copy_to_clipboard_package)
def test_action_copy_spectrum_values_no_selection(self, mock_copy,
mock_show_mouse_toast):
mock_table = MockQTableView()
mock_table.mock_selection_model.hasSelection = Mock(return_value=False)
mock_table.mock_selection_model.selectedRows = Mock()
self.data_copier.copy_spectrum_values(mock_table, ws_read=None)
mock_table.selectionModel.assert_called_once_with()
mock_table.mock_selection_model.hasSelection.assert_called_once_with()
# the action should never look for rows if there is no selection
self.assertNotCalled(mock_table.mock_selection_model.selectedRows)
self.assertNotCalled(mock_copy)
mock_show_mouse_toast.assert_called_once_with(UserNotifier.NO_SELECTION_MESSAGE)
@patch(show_mouse_toast_package)
@patch(copy_to_clipboard_package)
def test_action_copy_bin_values(self, mock_copy, mock_show_mouse_toast):
mock_table = MockQTableView()
# two columns are selected at different positions
mock_indexes = [MockQModelIndex(0, 0), MockQModelIndex(0, 3)]
mock_table.mock_selection_model.selectedColumns = Mock(return_value=mock_indexes)
# change the mock ws to have 3 histograms
num_hist = 3
mock_read = Mock(return_value=[83, 11, 33, 70])
expected_string = "83\t70\n83\t70\n83\t70"
self.data_copier.copy_bin_values(mock_table, mock_read, num_hist)
mock_table.selectionModel.assert_called_once_with()
mock_table.mock_selection_model.hasSelection.assert_called_once_with()
mock_copy.assert_called_once_with(expected_string)
mock_show_mouse_toast.assert_called_once_with(UserNotifier.COPY_SUCCESSFUL_MESSAGE)
@patch(show_mouse_toast_package)
@patch(copy_to_clipboard_package)
def test_action_copy_bin_values_no_selection(self, mock_copy, mock_show_mouse_toast):
mock_table = MockQTableView()
mock_table.mock_selection_model.hasSelection = Mock(return_value=False)
mock_table.mock_selection_model.selectedColumns = Mock()
self.data_copier.copy_bin_values(mock_table, None, None)
mock_table.selectionModel.assert_called_once_with()
mock_table.mock_selection_model.hasSelection.assert_called_once_with()
# the action should never look for rows if there is no selection
self.assertNotCalled(mock_table.mock_selection_model.selectedColumns)
self.assertNotCalled(mock_copy)
mock_show_mouse_toast.assert_called_once_with(UserNotifier.NO_SELECTION_MESSAGE)
@patch(show_mouse_toast_package)
@patch(copy_to_clipboard_package)
def test_copy_cells_no_selection(self, mock_copy, mock_show_mouse_toast):
mock_table = MockQTableView()
mock_table.mock_selection_model.hasSelection = Mock(return_value=False)
self.data_copier.copy_cells(mock_table)
mock_table.selectionModel.assert_called_once_with()
mock_table.mock_selection_model.hasSelection.assert_called_once_with()
mock_show_mouse_toast.assert_called_once_with(UserNotifier.NO_SELECTION_MESSAGE)
self.assertNotCalled(mock_copy)
@patch(show_mouse_toast_package)
@patch(copy_to_clipboard_package)
def test_copy_cells(self, mock_copy, mock_show_mouse_toast):
mock_table = MockQTableView()
# two columns are selected at different positions
mock_index = MockQModelIndex(None, None)
mock_table.mock_selection_model.currentIndex = Mock(return_value=mock_index)
self.data_copier.copy_cells(mock_table)
mock_table.selectionModel.assert_called_once_with()
self.assertEqual(1, mock_copy.call_count)
self.assertEqual(9, mock_index.sibling.call_count)
mock_show_mouse_toast.assert_called_once_with(UserNotifier.COPY_SUCCESSFUL_MESSAGE)
@patch('qtpy.QtWidgets.QMessageBox.question', return_value=QMessageBox.Yes)
def test_ask_confirmation(self, mock_question):
message = "Hello"
title = "Title"
reply = self.data_copier.ask_confirmation(message, title)
mock_question.assert_called_once_with(self.data_copier, title, message, QMessageBox.Yes, QMessageBox.No)
self.assertEqual(reply, True)
|
gpl-3.0
|
INBio/NeoPortal
|
neoportal-web/src/main/webapp/resources/js/groupNav.js
|
955
|
/*
* groupNav.js
* Author: avargas
* Creation date: 20120806
*
* Description: behavior for groupNav page
*
*/
var groupNavId;
var itemsPerPage = 10;
var speciesUrl = "/api/groupNav/species";
$("document").ready(function(){
//prepare submenus
$("li.gn-node:not(.current) > ul").hide();
$("li.gn-node.current").parent().show();
//add click function
$("li.gn-node > a").click(function(){
//hide current and remove class
$("li.gn-node.current ul").hide();
$("li.gn-node.current").removeClass("current");
//show selected and set current class
$(this).siblings("ul").show();
$(this).parent().addClass("current");
});
});
function loadGroupNavSpecies(){
groupNavId = $("li.current a").attr('id');
groupNavId = groupNavId.split("_");
groupNavId = groupNavId[1];
//get data
$.get(speciesUrl + "?gni=" + groupNavId, function(){
//draw pagination info if necessary
});
}
function getPageData(page){
}
|
gpl-3.0
|
killbug2004/PREF
|
views/disassemblerview/disassemblerwidget/disassemblerhighlighter.cpp
|
4062
|
#include "disassemblerhighlighter.h"
DisassemblerHighlighter::DisassemblerHighlighter(QTextDocument *parent, Block* block): QSyntaxHighlighter(parent), _block(block)
{
this->generateHighlighters();
}
void DisassemblerHighlighter::generateHighlighters()
{
this->_segmentformat.setFontFamily("Monospace");
this->_segmentformat.setFontStyleHint(QFont::TypeWriter);
this->_segmentformat.setForeground(Qt::darkGreen);
this->_segmentkwformat.setFontFamily("Monospace");
this->_segmentkwformat.setFontStyleHint(QFont::TypeWriter);
this->_segmentkwformat.setFontWeight(QFont::Bold);
this->_segmentkwformat.setForeground(Qt::darkGreen);
this->_functionformat.setFontFamily("Monospace");
this->_functionformat.setFontStyleHint(QFont::TypeWriter);
this->_functionformat.setFontWeight(QFont::Bold);
this->_functionformat.setForeground(Qt::blue);
this->_functionnameformat.setFontFamily("Monospace");
this->_functionnameformat.setFontStyleHint(QFont::TypeWriter);
this->_functionnameformat.setForeground(Qt::darkRed);
this->_hexdigitsformat.setFontFamily("Monospace");
this->_hexdigitsformat.setFontStyleHint(QFont::TypeWriter);
this->_hexdigitsformat.setForeground(Qt::darkBlue);
this->_commentformat.setFontFamily("Monospace");
this->_commentformat.setFontStyleHint(QFont::TypeWriter);
this->_commentformat.setFontItalic(true);
this->_commentformat.setForeground(Qt::darkGreen);
this->_jumplabelformat.setFontFamily("Monospace");
this->_jumplabelformat.setFontStyleHint(QFont::TypeWriter);
this->_jumplabelformat.setForeground(Qt::darkGray);
}
void DisassemblerHighlighter::highlight(const QString &text, const QString& stringregex, const QTextCharFormat& charformat)
{
QRegExp regex(stringregex);
int idx = text.indexOf(regex);
while(idx >= 0)
{
int len = regex.matchedLength();
this->setFormat(idx, len, charformat);
idx = text.indexOf(regex, idx + len);
}
}
void DisassemblerHighlighter::highlightSegment(const QString &text)
{
QRegExp regex("segment .+$");
int idx = text.indexOf(regex);
while(idx >= 0)
{
int len = regex.matchedLength();
this->setFormat(idx, 7, this->_segmentkwformat);
this->setFormat(idx + 7, len - 7, this->_segmentformat);
idx = text.indexOf(regex, idx + len);
}
}
void DisassemblerHighlighter::highlightFunction(const QString &text)
{
QRegExp regex("[a-z]*[ ]*function [^.]+\\([^.]*\\)[^.]*$");
int idx = text.indexOf(regex);
while(idx >= 0)
{
int len = regex.matchedLength();
this->setFormat(idx, len, this->_functionformat);
idx = text.indexOf(regex, idx + len);
}
regex = QRegExp("[^. ]+\\([^.]*\\)");
idx = text.indexOf(regex);
while(idx >= 0)
{
int len = regex.matchedLength();
this->setFormat(idx, len, this->_functionnameformat);
idx = text.indexOf(regex, idx + len);
}
}
void DisassemblerHighlighter::highlightComment(const QString &text)
{
QRegExp regex("#[^#]*$");
int idx = text.indexOf(regex);
while(idx >= 0)
{
int len = regex.matchedLength();
this->setFormat(idx, len, this->_commentformat);
idx = text.indexOf(regex, idx + len);
}
}
void DisassemblerHighlighter::highlightLabel(const QString &text)
{
QRegExp regex("[a-zA-Z_]+[a-zA-Z0-9]*_[a-zA-Z0-9]+[\\:]*");
int idx = text.indexOf(regex);
if(idx == -1)
return;
this->setFormat(idx, regex.matchedLength(), this->_jumplabelformat);
}
void DisassemblerHighlighter::highlightBlock(const QString &text)
{
if(this->_block->blockType() == Block::SegmentBlock)
this->highlightSegment(text);
else if(this->_block->blockType() == Block::FunctionBlock)
this->highlightFunction(text);
else if(this->_block->blockType() == Block::LabelBlock)
this->highlightLabel(text);
this->highlightComment(text);
this->highlight(text, "\\b[0-9a-fA-F]+h\\b", this->_hexdigitsformat);
}
|
gpl-3.0
|
cleoquintiliano/controls
|
src/main/java/com/cqi/controls/converter/GrupoConverter.java
|
1226
|
package com.cqi.controls.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.cqi.controls.model.Grupo;
import com.cqi.controls.repository.Grupos;
import com.cqi.controls.util.cdi.CDIServiceLocator;
/**
* Um converter é uma classe que implementa a interface javax.faces.convert.Converter,
* implementando os dois métodos desta interface, o getAsObject e o getAsString.
* @author cqfb
*/
@FacesConverter(forClass = Grupo.class)
public class GrupoConverter implements Converter {
//@Inject (não funciona em conversores para essa versão)
private Grupos grupos;
public GrupoConverter() {
grupos = CDIServiceLocator.getBean(Grupos.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
Grupo retorno = null;
if (value != null) {
Long id = new Long(value);
retorno = grupos.porId(id);
}
return retorno;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value != null) {
return ((Grupo) value).getId().toString();
}
return "";
}
}
|
gpl-3.0
|
sgs-us/talfer
|
src/CStage_FluidSimulationNS.hpp
|
21597
|
/*
* CStage_ImageInput.hpp
*
* Created on: Jul 5, 2013
* Author: Martin Schreiber <martin.schreiber@in.tum.de>
*
* There's already an existing file named CStage_FluidSimulationLBM.hpp
* with a skeleton for the LBM simulation. Please consider using this as
* your NS Skeleton. You get a flag array from the image processing as
* an input which can frequently change. The output should be a velocity
* field based on the simulation involving the input flag array.
*/
#ifndef CSTAGE_FLUIDSIMULATION_NS_HPP_
#define CSTAGE_FLUIDSIMULATION_NS_HPP_
#include "CParameters.hpp"
#include "CPipelineStage.hpp"
#include "SDL/SDL_image.h"
#include "CDataArray2D.hpp"
#include "CDataDrawingInformation.hpp"
#include <math.h>
#include <iostream>
#include <cassert>
#ifdef EPETRA_MPI
#include "mpi.h"
#include "Epetra_MpiComm.h"
#else
#include "Epetra_SerialComm.h"
#endif
#include "Epetra_ConfigDefs.h"
#include "Epetra_CrsMatrix.h"
#include "Epetra_MsrMatrix.h"
#include "Epetra_VbrMatrix.h"
#include "Epetra_Vector.h"
#include "Epetra_LinearProblem.h"
#include "Epetra_Map.h"
#include "AztecOO.h"
enum Direction {
CENTER = 16,
EAST = 8,
WEST = 4,
SOUTH = 2,
NORTH = 1,
NORTHEAST = 9,
SOUTHEAST = 10,
SOUTHWEST = 6,
NORTHWEST = 5,
INFLOW = 32,
OUTFLOW = 64
};
enum Axis {
X, Y
};
/**
* class providing static image input
*
* the image is send to the pipeline during each main loop iteration
*/
class CStage_FluidSimulationNS: public CPipelineStage {
private:
const float density = 1000;
const float viscosity = 1;
const float gravity[2] = { 0.0, 0.0 };
const float dx = 1e-1;
const float dy = 1e-1;
const float max_dt = 5e-4;
float dt;
const float inflowPressure = 5e3;
const float fluidPressure = 1e2;
const float outflowPressure = 1e1;
bool initialized;
CDataArray2D<char, 1> type;
CDataArray2D<float, 1> pressure;
CDataArray2D<float, 2> velocity;
CDataArray2D<float, 2> velocity_tmp;
public:
CDataArray2D<unsigned char, 1> input_cDataArray2D;
CParameters &cParameters;
CDataArray2D<float, 2>& output_cDataArray2D_f2;
/**
* constructor
*/
CStage_FluidSimulationNS(CParameters &i_cParameters) :
CPipelineStage("FluidSimulationNS"), dt(max_dt), initialized(false), cParameters(
i_cParameters), output_cDataArray2D_f2(velocity) {
}
public:
/**
* manually triggered pushing of next image to the pipeline
*/
void pipeline_push() {
if (cParameters.stage_fluidsimulation_visualize_flagfield)
CPipelineStage::pipeline_push(
(CPipelinePacket&) input_cDataArray2D);
CPipelineStage::pipeline_push(
(CPipelinePacket&) output_cDataArray2D_f2);
}
// own calculators / getters / setter
float& getPressure(int i, int j, Direction direction) {
switch (direction) {
case CENTER:
return pressure.getRef(normalize(i, X), normalize(j, Y));
break;
case EAST:
return pressure.getRef(normalize(i + 1, X), normalize(j, Y));
break;
case WEST:
return pressure.getRef(normalize(i - 1, X), normalize(j, Y));
break;
case SOUTH:
return pressure.getRef(normalize(i, X), normalize(j - 1, Y));
break;
case NORTH:
return pressure.getRef(normalize(i, X), normalize(j + 1, Y));
break;
case NORTHEAST:
return pressure.getRef(normalize(i + 1, X), normalize(j + 1, Y));
break;
case SOUTHEAST:
return pressure.getRef(normalize(i + 1, X), normalize(j - 1, Y));
break;
case SOUTHWEST:
return pressure.getRef(normalize(i - 1, X), normalize(j - 1, Y));
break;
case NORTHWEST:
return pressure.getRef(normalize(i - 1, X), normalize(j + 1, Y));
break;
default:
assert(false);
break;
}
return pressure.getRef(i, j);
}
float& getVelocity(int i, int j, Direction direction, Axis axis) {
return getVelocity(i, j, direction, axis, velocity);
}
float& getVelocity(int i, int j, Direction direction, Axis axis,
CDataArray2D<float, 2>& source) {
switch (direction) {
case CENTER:
return source.getRef(normalize(i, X), normalize(j, Y), axis);
break;
case EAST:
return source.getRef(normalize(i + 1, X), normalize(j, Y), axis);
break;
case WEST:
return source.getRef(normalize(i - 1, X), normalize(j, Y), axis);
break;
case SOUTH:
return source.getRef(normalize(i, X), normalize(j - 1, Y), axis);
break;
case NORTH:
return source.getRef(normalize(i, X), normalize(j + 1, Y), axis);
break;
case NORTHEAST:
return source.getRef(normalize(i + 1, X), normalize(j + 1, Y), axis);
break;
case SOUTHEAST:
return source.getRef(normalize(i + 1, X), normalize(j - 1, Y), axis);
break;
case SOUTHWEST:
return source.getRef(normalize(i - 1, X), normalize(j - 1, Y), axis);
break;
case NORTHWEST:
return source.getRef(normalize(i - 1, X), normalize(j + 1, Y), axis);
break;
default:
assert(false);
break;
}
return source.getRef(i, j, axis);
}
int getLinear(int i, int j, Direction direction) {
switch (direction) {
case CENTER:
break;
case EAST:
i += 1;
break;
case WEST:
i -= 1;
break;
case SOUTH:
j -= 1;
break;
case NORTH:
j += 1;
break;
case NORTHEAST:
i += 1;
j += 1;
break;
case SOUTHEAST:
j -= 1;
i += 1;
break;
case SOUTHWEST:
j -= 1;
i -= 1;
break;
case NORTHWEST:
j += 1;
i -= 1;
break;
default:
assert(false);
break;
}
return normalize(j, Y) * input_cDataArray2D.width + normalize(i, X);
}
float diffusive_x(int i, int j) {
// diffusive term in x-dir
float d2ud2x = (getVelocity(i, j, EAST, X)
- 2 * getVelocity(i, j, CENTER, X) + getVelocity(i, j, WEST, X))
/ (dx * dx);
float d2ud2y =
(getVelocity(i, j, NORTH, X) - 2 * getVelocity(i, j, CENTER, X)
+ getVelocity(i, j, SOUTH, X)) / (dy * dy);
return viscosity * (d2ud2x + d2ud2y);
}
float diffusive_y(int i, int j) {
// diffusive term in y-dir
float d2vd2x = (getVelocity(i, j, EAST, Y)
- 2 * getVelocity(i, j, CENTER, Y) + getVelocity(i, j, WEST, Y))
/ (dx * dx);
float d2vd2y =
(getVelocity(i, j, NORTH, Y) - 2 * getVelocity(i, j, CENTER, Y)
+ getVelocity(i, j, SOUTH, Y)) / (dy * dy);
return viscosity * (d2vd2x + d2vd2y);
}
float pressure_x(int i, int j) {
//pressure term in x
float dpdx = (getPressure(i, j, EAST) - getPressure(i, j, CENTER)) / dx;
return -(1 / density) * dpdx;
}
float pressure_y(int i, int j) {
//pressure term in y
float dpdy = (getPressure(i, j, NORTH) - getPressure(i, j, CENTER))
/ dy;
return -(1 / density) * dpdy;
}
float gravity_x() {
return gravity[X];
}
float gravity_y() {
return gravity[Y];
}
float pow(float x) {
return x * x;
}
float convective_x(int i, int j) {
double du2dx = (pow(
(getVelocity(i, j, EAST, X) + getVelocity(i, j, CENTER, X)))
- pow(
(getVelocity(i, j, CENTER, X)
+ getVelocity(i, j, WEST, X)))) / (4 * dx);
double duvdy =
((getVelocity(i, j, CENTER, Y) + getVelocity(i, j, EAST, Y))
* (getVelocity(i, j, CENTER, X)
+ getVelocity(i, j, NORTH, X))
- (getVelocity(i, j, SOUTH, Y)
+ getVelocity(i, j, SOUTHEAST, Y))
* (getVelocity(i, j, SOUTH, X)
+ getVelocity(i, j, CENTER, X)))
/ (4 * dy);
return du2dx + duvdy;
}
float convective_y(int i, int j) {
double dv2dy = (pow(
getVelocity(i, j, CENTER, Y) + getVelocity(i, j, NORTH, Y))
- pow(
getVelocity(i, j, SOUTH, Y)
+ getVelocity(i, j, CENTER, Y))) / (4 * dy);
double duvdx = ((getVelocity(i, j, CENTER, X)
+ getVelocity(i, j, NORTH, X))
* (getVelocity(i, j, CENTER, Y) + getVelocity(i, j, EAST, Y))
- (getVelocity(i, j, WEST, X) + getVelocity(i, j, NORTHWEST, X))
* (getVelocity(i, j, WEST, Y)
+ getVelocity(i, j, CENTER, Y))) / (4 * dx);
return dv2dy + duvdx;
}
float get_maxvelocity() {
//int max_i_x, max_j_x, max_i_y, max_j_y;
float max = abs(getVelocity(0, 0, CENTER, X));
for (int j = 0; j < velocity.height; j++) {
for (int i = 0; i < velocity.width; i++) {
if (abs(getVelocity(i, j, CENTER, X)) > max) {
max = abs(getVelocity(i, j, CENTER, X));
//max_i_x = i;
//max_j_x = j;
}
if (abs(getVelocity(i, j, CENTER, Y)) > max) {
max = abs(getVelocity(i, j, CENTER, Y));
//max_i_y = i;
//max_j_y = j;
}
}
}
return max;
}
int normalize(int v, Axis axis, bool quadratic) {
int norm;
if (quadratic)
norm = input_cDataArray2D.width * input_cDataArray2D.height;
else if (axis == X)
norm = input_cDataArray2D.width;
else
norm = input_cDataArray2D.height;
if (v < 0)
v += norm;
else if (v >= norm)
v -= norm;
return v;
}
int normalize(int v, Axis axis) {
return normalize(v, axis, false);
}
void simulation_timestep() {
// 0:fluid, 1:obstacle, 2: inflow, 3:outflow
if (!input_cDataArray2D.isValidData())
return;
// initialize
if (!initialized) {
initialized = true;
pressure.resize(input_cDataArray2D.width,
input_cDataArray2D.height);
velocity_tmp.resize(input_cDataArray2D.width,
input_cDataArray2D.height);
velocity.resize(input_cDataArray2D.width,
input_cDataArray2D.height);
type.resize(input_cDataArray2D.width, input_cDataArray2D.height);
for (int j = 0; j < pressure.height; j++) {
for (int i = 0; i < pressure.width; i++) {
getPressure(i, j, CENTER) = fluidPressure;
getVelocity(i, j, CENTER, X) = 0;
getVelocity(i, j, CENTER, Y) = 0;
getVelocity(i, j, CENTER, X, velocity_tmp) = 0;
getVelocity(i, j, CENTER, Y, velocity_tmp) = 0;
type.getRef(i, j) = (input_cDataArray2D.getRef(
normalize(i, X), normalize(j, Y)) != 1) * CENTER
+ (input_cDataArray2D.getRef(normalize(i + 1, X),
normalize(j, Y)) != 1) * EAST
+ (input_cDataArray2D.getRef(normalize(i - 1, X),
normalize(j, Y)) != 1) * WEST
+ (input_cDataArray2D.getRef(normalize(i, X),
normalize(j - 1, Y)) != 1) * SOUTH
+ (input_cDataArray2D.getRef(normalize(i, X),
normalize(j + 1, Y)) != 1) * NORTH
+ (input_cDataArray2D.getRef(normalize(i, X),
normalize(j, Y)) == 2) * INFLOW
+ (input_cDataArray2D.getRef(normalize(i, X),
normalize(j, Y)) == 3) * OUTFLOW;
}
}
} else {
//calculate maximum possible timestep size
dt = (dx < dy ? dx : dy) / (2 * get_maxvelocity()); //TODO
dt = dt > max_dt ? max_dt : dt;
std::cout << dt << endl;
}
//TODO
//type.getRef(5,5) = INFLOW+CENTER+EAST+WEST+NORTH+SOUTH;
//type.getRef(9,9) = OUTFLOW+CENTER+EAST+WEST+NORTH+SOUTH;
// temporary velocities;
for (int j = 0; j < velocity_tmp.height; j++) {
for (int i = 0; i < velocity_tmp.width; i++) {
getVelocity(i, j, CENTER, X, velocity_tmp) = getVelocity(i, j,
CENTER, X)
+ dt
* (-convective_x(i, j) + diffusive_x(i, j)
+ gravity_x());
getVelocity(i, j, CENTER, Y, velocity_tmp) = getVelocity(i, j,
CENTER, Y)
+ dt
* (-convective_y(i, j) + diffusive_y(i, j)
+ gravity_y());
}
}
// initialize structures
#ifdef EPETRA_MPI
// Initialize MPI
MPI_Init(&argc,&argv);
Epetra_MpiComm Comm( MPI_COMM_WORLD );
#else
Epetra_SerialComm Comm;
#endif
int NumMyElements = input_cDataArray2D.width
* input_cDataArray2D.height;
Epetra_Map Map(NumMyElements, NumMyElements, 0, Comm);
Epetra_CrsMatrix A(Copy, Map, 5);
Epetra_Vector x(Map);
Epetra_Vector b(Map);
// populate matrix
double value_A_Y = 1 / (dy * dy);
double value_A_X = 1 / (dx * dx);
double value_A_CENTER = -2 * value_A_Y - 2 * value_A_X;
double value_one = 1;
double value_minusone = -1;
double value_minushalf = -0.5;
for (int j = 0; j < input_cDataArray2D.height; j++) {
for (int i = 0; i < input_cDataArray2D.width; i++) {
int globalRow_CENTER = A.GRID(getLinear(i, j, CENTER));
int globalRow_NORTH = A.GRID(getLinear(i, j, NORTH));
int globalRow_SOUTH = A.GRID(getLinear(i, j, SOUTH));
int globalRow_WEST = A.GRID(getLinear(i, j, WEST));
int globalRow_EAST = A.GRID(getLinear(i, j, EAST));
if ((type.getRef(i, j) & INFLOW) == INFLOW) {
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
b[getLinear(i, j, CENTER)] = inflowPressure;
} else if ((type.getRef(i, j) & OUTFLOW) == OUTFLOW) {
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
b[getLinear(i, j, CENTER)] = outflowPressure;
} else if ((type.getRef(i, j) & CENTER) == CENTER) { //Fluidzelle
A.InsertGlobalValues(globalRow_CENTER, 1, &value_A_CENTER,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1, &value_A_Y,
&globalRow_NORTH);
A.InsertGlobalValues(globalRow_CENTER, 1, &value_A_Y,
&globalRow_SOUTH);
A.InsertGlobalValues(globalRow_CENTER, 1, &value_A_X,
&globalRow_WEST);
A.InsertGlobalValues(globalRow_CENTER, 1, &value_A_X,
&globalRow_EAST);
b[getLinear(i, j, CENTER)] = density / dt
* ((getVelocity(i, j, EAST, X, velocity_tmp)
- getVelocity(i, j, WEST, X, velocity_tmp))
/ (2 * dx)
+ (getVelocity(i, j, NORTH, Y, velocity_tmp)
- getVelocity(i, j, SOUTH, Y,
velocity_tmp)) / (2 * dy));
} else { //Hinderniszelle
switch (type.getRef(i, j)) {
case NORTH: //North
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minusone, &globalRow_NORTH);
b[getLinear(i, j, CENTER)] = 0;
break;
case SOUTH: //South
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minusone, &globalRow_SOUTH);
b[getLinear(i, j, CENTER)] = 0;
break;
case EAST: //East
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minusone, &globalRow_EAST);
b[getLinear(i, j, CENTER)] = 0;
break;
case WEST: //West
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minusone, &globalRow_WEST);
b[getLinear(i, j, CENTER)] = 0;
break;
case NORTHWEST: //Northwest
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_NORTH);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_WEST);
b[getLinear(i, j, CENTER)] = 0;
break;
case NORTHEAST: //Northeast
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_NORTH);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_EAST);
b[getLinear(i, j, CENTER)] = 0;
break;
case SOUTHWEST: //Southwest
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_SOUTH);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_WEST);
b[getLinear(i, j, CENTER)] = 0;
break;
case SOUTHEAST: //Southeast
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_SOUTH);
A.InsertGlobalValues(globalRow_CENTER, 1,
&value_minushalf, &globalRow_EAST);
b[getLinear(i, j, CENTER)] = 0;
break;
case 0: //komplett im Hindernis
A.InsertGlobalValues(globalRow_CENTER, 1, &value_one,
&globalRow_CENTER);
b[getLinear(i, j, CENTER)] = fluidPressure;
break;
}
}
}
}
A.FillComplete();
//A.Print(std::cout);
//b.Print(std::cout);
// run solver
Epetra_LinearProblem Problem(&A, &x, &b);
AztecOO Solver(Problem);
Solver.SetAztecOption(AZ_diagnostics, AZ_none);
Solver.SetAztecOption(AZ_output, AZ_none);
Solver.SetAztecOption(AZ_solver, AZ_gmres);
Solver.SetAztecOption(AZ_precond, AZ_dom_decomp);
//Solver.SetAztecOption(AZ_solver, AZ_gmres);
//Solver.SetAztecOption(AZ_precond, AZ_Jacobi);
Solver.Iterate(10000, 1E-3);
// retrieving solution
for (int j = 0; j < pressure.height; j++) {
for (int i = 0; i < pressure.width; i++) {
getPressure(i, j, CENTER) = x[getLinear(i, j, CENTER)];
}
}
// final velocities
for (int j = 0; j < velocity.height; j++) {
for (int i = 0; i < velocity.width; i++) {
getVelocity(i, j, CENTER, X, velocity) = (getVelocity(i, j,
CENTER, X, velocity_tmp)
- dt / (dx * density)
* (getPressure(i, j, EAST)
- getPressure(i, j, CENTER)));
getVelocity(i, j, CENTER, Y, velocity) = (getVelocity(i, j,
CENTER, Y, velocity_tmp)
- dt / (dy * density)
* (getPressure(i, j, NORTH)
- getPressure(i, j, CENTER)));
}
}
// boundary conditions
for (int j = 0; j < velocity.height; j++) {
for (int i = 0; i < velocity.width; i++) {
// not allowed
if (type.getRef(i, j) <= CENTER
&& ((type.getRef(i, j) & (NORTH + SOUTH))
== (NORTH + SOUTH)
|| (type.getRef(i, j) & (EAST + WEST))
== (EAST + WEST))) {
assert(false);
}
switch (type.getRef(i, j)) {
// not interesting: 1xxxx, 00000
case EAST: //EAST
getVelocity(i, j, CENTER, X) = 0;
getVelocity(i, j, CENTER, Y) = -getVelocity(i, j, EAST, Y);
getVelocity(i, j, WEST, X) = 0;
getVelocity(i, j, SOUTH, Y) = -getVelocity(i, j, SOUTHEAST,
Y);
break;
case WEST: //WEST
getVelocity(i, j, CENTER, X) = 0;
getVelocity(i, j, CENTER, Y) = -getVelocity(i, j, WEST, Y);
getVelocity(i, j, WEST, X) = 0;
getVelocity(i, j, SOUTH, Y) = -getVelocity(i, j, SOUTHWEST,
Y);
break;
case SOUTH: //SOUTH
getVelocity(i, j, CENTER, X) = -getVelocity(i, j, SOUTH, X);
getVelocity(i, j, CENTER, Y) = 0;
getVelocity(i, j, WEST, X) = -getVelocity(i, j, SOUTHWEST,
X);
getVelocity(i, j, SOUTH, Y) = 0;
break;
case NORTH: //NORTH
getVelocity(i, j, CENTER, X) = -getVelocity(i, j, NORTH, X);
getVelocity(i, j, CENTER, Y) = 0;
getVelocity(i, j, WEST, X) = -getVelocity(i, j, NORTHWEST,
X);
getVelocity(i, j, SOUTH, Y) = 0;
break;
case NORTHWEST: //NORTHWEST
getVelocity(i, j, CENTER, X) = -getVelocity(i, j, NORTH, X);
getVelocity(i, j, CENTER, Y) = 0;
getVelocity(i, j, WEST, X) = 0;
getVelocity(i, j, SOUTH, Y) = -getVelocity(i, j, SOUTHWEST,
Y);
break;
case SOUTHEAST: //SOUTHEAST
getVelocity(i, j, CENTER, X) = 0;
getVelocity(i, j, CENTER, Y) = -getVelocity(i, j, EAST, Y);
getVelocity(i, j, WEST, X) = -getVelocity(i, j, SOUTHWEST,
X);
getVelocity(i, j, SOUTH, Y) = 0;
break;
case NORTHEAST: //NORTHEAST
getVelocity(i, j, CENTER, X) = 0;
getVelocity(i, j, CENTER, Y) = 0;
getVelocity(i, j, WEST, X) = -getVelocity(i, j, NORTHWEST,
X);
getVelocity(i, j, SOUTH, Y) = -getVelocity(i, j, SOUTHEAST,
Y);
break;
case SOUTHWEST: //SOUTHWEST
getVelocity(i, j, CENTER, X) = -getVelocity(i, j, SOUTH, X);
getVelocity(i, j, CENTER, Y) = -getVelocity(i, j, WEST, Y);
getVelocity(i, j, WEST, X) = 0;
getVelocity(i, j, SOUTH, Y) = 0;
break;
}
}
}
if (false) {
std::cout << "***** final Types *****" << endl; // TODO
for (int j = 0; j < input_cDataArray2D.height; j++) {
for (int i = 0; i < input_cDataArray2D.width; i++) {
printf("%d\t", type.getRef(i, j));
}
std::cout << endl;
}
}
if (false) {
std::cout << "***** final Pressures *****" << endl; // TODO
for (int j = 0; j < input_cDataArray2D.height; j++) {
for (int i = 0; i < input_cDataArray2D.width; i++) {
printf("%e\t", getPressure(i, j, CENTER));
}
std::cout << endl;
}
}
if (false) {
std::cout << "***** final Velocities *****" << endl; // TODO
for (int j = 0; j < input_cDataArray2D.height; j++) {
for (int i = 0; i < input_cDataArray2D.width; i++) {
if (getVelocity(i, j, CENTER, X) != 0
|| getVelocity(i, j, CENTER, Y) != 0)
printf("%e,%e\t", getVelocity(i, j, CENTER, X),
getVelocity(i, j, CENTER, Y));
}
std::cout << endl;
}
}
// push pipeline
pipeline_push();
#ifdef EPETRA_MPI
MPI_Finalize();
#endif
}
void main_loop_callback() {
simulation_timestep();
}
/**
* process incoming pipeline input.
*
* the only input processed so far is from the video output stage to
* draw something into the image.
*/
void pipeline_process_input(CPipelinePacket &i_cPipelinePacket) {
// we are currently only able to process "unsigned char,1" flag arrays.
if (i_cPipelinePacket.type_info_name
!= typeid(CDataArray2D<unsigned char, 1> ).name()) {
std::cerr
<< "ERROR: Simulation input is only able to process (char,1) flag arrays"
<< std::endl;
exit(-1);
}
// unpack data
CDataArray2D<unsigned char, 1> *input = i_cPipelinePacket.getPayload<
CDataArray2D<unsigned char, 1> >();
// copy data to input array
input_cDataArray2D.resize(input->width, input->height);
input_cDataArray2D.loadData(input->data);
}
};
#endif /* CSTAGE_FLUIDSIMULATION_NS_HPP_ */
|
gpl-3.0
|
jlaws/gundog-engine
|
GaTCore/src/com/godsandtowers/achievements/CampaignAchievement.java
|
3111
|
/**
* Copyright (C) 2013 Gundog Studios LLC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.godsandtowers.achievements;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import com.godsandtowers.campaigns.Campaign;
import com.godsandtowers.campaigns.CampaignLevel;
import com.godsandtowers.core.PlayerStats;
import com.godsandtowers.sprites.BaseSpecial;
import com.godsandtowers.sprites.Races;
import com.gundogstudios.util.FastMath;
public class CampaignAchievement extends Achievement {
private int races;
private int difficulty;
public CampaignAchievement() {
}
public CampaignAchievement(String name, int achievementLevel, int races, int difficulty) {
super("campaign_" + name + "_" + difficulty, achievementLevel);
this.races = races;
this.difficulty = difficulty;
}
@Override
protected boolean execute(PlayerStats playerStats) {
HashMap<Integer, Campaign> campaigns = playerStats.getCampaigns();
int[] raceArray = Races.asArray(races);
for (int race : raceArray) {
Campaign campaign = campaigns.get(race);
for (CampaignLevel level : campaign.getLevels()) {
if (level.getStars() <= 0 || level.getDifficulty() < difficulty) {
return false;
}
}
}
for (int race : raceArray) {
for (BaseSpecial special : playerStats.getSpecials()) {
if (Races.isRaces(special.getRaces(), race)) {
for (int i = 0; i < achievementLevel * 5; i++) {
special.upgrade(0);
}
}
}
}
return true;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeInt(races);
out.writeInt(difficulty);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
races = in.readInt();
difficulty = in.readInt();
}
@Override
public float getPercentComplete(PlayerStats playerStats) {
HashMap<Integer, Campaign> campaigns = playerStats.getCampaigns();
float total = 0f;
float completed = 0f;
int[] raceArray = Races.asArray(races);
for (int race : raceArray) {
Campaign campaign = campaigns.get(race);
for (CampaignLevel level : campaign.getLevels()) {
if (level.getStars() > 0 && level.getDifficulty() >= difficulty) {
completed++;
}
total++;
}
}
return FastMath.min(1f, completed / total);
}
}
|
gpl-3.0
|
benfitzpatrick/cylc
|
lib/cylc/network/port_scan.py
|
7164
|
#!/usr/bin/pyro
# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2016 NIWA
#
# 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/>.
"""Pyro port scan utilities."""
from multiprocessing import cpu_count, Pool
import sys
from time import sleep
import traceback
import Pyro.errors
import Pyro.core
from cylc.cfgspec.globalcfg import GLOBAL_CFG
import cylc.flags
from cylc.network import PYRO_SUITEID_OBJ_NAME, NO_PASSPHRASE
from cylc.network.connection_validator import ConnValidator, SCAN_HASH
from cylc.network.suite_state import SuiteStillInitialisingError
from cylc.owner import USER
from cylc.registration import RegistrationDB
from cylc.suite_host import get_hostname, is_remote_host
def get_proxy(host, port, pyro_timeout):
"""Return Pyro URL of proxy."""
proxy = Pyro.core.getProxyForURI(
'PYROLOC://%s:%s/%s' % (host, port, PYRO_SUITEID_OBJ_NAME))
proxy._setTimeout(pyro_timeout)
return proxy
def scan(host=None, db=None, pyro_timeout=None):
"""Scan ports, return a list of suites found: [(port, suite.identify())].
Note that we could easily scan for a given suite+owner and return its
port instead of reading port files, but this may not always be fast enough.
"""
if host is None:
host = get_hostname()
base_port = GLOBAL_CFG.get(['pyro', 'base port'])
last_port = base_port + GLOBAL_CFG.get(['pyro', 'maximum number of ports'])
if pyro_timeout:
pyro_timeout = float(pyro_timeout)
else:
pyro_timeout = None
reg_db = RegistrationDB(db)
results = []
for port in range(base_port, last_port):
try:
proxy = get_proxy(host, port, pyro_timeout)
conn_val = ConnValidator()
conn_val.set_default_hash(SCAN_HASH)
proxy._setNewConnectionValidator(conn_val)
proxy._setIdentification((USER, NO_PASSPHRASE))
result = (port, proxy.identify())
except Pyro.errors.ConnectionDeniedError as exc:
if cylc.flags.debug:
print '%s:%s (connection denied)' % (host, port)
# Back-compat <= 6.4.1
msg = ' Old daemon at %s:%s?' % (host, port)
for pphrase in reg_db.load_all_passphrases():
try:
proxy = get_proxy(host, port, pyro_timeout)
proxy._setIdentification(pphrase)
info = proxy.id()
result = (port, {'name': info[0], 'owner': info[1]})
except Pyro.errors.ConnectionDeniedError:
connected = False
else:
connected = True
break
if not connected:
if cylc.flags.verbose:
print >> sys.stderr, msg, "- connection denied (%s)" % exc
continue
else:
if cylc.flags.verbose:
print >> sys.stderr, msg, "- connected with passphrase"
except Pyro.errors.TimeoutError as exc:
# E.g. Ctrl-Z suspended suite - holds up port scanning!
if cylc.flags.debug:
print '%s:%s (connection timed out)' % (host, port)
print >> sys.stderr, (
'suite? owner?@%s:%s - connection timed out (%s)' % (
host, port, exc))
continue
except (Pyro.errors.ProtocolError, Pyro.errors.NamingError) as exc:
# No suite at this port.
if cylc.flags.debug:
print str(exc)
print '%s:%s (no suite)' % (host, port)
continue
except SuiteStillInitialisingError:
continue
except Exception as exc:
if cylc.flags.debug:
traceback.print_exc()
raise
else:
owner = result[1].get('owner')
name = result[1].get('name')
states = result[1].get('states', None)
if cylc.flags.debug:
print ' suite:', name, owner
if states is None:
# This suite keeps its state info private.
# Try again with the passphrase if I have it.
pphrase = reg_db.load_passphrase(name, owner, host)
if pphrase:
try:
proxy = get_proxy(host, port, pyro_timeout)
conn_val = ConnValidator()
conn_val.set_default_hash(SCAN_HASH)
proxy._setNewConnectionValidator(conn_val)
proxy._setIdentification((USER, pphrase))
result = (port, proxy.identify())
except Exception:
# Nope (private suite, wrong passphrase).
if cylc.flags.debug:
print ' (wrong passphrase)'
else:
reg_db.cache_passphrase(
name, owner, host, pphrase)
if cylc.flags.debug:
print ' (got states with passphrase)'
results.append(result)
return results
def scan_all(hosts=None, reg_db_path=None, pyro_timeout=None):
"""Scan all hosts."""
if not hosts:
hosts = GLOBAL_CFG.get(["suite host scanning", "hosts"])
# Ensure that it does "localhost" only once
hosts = set(hosts)
for host in list(hosts):
if not is_remote_host(host):
hosts.remove(host)
hosts.add("localhost")
proc_pool_size = GLOBAL_CFG.get(["process pool size"])
if proc_pool_size is None:
proc_pool_size = cpu_count()
if proc_pool_size > len(hosts):
proc_pool_size = len(hosts)
proc_pool = Pool(proc_pool_size)
async_results = {}
for host in hosts:
async_results[host] = proc_pool.apply_async(
scan, [host, reg_db_path, pyro_timeout])
proc_pool.close()
scan_results = []
scan_results_hosts = []
while async_results:
sleep(0.05)
for host, async_result in async_results.items():
if async_result.ready():
async_results.pop(host)
try:
res = async_result.get()
except Exception:
if cylc.flags.debug:
traceback.print_exc()
else:
scan_results.extend(res)
scan_results_hosts.extend([host] * len(res))
proc_pool.join()
return zip(scan_results_hosts, scan_results)
|
gpl-3.0
|
SpecLad/Octetoscope
|
core/src/main/scala/ru/corrigendum/octetoscope/core/Dissector.scala
|
2000
|
/*
This file is part of Octetoscope.
Copyright (C) 2013-2016 Octetoscope contributors (see /AUTHORS.txt)
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 ru.corrigendum.octetoscope.core
import ru.corrigendum.octetoscope.abstractinfra.Blob
sealed case class DissectionContext(input: Blob,
softLimit: InfoSize,
untested: UntestedCallback = DissectionContext.ignoreUntested) {
require(softLimit <= Bytes(input.size))
}
object DissectionContext {
val ignoreUntested: UntestedCallback = () => ()
def apply(): DissectionContext = DissectionContext(Blob.empty, InfoSize())
def apply(input: Blob): DissectionContext = DissectionContext(input, Bytes(input.size))
}
trait Dissector[+V, +C <: Contents[V]] {
def dissect(context: DissectionContext, offset: InfoSize = InfoSize()): Piece[C]
def +?(constraint: Constraint[V]): Dissector[V, C] =
SpecialDissectors.constrained(this, constraint, NoteSeverity.Warning)
def +(constraint: Constraint[V]): Dissector[V, C] =
SpecialDissectors.constrained(this, constraint, NoteSeverity.Error)
}
trait MoleculeDissector[+V, +C <: Contents[V]] extends Dissector[V, C] {
override def dissect(context: DissectionContext, offset: InfoSize = InfoSize()): Molecule[C]
}
trait DissectorWithDefaultValue[+V, +C <: Contents[V]] extends Dissector[V, C] {
def defaultValue: V
}
|
gpl-3.0
|
ptsefton/worddown
|
tools/recite/citeproc-js/src/obj_token.js
|
6693
|
/*
* Copyright (c) 2009, 2010 and 2011 Frank G. Bennett, Jr. All Rights
* Reserved.
*
* The contents of this file are subject to the Common Public
* Attribution License Version 1.0 (the “License”); you may not use
* this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://bitbucket.org/fbennett/citeproc-js/src/tip/LICENSE.
*
* The License is based on the Mozilla Public License Version 1.1 but
* Sections 14 and 15 have been added to cover use of software over a
* computer network and provide for limited attribution for the
* Original Developer. In addition, Exhibit A has been modified to be
* consistent with Exhibit B.
*
* Software distributed under the License is distributed on an “AS IS”
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is the citation formatting software known as
* "citeproc-js" (an implementation of the Citation Style Language
* [CSL]), including the original test fixtures and software located
* under the ./std subdirectory of the distribution archive.
*
* The Original Developer is not the Initial Developer and is
* __________. If left blank, the Original Developer is the Initial
* Developer.
*
* The Initial Developer of the Original Code is Frank G. Bennett,
* Jr. All portions of the code written by Frank G. Bennett, Jr. are
* Copyright (c) 2009 and 2010 Frank G. Bennett, Jr. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Affero General Public License (the [AGPLv3]
* License), in which case the provisions of [AGPLv3] License are
* applicable instead of those above. If you wish to allow use of your
* version of this file only under the terms of the [AGPLv3] License
* and not to allow others to use your version of this file under the
* CPAL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the
* [AGPLv3] License. If you do not delete the provisions above, a
* recipient may use your version of this file under either the CPAL
* or the [AGPLv3] License.”
*/
/*global CSL: true */
/**
* Style token.
* <p>This class provides the tokens that define
* the runtime version of the style. The tokens are
* instantiated by {@link CSL.Core.Build}, but the token list
* must be post-processed with
* {@link CSL.Core.Configure} before it can be used to generate
* citations.</p>
* @param {String} name The node name represented by this token.
* @param {Int} tokentype A flag indicating whether this token
* marks the start of a node, the end of a node, or is a singleton.
* @class
*/
CSL.Token = function (name, tokentype) {
/**
* Name of the element.
* <p>This corresponds to the element name of the
* relevant tag in the CSL file.
*/
this.name = name;
/**
* Strings and other static content specific to the element.
*/
this.strings = {};
this.strings.delimiter = undefined;
this.strings.prefix = "";
this.strings.suffix = "";
/**
* Formatting parameters.
* <p>This is a placeholder at instantiation. It is
* replaced by the result of {@link CSL.setDecorations}
* when the tag is created and configured during {@link CSL.Core.Build}
* by {@link CSL.XmlToToken}. The parameters for particular
* formatting attributes are stored as string arrays, which
* map to formatting functions at runtime,
* when the output format is known. Note that the order in which
* parameters are registered is fixed by the constant
* {@link CSL.FORMAT_KEY_SEQUENCE}.
*/
this.decorations = false;
this.variables = [];
/**
* Element functions.
* <p>Functions implementing the styling behaviour of the element
* are pushed into this array in the {@link CSL.Core.Build} phase.
*/
this.execs = [];
/**
* Token type.
* <p>This is a flag constant indicating whether the token represents
* a start tag, an end tag, or is a singleton.</p>
*/
this.tokentype = tokentype;
/**
* Condition evaluator.
* <p>This is a placeholder that receives a single function, and is
* only relevant for a conditional branching tag (<code>if</code> or
* <code>else-if</code>). The function implements the argument to
* the <code>match=</code> attribute (<code>any</code>, <code>all</code>
* or <code>none</code>), by executing the functions registered in the
* <code>tests</code> array (see below), and reacting accordingly. This
* function is invoked by the execution wrappers found in
* {@link CSL.Engine}.</p>
*/
this.evaluator = false;
/**
* Conditions.
* <p>Functions that evaluate to true or false, implementing
* various posisble attributes to the conditional branching tags,
* are registered here during {@link CSL.Core.Build}.
* </p>
*/
this.tests = [];
/**
* Jump point on success.
* <p>This holds the list jump point to be used when the
* <code>evaluator</code> function of a conditional tag
* returns true (success). The jump index value is set during the
* back-to-front token pass performed during {@link CSL.Core.Configure}.
* </p>
*/
this.succeed = false;
/**
* Jump point on failure.
* <p>This holds the list jump point to be used when the
* <code>evaluator</code> function of a conditional tag
* returns false (failure). Jump index values are set during the
* back-to-front token pass performed during {@link CSL.Core.Configure}.
* </p>
*/
this.fail = false;
/**
* Index of next token.
* <p>This holds the index of the next token in the
* token list, which is the default "jump-point" for ordinary
* processing. Jump index values are set during the
* back-to-front token pass performed during {@link CSL.Core.Configure}.
* </p>
*/
this.next = false;
};
// Have needed this for yonks
CSL.Util.cloneToken = function (token) {
var newtok, key, pos, len;
if ("string" === typeof token) {
return token;
}
newtok = new CSL.Token(token.name, token.tokentype);
for (key in token.strings) {
if (token.strings.hasOwnProperty(key)) {
newtok.strings[key] = token.strings[key];
}
}
if (token.decorations) {
newtok.decorations = [];
for (pos = 0, len = token.decorations.length; pos < len; pos += 1) {
newtok.decorations.push(token.decorations[pos].slice());
}
}
if (token.variables) {
newtok.variables = token.variables.slice();
}
// Probably overkill; this is only used for cloning formatting
// tokens.
if (token.execs) {
newtok.execs = token.execs.slice();
newtok.tests = token.tests.slice();
}
return newtok;
};
|
gpl-3.0
|
PrekenWeb/PrekenWeb
|
src/PrekenWeb.WebApi/Models/JobParameter.cs
|
359
|
using System;
using System.Collections.Generic;
namespace PrekenWeb.WebApi.Models
{
public partial class JobParameter
{
public int Id { get; set; }
public int JobId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public virtual Job Job { get; set; }
}
}
|
gpl-3.0
|
akaunting/akaunting
|
app/Events/Document/DocumentCancelled.php
|
332
|
<?php
namespace App\Events\Document;
use Illuminate\Queue\SerializesModels;
class DocumentCancelled
{
use SerializesModels;
public $document;
/**
* Create a new event instance.
*
* @param $document
*/
public function __construct($document)
{
$this->document = $document;
}
}
|
gpl-3.0
|
xylographe/subtitleedit
|
src/Controls/SETextBox.cs
|
9545
|
using Nikse.SubtitleEdit.Core;
using Nikse.SubtitleEdit.Logic;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Nikse.SubtitleEdit.Controls
{
/// <summary>
/// TextBox where double click selects current word
/// </summary>
public sealed class SETextBox : TextBox
{
private string _dragText = string.Empty;
private int _dragStartFrom;
private long _dragStartTicks;
private bool _dragRemoveOld;
private bool _dragFromThis;
private long _gotFocusTicks;
public SETextBox()
{
AllowDrop = true;
DragEnter += SETextBox_DragEnter;
//DragOver += SETextBox_DragOver; could draw some gfx where drop position is...
DragDrop += SETextBox_DragDrop;
MouseDown += SETextBox_MouseDown;
MouseUp += SETextBox_MouseUp;
KeyDown += SETextBox_KeyDown;
// To fix issue where WM_LBUTTONDOWN got wrong "SelectedText" (only in undocked mode)
GotFocus += (sender, args) => { _gotFocusTicks = DateTime.UtcNow.Ticks; };
}
private void SETextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
{
SelectAll();
e.SuppressKeyPress = true;
}
else if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Back)
{
UiUtil.ApplyControlBackspace(this);
e.SuppressKeyPress = true;
}
}
private void SETextBox_MouseUp(object sender, MouseEventArgs e)
{
_dragRemoveOld = false;
_dragFromThis = false;
}
private void SETextBox_MouseDown(object sender, MouseEventArgs e)
{
if (MouseButtons == MouseButtons.Left && !string.IsNullOrEmpty(_dragText))
{
var pt = new Point(e.X, e.Y);
int index = GetCharIndexFromPosition(pt);
if (index >= _dragStartFrom && index <= _dragStartFrom + _dragText.Length)
{
// re-make selection
SelectionStart = _dragStartFrom;
SelectionLength = _dragText.Length;
try
{
var dataObject = new DataObject();
dataObject.SetText(_dragText, TextDataFormat.UnicodeText);
dataObject.SetText(_dragText, TextDataFormat.Text);
_dragFromThis = true;
if (ModifierKeys == Keys.Control)
{
_dragRemoveOld = false;
DoDragDrop(dataObject, DragDropEffects.Copy);
}
else if (ModifierKeys == Keys.None)
{
_dragRemoveOld = true;
DoDragDrop(dataObject, DragDropEffects.Move);
}
}
catch
{
// ignored
}
}
}
}
private void SETextBox_DragDrop(object sender, DragEventArgs e)
{
var pt = PointToClient(new Point(e.X, e.Y));
int index = GetCharIndexFromPosition(pt);
string newText;
if (e.Data.GetDataPresent(DataFormats.UnicodeText))
{
newText = (string)e.Data.GetData(DataFormats.UnicodeText);
}
else
{
newText = (string)e.Data.GetData(DataFormats.Text);
}
if (string.IsNullOrWhiteSpace(Text))
{
Text = newText;
}
else
{
bool justAppend = index == Text.Length - 1 && index > 0;
const string expectedChars = ":;]<.!?؟";
if (_dragFromThis)
{
_dragFromThis = false;
long milliseconds = (DateTime.UtcNow.Ticks - _dragStartTicks) / 10000;
if (milliseconds < 400)
{
SelectionLength = 0;
if (justAppend)
{
index++;
}
SelectionStart = index;
return; // too fast - nobody can drag'n'drop this fast
}
if (index >= _dragStartFrom && index <= _dragStartFrom + _dragText.Length)
{
return; // don't drop same text at same position
}
if (_dragRemoveOld)
{
_dragRemoveOld = false;
Text = Text.Remove(_dragStartFrom, _dragText.Length);
// fix spaces
if (_dragStartFrom == 0 && Text.Length > 0 && Text[0] == ' ')
{
Text = Text.Remove(0, 1);
index--;
}
else if (_dragStartFrom > 1 && Text.Length > _dragStartFrom + 1 && Text[_dragStartFrom] == ' ' && Text[_dragStartFrom - 1] == ' ')
{
Text = Text.Remove(_dragStartFrom, 1);
if (_dragStartFrom < index)
{
index--;
}
}
else if (_dragStartFrom > 0 && Text.Length > _dragStartFrom + 1 && Text[_dragStartFrom] == ' ' && expectedChars.Contains(Text[_dragStartFrom + 1]))
{
Text = Text.Remove(_dragStartFrom, 1);
if (_dragStartFrom < index)
{
index--;
}
}
// fix index
if (index > _dragStartFrom)
{
index -= _dragText.Length;
}
if (index < 0)
{
index = 0;
}
}
}
if (justAppend)
{
index = Text.Length;
Text += newText;
}
else
{
Text = Text.Insert(index, newText);
}
// fix start spaces
int endIndex = index + newText.Length;
if (index > 0 && !newText.StartsWith(' ') && Text[index - 1] != ' ')
{
Text = Text.Insert(index, " ");
endIndex++;
}
else if (index > 0 && newText.StartsWith(' ') && Text[index - 1] == ' ')
{
Text = Text.Remove(index, 1);
endIndex--;
}
// fix end spaces
if (endIndex < Text.Length && !newText.EndsWith(' ') && Text[endIndex] != ' ')
{
bool lastWord = expectedChars.Contains(Text[endIndex]);
if (!lastWord)
{
Text = Text.Insert(endIndex, " ");
}
}
else if (endIndex < Text.Length && newText.EndsWith(' ') && Text[endIndex] == ' ')
{
Text = Text.Remove(endIndex, 1);
}
SelectionStart = index + 1;
UiUtil.SelectWordAtCaret(this);
}
_dragRemoveOld = false;
_dragFromThis = false;
}
private void SETextBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text) || e.Data.GetDataPresent(DataFormats.UnicodeText))
{
e.Effect = ModifierKeys == Keys.Control ? DragDropEffects.Copy : DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private const int WM_DBLCLICK = 0xA3;
private const int WM_LBUTTONDBLCLK = 0x203;
private const int WM_LBUTTONDOWN = 0x0201;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_DBLCLICK || m.Msg == WM_LBUTTONDBLCLK)
{
UiUtil.SelectWordAtCaret(this);
return;
}
if (m.Msg == WM_LBUTTONDOWN)
{
long milliseconds = (DateTime.UtcNow.Ticks - _gotFocusTicks) / 10000;
if (milliseconds > 10)
{
_dragText = SelectedText;
_dragStartFrom = SelectionStart;
_dragStartTicks = DateTime.UtcNow.Ticks;
}
}
base.WndProc(ref m);
}
}
}
|
gpl-3.0
|
gnoubi/MarrakAir
|
javaFX/marrakAir2/src/main/java/ummisco/marrakAir/common/FollowedVariable.java
|
1367
|
package ummisco.marrakAir.common;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Timer;
public class FollowedVariable extends Observable {
private ArrayList<Map<String,Object>> data = null;
private String name = null;
private int lastIndex = 0;
public FollowedVariable(String nm)
{
this.data = new ArrayList<Map<String,Object>>();
this.name = nm;
}
public synchronized void pushNewData(Map<String,Object> nd)
{
newData(nd);
}
public List<Map<String,Object>> popAllData()
{
this.lastIndex = data.size();
return this.newData(null);
}
public List<Map<String,Object>> popLastData()
{
int tmp = lastIndex;
this.lastIndex = data.size();
System.out.println("taill "+ tmp+ " "+this.lastIndex);
return this.data.subList(tmp, this.lastIndex);
}
public String getName()
{
return name;
}
public synchronized ArrayList<Map<String,Object>> newData(Map<String,Object> nd)
{
System.out.println("new Data XXX");
if(nd== null )
{
ArrayList<Map<String,Object>> tmp = this.data;
this.data = new ArrayList<Map<String,Object>>();
this.lastIndex = 0;
return tmp;
}
System.out.println("new Data "+ nd);
this.data.add(nd);
this.setChanged();
this.notifyObservers();
return this.data;
}
}
|
gpl-3.0
|
iCarto/siga
|
libRaster/src/org/gvsig/raster/dataset/io/features/BMPFeatures.java
|
1659
|
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2007 IVER T.I. and Generalitat Valenciana.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*/
package org.gvsig.raster.dataset.io.features;
import org.gvsig.raster.dataset.Params;
import org.gvsig.raster.dataset.io.GdalDriver;
import org.gvsig.raster.dataset.io.GdalWriter;
/**
* Caracteristicas del formato BMP para escritura.
* Soporta escritura de imagenes 1 banda (monocromo) o 3 (RGB) en 8 bits.
* La georreferenciación puede hacerse mediante un fichero .wld.
*
* @version 04/06/2007
* @author Nacho Brodin (nachobrodin@gmail.com)
*/
public class BMPFeatures extends WriteFileFormatFeatures {
public BMPFeatures() {
super(GdalDriver.FORMAT_BMP, "bmp", new int[] { 3 }, null, GdalWriter.class);
}
/**
* Carga los parámetros de este driver.
*/
public void loadParams() {
super.loadParams();
driverParams.setParam("tfw", new Boolean("true"), Params.CHECK, null);
}
}
|
gpl-3.0
|
smnslwl/project_euler
|
41/41.py
|
1250
|
"""
We shall say that an n-digit number is pandigital if it makes use of all
the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital
and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
from math import sqrt
from itertools import permutations
def is_prime(n):
"""Returns true if n is a prime number"""
if n == 2 :
return True
if not n % 2 or n < 2:
return False
return all(n % x for x in range(3, int(sqrt(n)) + 1, 2))
def to_num(numbers):
"""Return a number made from an iterable of digits"""
n = 0
for i, num in enumerate(numbers):
n += 10 ** (len(numbers) - i - 1) * num
return n
if __name__ == '__main__':
max_pprime = 2143
for n in range(4, 10):
perms = (to_num(p) for p in permutations(range(1, n + 1), n))
for perm in perms:
if is_prime(perm):
max_pprime = perm
print(max_pprime)
"""
NOTE:
We start from the 2143 and the 4th digit because we are given
an example in the problem. As we are going through permutations,
there is no need to check for pandigital-ness. Similarly, the last
found result is always going to be the max as we are iterating in order.
"""
|
gpl-3.0
|
TkYu/SimpleAccessTokenContainer
|
SimpleAccessTokenContainer/WeixinJSSDKTicket.cs
|
1722
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SimpleAccessTokenContainer
{
public static class WeixinJSSDKTicket
{
private const string KeyName = "WeixinJSSDKTicket";
private const string ExpTimeName = "WeixinJSSDKTicketExpTime";
public static string GetNewToken(string appid, string secret)
{
var url = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={WeixinAccessToken.GetToken(appid, secret)}&type=jsapi";
var ret = Utils.GetString(url);
if (!ret.Contains("\"errcode\":0"))throw new Exception("error return code");
var regx = new Regex(@"^.*?""ticket"":""(.*?)"",""expires_in"":(\d+)\}$");
var mt = regx.Match(ret);
if (!mt.Success) throw new InvalidOperationException("wrong return");
Utils.WriteValue(appid, KeyName, mt.Groups[1].Value);
Utils.WriteValue(appid, ExpTimeName, DateTime.UtcNow.AddSeconds(int.Parse(mt.Groups[2].Value) - 120).ToString("yyyyMMddHHmmss"));
return mt.Groups[1].Value;
}
public static string GetToken(string appid, string secret)
{
var token = Utils.ReadValue(appid, KeyName);
var exp = string.IsNullOrEmpty(Utils.ReadValue(appid, ExpTimeName)) ? new DateTime(1970, 1, 1) : DateTime.ParseExact(Utils.ReadValue(appid, ExpTimeName), "yyyyMMddHHmmss", null, DateTimeStyles.None);
if (string.IsNullOrEmpty(token) || DateTime.UtcNow > exp)return GetNewToken(appid, secret);
return token;
}
}
}
|
gpl-3.0
|
allthefoxes/Reddit-Enhancement-Suite
|
lib/modules/showImages.js
|
53206
|
/*
If you would like RES to embed content from your website,
consult lib/modules/hosts/example.js
*/
import _ from 'lodash';
import elementResizeDetectorMaker from 'element-resize-detector';
import { flow, forEach, keyBy, map, tap } from 'lodash/fp';
import audioTemplate from '../templates/audio.mustache';
import galleryTemplate from '../templates/gallery.mustache';
import imageTemplate from '../templates/image.mustache';
import mediaControlsTemplate from '../templates/mediaControls.mustache';
import siteAttributionTemplate from '../templates/siteAttribution.mustache';
import textTemplate from '../templates/text.mustache';
import videoAdvancedTemplate from '../templates/videoAdvanced.mustache';
import { $ } from '../vendor';
import {
DAY,
positiveModulo,
Expando,
expandos,
primaryExpandos,
Thing,
getPostMetadata,
addCSS,
batch,
CreateElement,
scrollToElement,
forEachChunked,
forEachSeq,
filter,
frameDebounce,
isCurrentSubreddit,
isPageType,
objectValidator,
waitForEvent,
watchForElement,
regexes,
} from '../utils';
import { addURLToHistory, ajax, isPrivateBrowsing, openNewTab } from '../environment';
import * as Options from '../core/options';
import * as SettingsNavigation from './settingsNavigation';
const hostsContext = require.context('./hosts', false, /\.js$/);
const siteModules = flow(
map(hostsContext),
map('default'),
tap(forEach(objectValidator({ requiredProps: ['moduleID', 'name', 'domains', 'detect', 'handleLink'] }))),
keyBy('moduleID')
)(hostsContext.keys());
export const module = {};
module.moduleID = 'showImages';
module.moduleName = 'Inline Image Viewer';
module.category = ['Productivity', 'Browsing'];
module.description = 'Opens images inline in your browser with the click of a button. Also has configuration options, check it out!';
module.bodyClass = true;
module.options = {
galleryPreloadCount: {
type: 'text',
value: 2,
description: 'Number of preloaded gallery pieces for faster browsing.',
},
conserveMemory: {
type: 'boolean',
value: true,
description: 'Conserve memory by temporarily hiding images when they are offscreen.',
},
bufferScreens: {
type: 'text',
value: 2,
description: 'Hide images that are further than x screens away to save memory. A higher value means less flicker, but less memory savings.',
dependsOn: 'conserveMemory',
advanced: true,
},
maxWidth: {
type: 'text',
value: '100%',
description: 'Max width of media (in pixels, enter zero for unlimited). Percentage of window width may also be used (e.g. "100%").',
advanced: true,
},
maxHeight: {
type: 'text',
value: '80%',
description: 'Max height of media (in pixels, enter zero for unlimited). Percentage of window height may also be used (e.g. "100%").',
advanced: true,
},
displayOriginalResolution: {
type: 'boolean',
value: false,
description: 'Display each image\'s original (unresized) resolution in a tooltip.',
},
selfTextMaxHeight: {
type: 'text',
value: 0,
description: 'Add a scroll bar to text expandos taller than [x] pixels (enter zero for unlimited).',
advanced: true,
},
commentMaxHeight: {
type: 'text',
value: 0,
description: 'Add a scroll bar to comments taller than [x] pixels (enter zero for unlimited).',
advanced: true,
},
autoMaxHeight: {
type: 'boolean',
value: false,
description: `
Increase the max height of a self-text expando or comment if an expando is taller than the current max height.
This only takes effect if max height is specified (previous two options).
`,
advanced: true,
},
openInNewWindow: {
type: 'boolean',
value: true,
description: 'Open images in a new tab/window when clicked?',
},
hideNSFW: {
type: 'boolean',
value: false,
description: 'If checked, do not show images marked NSFW.',
},
highlightNSFWButton: {
type: 'boolean',
value: true,
description: 'Add special styling to expando buttons for images marked NSFW.',
bodyClass: true,
},
autoExpandSelfText: {
type: 'boolean',
value: true,
description: 'When loading selftext from an Aa+ expando, auto expand images, videos, and embeds.',
},
imageZoom: {
type: 'boolean',
value: true,
description: 'Allow dragging to resize/zoom images.',
},
imageMove: {
type: 'boolean',
value: true,
description: 'Allow dragging while holding shift to move images.',
},
mediaControls: {
type: 'boolean',
value: true,
description: 'Show additional image controls on hover.',
},
mediaControlsPosition: {
dependsOn: 'mediaControls',
type: 'enum',
value: 'top-left',
values: [{
name: 'Top left',
value: 'top-left',
}, {
name: 'Top right',
value: 'top-right',
}, {
name: 'Bottom left.',
value: 'bottom-left',
}, {
name: 'Bottom right.',
value: 'bottom-right',
}],
description: 'Set position of media controls',
},
clippy: {
dependsOn: 'mediaControls',
type: 'boolean',
value: true,
description: 'Show educational info, such as showing "drag to resize" in the media controls.',
},
displayImageCaptions: {
type: 'boolean',
value: true,
description: 'Retrieve image captions/attribution information.',
advanced: true,
bodyClass: true,
},
captionsPosition: {
dependsOn: 'displayImageCaptions',
type: 'enum',
value: 'titleAbove',
values: [{
name: 'Display all captions above image.',
value: 'allAbove',
}, {
name: 'Display title and caption above image, credits below.',
value: 'creditsBelow',
}, {
name: 'Display title above image, caption and credits below.',
value: 'titleAbove',
}, {
name: 'Display all captions below image.',
value: 'allBelow',
}],
description: 'Where to display captions around an image.',
advanced: true,
bodyClass: true,
},
markVisited: {
type: 'boolean',
value: true,
description: 'Mark links visited when you view images.',
advanced: true,
},
sfwHistory: {
dependsOn: 'markVisited',
type: 'enum',
value: 'add',
values: [{
name: 'Add links to history',
value: 'add',
}, {
name: 'Color links, but do not add to history',
value: 'color',
}, {
name: 'Do not add or color links.',
value: 'none',
}],
description: `
Keeps NSFW links from being added to your browser history <span style="font-style: italic">by the markVisited feature</span>.<br/>
<span style="font-style: italic">If you chose the second option, then links will be blue again on refresh.</span><br/>
<span style="color: red">This does not change your basic browser behavior.
If you click on a link then it will still be added to your history normally.
This is not a substitute for using your browser's privacy mode.</span>
`,
},
galleryAsFilmstrip: {
type: 'boolean',
value: false,
description: 'Display all media at once in a \'filmstrip\' layout, rather than the default navigable \'slideshow\' style.',
},
filmstripLoadIncrement: {
dependsOn: 'galleryAsFilmstrip',
type: 'text',
value: 30,
description: 'Limit the number of pieces loaded in a \'filmstrip\' by this number. (0 for no limit)',
},
useSlideshowWhenLargerThan: {
dependsOn: 'galleryAsFilmstrip',
type: 'text',
value: 0,
description: 'Show gallery as \'slideshow\' when the total number of pieces is larger than this number. (0 for no limit)',
},
convertGifstoGfycat: {
type: 'boolean',
value: false,
description: 'Convert Gif links to Gfycat links.',
},
showViewImagesTab: {
type: 'boolean',
value: true,
description: 'Show a \'view images\' tab at the top of each subreddit, to easily toggle showing all images at once.',
},
showSiteAttribution: {
type: 'boolean',
value: true,
description: 'Show the site logo and name after embedded content.',
},
expandoCommentRedirects: {
type: 'enum',
value: 'expando',
values: [{
name: 'Do nothing',
value: 'nothing',
}, {
name: 'Create expandos',
value: 'expando',
}, {
name: 'Create expandos, redirect the link back to the image',
value: 'rewrite',
}],
description: 'How should RES handle posts where the link is redirected to the comments page with preview expanded?',
},
showVideoControls: {
type: 'boolean',
value: true,
description: 'Show controls such as pause/play, step and playback rate.',
},
autoplayVideo: {
type: 'boolean',
value: true,
description: 'Autoplay inline videos',
},
};
module.exclude = [
/^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/ads\/[\-\w\._\?=]*/i,
/^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/[\-\w\.\/]*\/submit\/?$/i,
/^https?:\/\/(?:[\-\w\.]+\.)?reddit\.com\/subreddits/i,
];
module.loadDynamicOptions = () => {
// Augment the options with available image modules
for (const [id, siteModule] of Object.entries(siteModules)) {
// Ignore default
if (id === 'default') continue;
if (id === 'defaultVideo') continue;
if (id === 'defaultAudio') continue;
// Create on/off options
module.options[siteModuleOptionKey(siteModule)] = {
title: `display ${siteModule.name}`,
description: `Display expander for ${siteModule.name}`,
value: true,
type: 'boolean',
};
// Find out if module has any additional options - if it does add them
Object.assign(module.options, siteModule.options); // Object.assign ignores null/undefined
}
};
module.beforeLoad = () => {
const selfTextMaxHeight = parseInt(module.options.selfTextMaxHeight.value, 10);
if (selfTextMaxHeight) {
// Strange selector necessary to select tumblr expandos, etc.
addCSS(`
.selftext.expanded ~ * .md {
max-height: ${selfTextMaxHeight}px;
overflow-y: auto !important;
position: relative;
}
`);
}
const commentMaxHeight = parseInt(module.options.commentMaxHeight.value, 10);
if (commentMaxHeight) {
addCSS(`
.comment .md {
max-height: ${commentMaxHeight}px;
overflow-y: auto !important;
position: relative;
}
`);
}
};
let elementResizeDetector;
module.go = () => {
elementResizeDetector = elementResizeDetectorMaker({ strategy: 'scroll' });
watchForElement('siteTable', findAllImages);
watchForElement('selfText', v => findAllImages(v, true));
watchForElement('newComments', v => findAllImages(v, true));
createImageButtons();
for (const siteModule of Object.values(siteModules)) {
if (isSiteModuleEnabled(siteModule)) {
if (siteModule.go) siteModule.go();
}
}
findAllImages(document.body);
document.addEventListener('dragstart', () => false);
// Handle spotlight next/prev hiding open expando's
const spotlight = document.querySelector('#siteTable_organic');
if (spotlight) {
const nextprev = spotlight.querySelector('.nextprev');
if (!nextprev) return;
nextprev.addEventListener('click', () => {
const open = spotlight.querySelector('.expando-button.expanded');
if (open) open.click();
});
}
};
module.afterLoad = () => {
if (module.options.conserveMemory.value) {
enableConserveMemory();
}
enableCompleteDeferredExpandos();
};
function siteModuleOptionKey(siteModule) {
const id = siteModule.moduleID;
return `display_${id}`;
}
function isSiteModuleEnabled(siteModule) {
const key = siteModuleOptionKey(siteModule);
return !module.options[key] || module.options[key].value;
}
// A missing subdomain matches all subdomains, for example:
// A module with `domains: ['example.com']` will match `www.example.com` and `example.com`
// A module with `domains: ['www.example.com']` will match only `www.example.com`
const modulesForHostname = _.memoize(hostname => {
const hostComponents = hostname.split('.');
return Object.values(siteModules).filter(siteModule => (
isSiteModuleEnabled(siteModule) &&
siteModule.domains.some(domain => {
const domainComponents = domain.split('.');
return _.isEqual(domainComponents, _.takeRight(hostComponents, domainComponents.length));
})
));
});
// @type {Map.<expandoButton, () => completeExpando>}
const deferredExpandos = new Map();
const mediaStates = {
NONE: 0,
LOADED: 1,
UNLOADED: 2,
};
const resizeSources = {
OTHER: 0,
KEEP_VISIBLE: 1,
USER_MOVE: 2,
};
function isWithinBuffer(ele) {
if (!ele.offsetParent) return false;
const bufferScreens = module.options.bufferScreens.value || 2;
const viewportHeight = window.innerHeight;
const maximumTop = viewportHeight * (bufferScreens + 1);
const minimumBottom = viewportHeight * bufferScreens * -1;
const { bottom, top } = ele.getBoundingClientRect();
return top <= maximumTop && bottom >= minimumBottom;
}
function enableCompleteDeferredExpandos() {
const check = _.throttle(() => {
// Complete any deferred expandos which is within the buffer
for (const [expando, completeFunc] of deferredExpandos) {
if (isWithinBuffer(expando.button)) completeFunc();
}
}, 150);
window.addEventListener('scroll', check);
// not using element-resize-detector because it sets the target to `position: relative`, breaking some stylesheets (/r/nba)
window.addEventListener('resize', check);
}
/**
* enableConserveMemory
* attempt to unload collapsed expando's & images that are off screen in order
* to save memory
*
* @returns {void}
*/
function enableConserveMemory() {
const refresh = _.debounce(() => {
const activeExpandos = Array.from(primaryExpandos.values());
// Empty collapsed when beyond buffer
for (const expando of activeExpandos) {
if (!expando.isAttached()) expando.destroy();
else if (!expando.open && !isWithinBuffer(expando.button)) expando.empty();
}
// Unload expanded when beyond buffer
activeExpandos
.filter(v => v.isAttached() && v.open)
.map(v => ({ media: v.media, data: v.media }))
::lazyUnload(isWithinBuffer);
}, 150);
window.addEventListener('scroll', refresh);
// not using element-resize-detector because it sets the target to `position: relative`, breaking some stylesheets (/r/nba)
window.addEventListener('resize', refresh);
}
function lazyUnload(testKeepLoaded) {
for (const { media, data } of this) {
if (!media.unload || !media.restore) continue;
const keepLoaded = testKeepLoaded(data);
if (keepLoaded && media.state === mediaStates.UNLOADED) {
media.restore();
} else if (!keepLoaded && media.state === mediaStates.LOADED) {
media.unload();
}
}
}
let viewImagesButton;
let autoExpandActive = false;
let mediaBrowseModeActive = false;
export function toggleViewImages() {
viewImagesButton.checkbox.checked = !viewImagesButton.checkbox.checked;
viewImagesButton.checkbox.dispatchEvent(new Event('change'));
}
function createImageButtons() {
let $mainMenuUL = $('#header-bottom-left ul.tabmenu');
// Create new tabmenu on these pages, regardless if one already exists.
if (isPageType('search', 'modqueue') || isCurrentSubreddit('dashboard')) {
$mainMenuUL = $('<ul>', { class: 'tabmenu viewimages' });
$mainMenuUL.appendTo('#header-bottom-left');
$mainMenuUL.css('display', 'inline-block'); // Override dashboard's subreddit style.
}
if (module.options.showViewImagesTab.value) {
viewImagesButton = CreateElement.tabMenuItem({
text: 'show images',
className: 'res-show-images',
});
viewImagesButton.checkbox.addEventListener('change', e => {
autoExpandActive = e.target.checked;
// When activated, open the new ones in addition to the ones already open
// When deactivated, close all which are open
updateRevealedImages({ onlyOpen: autoExpandActive });
});
}
}
const updateAutoExpandCount = _.debounce(() => {
if (!viewImagesButton) return;
const count = Array.from(primaryExpandos.values())
.filter(expando => expando.isAttached() && expando.button.offsetParent &&
expando::isExpandWanted({ autoExpand: true }))
.length;
viewImagesButton.label.setAttribute('aftercontent', ` (${count})`);
}, 200);
const updateRevealedImages = _.debounce(({ onlyOpen = false } = {}) => {
primaryExpandos.values()
::filter(expando => expando.isAttached() && expando.button.offsetParent)
::sortExpandosVertically()
::forEachChunked(expando => {
const open = expando::isExpandWanted();
if (open) expando.expand();
else if (!onlyOpen) expando.collapse();
});
}, 100, { leading: true });
function sortExpandosVertically() {
return Array.from(this)
.map(v => [v.button.getBoundingClientRect().top, v])
.sort((a, b) => a[0] - b[0])
.map(v => v[1]);
}
export function toggleThingExpandos(thing, scrollOnExpando) {
const expandos = thing.getExpandos();
if (!expandos.length) return;
const openExpandos = expandos.filter(v => v.open);
// If any open expandos exists within thing, collapse all
// Else, expand all
if (openExpandos.length) {
for (const expando of openExpandos) expando.collapse();
if (scrollOnExpando) scrollToElement(thing.entry, { scrollStyle: 'directional' });
} else {
for (const expando of expandos) {
if (!(expando instanceof Expando) ||
expando::isExpandWanted({ thing, autoExpand: true, ignoreDuplicates: false, explicitOpen: true })
) {
expando.expand();
}
}
if (scrollOnExpando) scrollToElement(thing.entry, { scrollStyle: 'top' });
}
}
export function mediaBrowseMode(oldThing, newThing) {
if (autoExpandActive) return false;
const oldExpando = oldThing && oldThing.getEntryExpando();
const newExpando = newThing && newThing.getEntryExpando();
if (oldExpando) {
mediaBrowseModeActive = oldExpando.expandWanted || oldExpando.open;
}
if (mediaBrowseModeActive) {
if (oldExpando) oldExpando.collapse();
if (newExpando) newExpando.expand();
}
return newExpando && mediaBrowseModeActive;
}
function isExpandWanted({
thing = null,
explicitOpen = false,
autoExpand = autoExpandActive || explicitOpen,
ignoreDuplicates = true,
} = {}) {
if (ignoreDuplicates && !this.isPrimary()) return false;
if (this.inText && thing && (autoExpand ||
module.options.autoExpandSelfText.value && thing.isSelfPost() && !isPageType('comments')
)) {
// Expand all muted expandos and the first non-muted expando
return (this.mediaOptions && this.mediaOptions.muted) ||
!thing.getTextExpandos()
.find(v => (v.open || v.expandWanted) && (v.mediaOptions && !v.mediaOptions.muted));
} else {
return explicitOpen || (autoExpand && (this.mediaOptions && this.mediaOptions.muted));
}
}
function findAllImages(elem, isSelfText) {
// get elements common across all pages first...
// if we're on a comments page, get those elements too...
let allElements = [];
if (isPageType('comments', 'profile')) {
allElements = elem.querySelectorAll('#siteTable a.title, .expando .usertext-body > div.md a, .content .usertext-body > div.md a');
} else if (isSelfText) {
// We're scanning newly opened (from an expando) selftext...
allElements = elem.querySelectorAll('.usertext-body > div.md a');
} else if (isPageType('wiki')) {
allElements = elem.querySelectorAll('.wiki-page-content a');
} else if (isPageType('inbox')) {
allElements = elem.querySelectorAll('#siteTable div.entry .md a');
} else if (isPageType('search')) {
allElements = elem.querySelectorAll('#siteTable a.title, .contents a.search-link');
} else {
allElements = elem.querySelectorAll('#siteTable A.title, #siteTable_organic a.title');
}
allElements::forEachChunked(checkElementForMedia);
}
async function convertGifToVideo(options) {
try {
const info = await ajax({
type: 'json',
url: '//upload.gfycat.com/transcodeRelease',
data: { fetchUrl: options.src },
cacheFor: DAY,
});
if (!info.gfyName) throw new Error('gfycat transcode did not contain "gfyName"');
return {
options: await siteModules.gfycat.handleLink('', [], info),
siteModule: siteModules.gfycat,
};
} catch (e) {
throw new Error(`Could not convert gif to video ${options.src}: ${e}`);
}
}
async function resolveMediaUrl(element, thing) {
if (module.options.expandoCommentRedirects.value === 'nothing') {
return element;
}
if (element.classList.contains('title')) {
const dataUrl = thing.$thing.data('url');
const fullDataUrl = dataUrl && new URL(dataUrl, location);
if (fullDataUrl && fullDataUrl.href !== thing.getCommentsLink().href) {
return fullDataUrl;
}
if (element.hostname === location.hostname) {
const [, , id] = regexes.comments.exec(element.pathname);
const { url } = await getPostMetadata({ id });
if (module.options.expandoCommentRedirects.value === 'rewrite') {
element.href = url;
}
return new URL(url, location);
}
}
return element;
}
function getMediaInfo(element, mediaUrl) {
const matchingHosts = [
...modulesForHostname(mediaUrl.hostname),
siteModules.default,
siteModules.defaultVideo,
siteModules.defaultAudio,
];
for (const siteModule of matchingHosts) {
const detectResult = siteModule.detect(mediaUrl);
if (detectResult) return { detectResult, siteModule, element, href: mediaUrl.href };
}
}
// @type {WeakMap.<element, boolean|Expando>}
const scannedLinks = new WeakMap();
export const getLinkExpando = link => {
const expando = scannedLinks.get(link);
if (expando instanceof Expando) return expando;
};
async function checkElementForMedia(element) {
if (scannedLinks.has(element)) return;
else scannedLinks.set(element, true);
const thing = new Thing(element);
if (!thing.element) return;
const inText = !!$(element).closest('.md, .search-result-footer')[0];
const entryExpando = !inText && thing.getEntryExpando();
const nativeExpando = entryExpando instanceof Expando ? null : entryExpando;
if (module.options.hideNSFW.value && thing.isNSFW()) {
if (nativeExpando) nativeExpando.detach();
return;
}
if (nativeExpando) {
trackNativeExpando(nativeExpando, element);
if (nativeExpando.open) {
console.log('Native expando has already been opened; skipping.', element.href);
return;
}
}
const mediaUrl = await resolveMediaUrl(element, thing);
const mediaInfo = getMediaInfo(element, mediaUrl);
if (!mediaInfo) return;
if (nativeExpando) nativeExpando.detach();
const expando = new Expando(inText);
expandos.set(expando.button, expando);
scannedLinks.set(element, expando);
if (!inText && thing.getTitleElement()) {
$(expando.button).insertAfter(element.parentElement);
thing.entry.appendChild(expando.box);
} else {
$(element).add($(element).next('.keyNavAnnotation')).last()
.after(expando.box)
.after(expando.button);
}
expando.button.addEventListener('click', () => {
if (expando.deferred) {
deferredExpandos.get(expando)();
}
expando.toggle({ scrollOnMoveError: true });
}, true);
const complete = () => {
completeExpando(expando, thing, mediaInfo).catch(e => {
console.error(`showImages: could not create expando for ${mediaInfo.href}`);
console.error(e);
if (nativeExpando) nativeExpando.reattach();
expando.destroy();
scannedLinks.set(element, true);
});
};
if (!expando.button.offsetParent) {
// No need to complete building non-visible expandos
expando.deferred = true;
deferredExpandos.set(expando, () => {
complete();
deferredExpandos.delete(expando);
});
} else {
complete();
}
}
async function completeExpando(expando, thing, mediaInfo) {
expando.deferred = false;
const options = await retrieveExpandoOptions(thing, mediaInfo);
Object.assign(expando, options);
if (thing.isComment()) {
expando.onExpand(_.once(() => {
let wasOpen;
// Execute expando toggle procedure when comment collapse / expand
thing.$thing
.parents('.comment')
.addBack()
.find('> .entry .tagline > .expand')
.click(() => {
if (expando.button.offsetParent) {
if (wasOpen) expando.expand();
} else {
wasOpen = expando.open;
if (expando.open) expando.collapse();
}
updateAutoExpandCount();
});
}));
}
if (module.options.autoMaxHeight.value && expando.inText) {
thing.entry.addEventListener('mediaResize', updateParentHeight);
}
if (!expando.expandWanted) expando.expandWanted = expando::isExpandWanted({ thing });
expando.initialize();
updateAutoExpandCount();
}
const retrieveExpandoOptions = _.memoize(async (thing, { siteModule, detectResult, element, href }) => {
let mediaOptions = await siteModule.handleLink(href, detectResult);
if (module.options.convertGifstoGfycat.value &&
mediaOptions.type === 'IMAGE' &&
(/^(http|https|ftp):\/\/.*\.gif($|\/?)/).test(mediaOptions.src)
) {
try {
({ options: mediaOptions, siteModule } = await convertGifToVideo(mediaOptions));
} catch (e) {
console.log(e);
}
}
const attribution = module.options.showSiteAttribution.value &&
thing.isPost() && !thing.isSelfPost() &&
siteModule.domains.length && siteModule.attribution !== false;
const isMuted = ({ muted, type }) => muted || ['IMAGE', 'TEXT'].includes(type);
mediaOptions = {
attribution,
href,
muted: mediaOptions.type === 'GALLERY' ? mediaOptions.src.every(isMuted) : isMuted(mediaOptions),
...mediaOptions,
};
mediaOptions.buttonInfo = getMediaButtonInfo(mediaOptions);
const trackLoad = _.once(() => trackMediaLoad(element));
return {
href, // Since mediaOptions.href may be overwritten
generateMedia: () => generateMedia(mediaOptions, siteModule),
mediaOptions,
onMediaAttach() {
trackLoad();
if (mediaOptions.onAttach) mediaOptions.onAttach();
},
};
}, (thing, { href }) => href);
function updateParentHeight(e) {
const thing = new Thing(e.target);
const basisHeight = (thing.isSelfPost() && parseInt(module.options.selfTextMaxHeight.value, 10)) ||
(thing.isComment() && parseInt(module.options.commentMaxHeight.value, 10));
if (basisHeight > 0) {
// .expando-button causes a line break
const expandoHeight = Array
.from(thing.entry.querySelectorAll('.res-expando-box, .expando-button.expanded'))
.reduce((a, b) => a + b.getBoundingClientRect().height, 0);
thing.querySelector('.md').style.maxHeight = `${basisHeight + expandoHeight}px`;
}
}
function trackNativeExpando(expando, element) {
// only track media
if (expando.button.classList.contains('selftext')) return;
const trackLoad = _.once(() => trackMediaLoad(element));
if (expando.open) trackLoad();
else expando.button.addEventListener('click', trackLoad);
}
function getMediaButtonInfo(options) {
let title = '';
let type = options.type;
if (options.type === 'GALLERY') {
if (options.src.length === 1) {
type = options.src[0].type;
} else {
title += `${options.src.length} items in gallery`;
}
}
const defaultClass = {
IMAGE: 'image',
GALLERY: 'image gallery',
TEXT: 'selftext',
VIDEO: options.muted ? 'video-muted' : 'video',
IFRAME: options.muted ? 'video-muted' : 'video',
AUDIO: 'video', // yes, still class "video", that's what reddit uses.
NOEMBED: 'video',
GENERIC_EXPANDO: 'selftext',
}[type];
return {
title,
mediaClass: options.expandoClass || defaultClass,
};
}
function generateMedia(options, siteModule) {
if (options.credits) options.credits = $('<span>').safeHtml(options.credits).html();
if (options.caption) options.caption = $('<span>').safeHtml(options.caption).html();
const mediaGenerators = {
GALLERY: generateGallery,
IMAGE: generateImage,
TEXT: generateText,
IFRAME: generateIframe,
VIDEO: generateVideo,
AUDIO: generateAudio,
NOEMBED: generateNoEmbed,
GENERIC_EXPANDO: generateGeneric,
};
const element = mediaGenerators[options.type](options);
if (options.attribution) addSiteAttribution(siteModule, element);
return element;
}
function generateGallery(options) {
const element = $(galleryTemplate(options))[0];
const piecesContainer = element.querySelector('.res-gallery-pieces');
const individualCtrl = element.querySelector('.res-gallery-individual-controls');
const ctrlPrev = individualCtrl.querySelector('.res-gallery-previous');
const ctrlNext = individualCtrl.querySelector('.res-gallery-next');
const msgPosition = individualCtrl.querySelector('.res-gallery-position');
const ctrlConcurrentIncrease = element.querySelector('.res-gallery-increase-concurrent');
const preloadCount = parseInt(module.options.galleryPreloadCount.value, 10) || 0;
const filmstripLoadIncrement = parseInt(module.options.filmstripLoadIncrement.value, 10) || Infinity;
const slideshowWhenLargerThan = parseInt(module.options.useSlideshowWhenLargerThan.value, 10) || Infinity;
const filmstripActive = module.options.galleryAsFilmstrip.value &&
options.src.length < slideshowWhenLargerThan;
const pieces = options.src.map(src => ({ options: { href: options.href, ...src }, media: null }));
let lastRevealedPiece = null;
function revealPiece(piece) {
lastRevealedPiece = piece;
piece.media = piece.media || generateMedia(piece.options);
if (!piece.media.parentElement) {
const block = document.createElement('div');
block.appendChild(piece.media);
piecesContainer.appendChild(block);
}
piece.media.parentElement.hidden = false;
if (piece.media.expand) piece.media.expand();
}
function preloadAhead() {
const preloadFrom = pieces.indexOf(lastRevealedPiece) + 1;
const preloadTo = Math.min(preloadFrom + preloadCount, pieces.length);
pieces.slice(preloadFrom, preloadTo)::forEachSeq(piece => {
if (!piece.media) piece.media = generateMedia(piece.options);
return piece.media.ready;
});
}
async function expandFilmstrip() {
const revealFrom = pieces.indexOf(lastRevealedPiece) + 1;
const revealTo = Math.min(revealFrom + filmstripLoadIncrement, pieces.length);
ctrlConcurrentIncrease.hidden = true;
// wait for last revealed piece to load, if present
if (lastRevealedPiece && lastRevealedPiece.media && lastRevealedPiece.media.ready) {
await lastRevealedPiece.media.ready;
}
// reveal new pieces
await pieces.slice(revealFrom, revealTo)::forEachSeq(piece => {
revealPiece(piece);
return piece.media.ready;
});
if (revealTo < pieces.length) {
ctrlConcurrentIncrease.innerText = `Show next ${Math.min(filmstripLoadIncrement, pieces.length - revealTo)} pieces`;
ctrlConcurrentIncrease.hidden = false;
}
preloadAhead();
}
async function changeSlideshowPiece(step) {
const lastRevealedPieceIndex = lastRevealedPiece ? pieces.indexOf(lastRevealedPiece) : 0;
const previousMedia = lastRevealedPiece && lastRevealedPiece.media;
let newIndex = lastRevealedPieceIndex + step;
// Allow wrap-around
newIndex = positiveModulo(newIndex, pieces.length);
individualCtrl.setAttribute('first-piece', newIndex === 0);
individualCtrl.setAttribute('last-piece', newIndex === pieces.length - 1);
msgPosition.innerText = newIndex + 1;
revealPiece(pieces[newIndex]);
if (previousMedia) {
const removeInstead = previousMedia.collapse && previousMedia.collapse();
if (removeInstead) {
previousMedia.remove();
} else {
previousMedia.parentElement.hidden = true;
}
}
if (module.options.conserveMemory.value) {
const first = newIndex - preloadCount;
const last = newIndex + preloadCount;
pieces.filter(piece => piece.media)
.map(piece => ({ media: piece.media, data: piece }))
::lazyUnload(piece => {
const index = pieces.indexOf(piece);
if (last > pieces.length && last % pieces.length >= index) return true;
if (first < 0 && positiveModulo(first, pieces.length) <= index) return true;
return index >= first && index <= last;
});
}
if (lastRevealedPiece.media.ready) await lastRevealedPiece.media.ready;
preloadAhead();
}
if (filmstripActive || pieces.length === 1) {
expandFilmstrip();
ctrlConcurrentIncrease.addEventListener('click', expandFilmstrip);
} else {
element.classList.add('res-gallery-slideshow');
changeSlideshowPiece(0);
ctrlPrev.addEventListener('click', () => { changeSlideshowPiece(-1); });
ctrlNext.addEventListener('click', () => { changeSlideshowPiece(1); });
}
return element;
}
function generateImage(options) {
options.openInNewWindow = module.options.openInNewWindow.value;
const element = $(imageTemplate(options))[0];
const image = element.querySelector('img.res-image-media');
const anchor = element.querySelector('a.res-expando-link');
const transparentGif = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
element.state = mediaStates.NONE;
image.addEventListener('error', () => {
element.classList.add('res-media-load-error');
image.title = '';
element.emitResizeEvent();
});
image.addEventListener('load', () => {
if (element.state !== mediaStates.UNLOADED) element.emitResizeEvent();
if (element.state === mediaStates.NONE) {
if (module.options.displayOriginalResolution.value && image.naturalWidth && image.naturalHeight) {
image.title = `${image.naturalWidth} × ${image.naturalHeight} px`;
}
element.state = mediaStates.LOADED;
}
});
element.unload = () => {
element.state = mediaStates.UNLOADED;
image.src = transparentGif;
};
element.restore = () => {
element.state = mediaStates.LOADED;
image.src = options.src;
};
element.ready = waitForEvent(image, 'load', 'error');
element.emitResizeEvent = () => {
if (element.state !== mediaStates.UNLOADED) image.dispatchEvent(new CustomEvent('mediaResize', { bubbles: true }));
};
setMediaMaxSize(image);
makeMediaZoomable(image);
const wrapper = setMediaControls(anchor, options.src);
makeMediaMovable(wrapper);
keepMediaVisible(wrapper);
makeMediaIndependentOnResize(element, wrapper);
return element;
}
function generateIframe(options) {
const iframeNode = document.createElement('iframe');
iframeNode.src = (module.options.autoplayVideo.value && options.embedAutoplay) ?
options.embedAutoplay : options.embed;
iframeNode.allowFullscreen = true;
iframeNode.style.border = '0';
iframeNode.style.height = options.height || '360px';
iframeNode.style.width = options.width || '640px';
iframeNode.style.minWidth = '480px';
iframeNode.style.maxWidth = 'initial';
const element = document.createElement('div');
element.appendChild(iframeNode);
let loaded = false;
element.expand = async () => {
if (module.options.autoplayVideo.value && options.play) {
if (!loaded) await waitForEvent(iframeNode, 'load');
loaded = true;
if (!iframeNode.offsetParent) {
// It may have been collapsed in the meanwhile
element.remove();
return;
}
try {
iframeNode.contentWindow.postMessage(options.play, '*');
} catch (e) {
console.error('Could not post "play" command to iframe', options.embed, e);
}
}
};
element.collapse = () => {
let removeInstead = true;
if (options.pause) {
try {
iframeNode.contentWindow.postMessage(options.pause, '*');
removeInstead = false;
} catch (e) {
console.error('Could not post "pause" command to iframe', options.embed, e);
}
}
return removeInstead;
};
element.emitResizeEvent =
() => { iframeNode.dispatchEvent(new CustomEvent('mediaResize', { bubbles: true })); };
element.independent = true;
keepMediaVisible(iframeNode);
makeMediaIndependentOnResize(element, iframeNode);
return element;
}
function generateText(options) {
options.src = $('<span>').safeHtml(options.src).html();
return $(textTemplate(options))[0];
}
function generateVideo(options) {
// Use default values for options not explicitly set
const filledOptions = {
autoplay: options.muted || module.options.autoplayVideo.value,
advancedControls: module.options.showVideoControls.value,
controls: true,
frameRate: 24,
loop: false,
muted: false,
openInNewWindow: module.options.openInNewWindow.value,
playbackRate: 1,
reversable: false,
time: 0,
...options,
};
return videoAdvanced(filledOptions);
}
function generateAudio(options) {
let {
autoplay,
} = options;
const element = $(audioTemplate(options))[0];
const audio = element.querySelector('audio');
element.collapse = () => {
// Audio is auto-paused when detached from DOM
if (!document.body.contains(audio)) return;
autoplay = !audio.paused;
if (!audio.paused) audio.pause();
};
element.expand = () => { if (autoplay) audio.play(); };
return element;
}
function generateGeneric(options) {
const element = document.createElement('div');
element.appendChild(options.generate(options));
// Always remove content, in case it contains audio or other unwanted things
element.collapse = () => true;
return element;
}
// XXX Correctness not considered since it is not in use
async function generateNoEmbed(options) {
const noEmbedFrame = document.createElement('iframe');
// not all noEmbed responses have a height and width, so if
// this siteMod has a width and/or height set, use them.
if (options.width) {
noEmbedFrame.setAttribute('width', options.width);
}
if (options.height) {
noEmbedFrame.setAttribute('height', options.height);
}
if (options.urlMod) {
noEmbedFrame.setAttribute('src', options.urlMod(response.url));
}
const response = await ajax({
url: 'https://noembed.com/embed',
data: { url: options.src },
type: 'json',
});
for (const key in response) {
switch (key) {
case 'url':
if (!noEmbedFrame.hasAttribute('src')) {
noEmbedFrame.setAttribute('src', response[key]);
}
break;
case 'width':
noEmbedFrame.setAttribute('width', response[key]);
break;
case 'height':
noEmbedFrame.setAttribute('height', response[key]);
break;
default:
break;
}
}
return noEmbedFrame;
}
const trackVisit = batch(async links => {
if (await isPrivateBrowsing()) return;
const fullnames = links
.map(link => $(link).closest('.thing'))
.filter($link => !$link.hasClass('visited'))
.map($link => $link.data('fullname'));
await ajax({
method: 'POST',
url: '/api/store_visits',
data: { links: fullnames.join(',') },
});
}, { delay: 1000 });
function trackMediaLoad(link) {
if (module.options.markVisited.value) {
// also use reddit's mechanism for storing visited links if user has gold.
if ($('body').hasClass('gold')) {
trackVisit(link);
}
const isNSFW = $(link).closest('.thing').is('.over18');
const sfwMode = module.options.sfwHistory.value;
const url = link.href;
if (!isNSFW || sfwMode !== 'none') link.classList.add('visited');
if (!isNSFW || sfwMode === 'add') addURLToHistory(url);
}
}
function setMediaControls(media, lookupUrl) {
if (!module.options.mediaControls.value) return media;
const [y, x] = module.options.mediaControlsPosition.value.split('-');
const options = { clippy: module.options.clippy.value, lookupUrl, x, y };
const element = $(mediaControlsTemplate(options))[0];
const controls = element.querySelector('.res-media-controls');
$(media).replaceWith(element);
element.appendChild(media);
let rotationState = 0;
const hookInResizeListener = _.once(() => {
media.addEventListener('mediaResize', () => {
const horizontal = rotationState % 2 === 0;
const height = horizontal ? media.clientHeight : media.clientWidth;
const width = horizontal ? media.clientWidth : media.clientHeight;
element.style.width = `${width}px`;
element.style.height = `${height}px`;
media.style.position = 'absolute';
});
});
controls.addEventListener('click', e => {
hookInResizeListener();
switch (e.target.dataset.action) {
case 'rotateLeft':
rotateMedia(media, --rotationState);
break;
case 'rotateRight':
rotateMedia(media, ++rotationState);
break;
case 'imageLookup':
// Google doesn't like image url's without a protacol
lookupUrl = new URL(lookupUrl, location.href).href;
openNewTab(`https://images.google.com/searchbyimage?image_url=${lookupUrl}`);
break;
case 'showImageSettings':
SettingsNavigation.loadSettingsPage(module.moduleID, 'mediaControls');
break;
case 'clippy':
if (e.target.classList.contains('res-media-controls-clippy-expanded')) {
Options.set(module, 'clippy', false);
e.target.remove();
} else {
e.target.classList.add('res-media-controls-clippy-expanded');
e.target.title = 'Click to disable the info button';
e.target.innerText = getClippyText();
}
break;
default:
// do nothing if action is unknown
break;
}
e.stopPropagation();
e.preventDefault();
});
return element;
}
function addSiteAttribution(siteModule, media) {
const metadata = {
name: siteModule.name,
url: siteModule.landingPage || `//${siteModule.domains[0]}`,
logoUrl: siteModule.logo,
settingsLink: SettingsNavigation.makeUrlHash(module.moduleID, siteModuleOptionKey(siteModule)),
};
const $element = $(siteAttributionTemplate(metadata));
const $replace = $.find('.res-expando-siteAttribution', media);
if ($replace.length) {
$element.replaceAll($replace);
} else {
$element.appendTo(media);
}
}
function keepMediaVisible(media) {
let isManuallyMoved = false;
media.classList.add('res-media-keep-visible');
media.addEventListener('mediaResize', e => {
if (e.detail === resizeSources.KEEP_VISIBLE) return;
if (isManuallyMoved || e.detail === resizeSources.USER_MOVE) {
isManuallyMoved = true;
return;
}
const documentWidth = document.documentElement.getBoundingClientRect().width;
const { width: mediaWidth, left: mediaLeft, right: mediaRight } = media.getBoundingClientRect();
const basisLeft = media.parentElement.getBoundingClientRect().left;
const deltaLeft = mediaLeft - basisLeft;
if (mediaWidth > documentWidth) { // Left align
moveMedia(media, -mediaLeft, 0, resizeSources.KEEP_VISIBLE);
} else if (mediaRight - deltaLeft > documentWidth) { // Right align
moveMedia(media, documentWidth - mediaRight, 0, resizeSources.KEEP_VISIBLE);
} else if (deltaLeft) { // Reset
moveMedia(media, -deltaLeft, 0, resizeSources.KEEP_VISIBLE);
}
});
}
function getClippyText() {
const clippy = [];
if (module.options.imageZoom.value) {
clippy.push('drag to resize');
}
if (module.options.imageMove.value) {
clippy.push('shift-drag to move');
}
return clippy.join(' or ');
}
function setMediaMaxSize(media) {
let value = module.options.maxWidth.value;
let maxWidth = parseInt(value, 10);
if (maxWidth > 0) {
if (_.isString(value) && value.endsWith('%')) {
const viewportWidth = document.documentElement.getBoundingClientRect().width;
maxWidth *= viewportWidth / 100;
}
media.style.maxWidth = `${maxWidth}px`;
}
value = module.options.maxHeight.value;
let maxHeight = parseInt(value, 10);
if (maxHeight > 0) {
if (_.isString(value) && value.endsWith('%')) {
const viewportHeight = document.documentElement.clientHeight;
maxHeight *= viewportHeight / 100;
}
media.style.maxHeight = `${maxHeight}px`;
}
}
function addDragListener({ media, atShiftKey, onStart, onMove }) {
let isActive, hasMoved, lastX, lastY;
const handleMove = frameDebounce(e => {
const movementX = e.clientX - lastX;
const movementY = e.clientY - lastY;
if (!movementX && !movementY) {
// Mousemove may be triggered even without movement
return;
} else if (atShiftKey !== e.shiftKey) {
isActive = false;
({ clientX: lastX, clientY: lastY } = e);
return;
}
if (!isActive) {
if (onStart) onStart(lastX, lastY);
isActive = true;
hasMoved = true;
document.body.classList.add('res-media-dragging');
}
onMove(e.clientX, e.clientY, movementX, movementY);
({ clientX: lastX, clientY: lastY } = e);
});
function handleClick(e) {
if (hasMoved) e.preventDefault();
document.removeEventListener('click', handleClick);
}
function stop() {
document.body.classList.remove('res-media-dragging');
document.removeEventListener('mousemove', handleMove);
document.removeEventListener('mouseup', stop);
}
function initiate(e) {
if (e.button !== 0) return;
({ clientX: lastX, clientY: lastY } = e);
hasMoved = false;
isActive = false;
document.addEventListener('mousemove', handleMove);
document.addEventListener('mouseup', stop);
document.addEventListener('click', handleClick);
e.preventDefault();
}
media.addEventListener('mousedown', initiate);
}
function makeMediaZoomable(media) {
if (!module.options.imageZoom.value) return;
media.classList.add('res-media-zoomable');
let initialWidth, initialDiagonal, minWidth, left, top;
function getDiagonal(x, y) {
const w = Math.max(1, x - left);
const h = Math.max(1, y - top);
return Math.round(Math.hypot(w, h));
}
addDragListener({
media,
atShiftKey: false,
onStart(x, y) {
({ left, top } = media.getBoundingClientRect());
initialDiagonal = getDiagonal(x, y);
initialWidth = media.clientWidth;
minWidth = Math.max(1, Math.min(media.clientWidth, 100));
},
onMove(x, y) {
const newWidth = Math.max(minWidth, getDiagonal(x, y) / initialDiagonal * initialWidth);
resizeMedia(media, newWidth);
},
});
}
function makeMediaMovable(media) {
if (!module.options.imageMove.value) return;
media.classList.add('res-media-movable');
addDragListener({
media,
atShiftKey: true,
onMove(x, y, deltaX, deltaY) { moveMedia(media, deltaX, deltaY); },
});
}
function makeMediaIndependentOnResize(media, element) {
const wrapper = document.createElement('div');
const independent = document.createElement('div');
$(element).replaceWith(wrapper);
wrapper.appendChild(independent);
independent.appendChild(element);
const debouncedResize = frameDebounce(media.emitResizeEvent);
media.addEventListener('mediaResize', e => {
media.independent = true;
if (!media.offsetParent) {
// Allowing propagation when non-visible may cause unwanted side-effects,
// so cancel and instead emit a new signal when expanded
e.stopImmediatePropagation();
}
}, true);
let lastHeight = 0;
media.addEventListener('mediaResize', () => {
const height = element.clientHeight;
if (lastHeight !== height) {
lastHeight = height;
wrapper.style.height = `${height}px`;
}
independent.classList.add('res-media-independent');
window.addEventListener('resize', debouncedResize);
});
// This is a slower method to listen to resizes, as it waits till the frame after the size is se to updatet.
// Using this is however necessary when it's not possible to determine size from media events.
elementResizeDetector.listenTo(element, () => {
if (element.clientHeight !== lastHeight) media.emitResizeEvent();
});
const prevExpand = media.expand;
media.expand = () => {
if (media.independent) media.emitResizeEvent();
if (prevExpand) return prevExpand();
};
const prevCollapse = media.collapse;
media.collapse = () => {
window.removeEventListener('resize', debouncedResize);
if (prevCollapse) return prevCollapse();
};
}
function videoAdvanced(options) {
const {
fallback,
frameRate,
playbackRate,
advancedControls,
} = options;
let {
autoplay,
time,
} = options;
// Poster is unnecessary, and will flash if loaded before the video is ready
if (autoplay) delete options.poster;
const element = document.createElement('div');
const player = $(videoAdvancedTemplate(options))[0];
element.appendChild(player);
const vid = player.querySelector('video');
const msgError = element.querySelector('.video-advanced-error');
const sourceElements = $(_.compact(options.sources.map(v => {
if (!vid.canPlayType(v.type)) return null;
const source = document.createElement('source');
source.src = v.source;
source.type = v.type;
if (v.reverse) source.dataset.reverse = v.reverse;
return source;
}))).appendTo(vid).get();
if (!sourceElements.length) {
_.defer(sourceErrorFallback);
return element;
}
function setAdvancedControls() {
function reverse() {
time = vid.duration - vid.currentTime;
for (const v of vid.querySelectorAll('source')) {
[v.src, v.dataset.reverse] = [v.dataset.reverse, v.src];
}
vid.load();
vid.play();
player.classList.toggle('reversed');
}
const ctrlContainer = player.querySelector('.video-advanced-controls');
const ctrlReverse = ctrlContainer.querySelector('.video-advanced-reverse');
const ctrlTogglePause = ctrlContainer.querySelector('.video-advanced-toggle-pause');
const ctrlSpeedDecrease = ctrlContainer.querySelector('.video-advanced-speed-decrease');
const ctrlSpeedIncrease = ctrlContainer.querySelector('.video-advanced-speed-increase');
const ctrlTimeDecrease = ctrlContainer.querySelector('.video-advanced-time-decrease');
const ctrlTimeIncrease = ctrlContainer.querySelector('.video-advanced-time-increase');
const progress = player.querySelector('.video-advanced-progress');
const indicatorPosition = progress.querySelector('.video-advanced-position');
const ctrlPosition = progress.querySelector('.video-advanced-position-thumb');
const msgSpeed = ctrlContainer.querySelector('.video-advanced-speed');
const msgTime = ctrlContainer.querySelector('.video-advanced-time');
ctrlTogglePause.addEventListener('click', () => { vid[vid.paused ? 'play' : 'pause'](); });
if (ctrlReverse) ctrlReverse.addEventListener('click', reverse);
ctrlSpeedDecrease.addEventListener('click', () => { vid.playbackRate /= 1.1; });
ctrlSpeedIncrease.addEventListener('click', () => { vid.playbackRate *= 1.1; });
ctrlTimeDecrease.addEventListener('click', () => { vid.currentTime -= 1 / frameRate; });
ctrlTimeIncrease.addEventListener('click', () => { vid.currentTime += 1 / frameRate; });
vid.addEventListener('ratechange', () => { msgSpeed.innerHTML = `${vid.playbackRate.toFixed(2).replace('.', '.<wbr>')}x`; });
vid.addEventListener('timeupdate', () => {
indicatorPosition.style.left = `${(vid.currentTime / vid.duration) * 100}%`;
msgTime.innerHTML = `${vid.currentTime.toFixed(2).replace('.', '.<wbr>')}s`;
});
progress.addEventListener('mousemove', e => {
let left = e.offsetX;
if (e.target === ctrlPosition) { left += e.target.offsetLeft; }
ctrlPosition.style.left = `${left}px`;
if (e.buttons === 1 /* left mouse button */) ctrlPosition.click();
});
ctrlPosition.addEventListener('click', e => {
const percentage = (e.target.offsetLeft + e.target.clientWidth / 2) / progress.clientWidth;
vid.currentTime = vid.duration * percentage;
});
}
if (advancedControls) {
Promise.all([waitForEvent(player, 'mouseenter'), waitForEvent(vid, 'loadedmetadata')])
.then(setAdvancedControls);
}
function sourceErrorFallback() {
if (fallback) {
$(element).replaceWith(generateImage({
...options,
src: fallback,
}));
} else {
msgError.hidden = false;
}
}
const lastSource = sourceElements[sourceElements.length - 1];
lastSource.addEventListener('error', sourceErrorFallback);
vid.addEventListener('pause', () => { player.classList.remove('playing'); });
vid.addEventListener('play', () => { player.classList.add('playing'); });
vid.addEventListener('loadedmetadata', () => { if (time !== vid.currentTime) vid.currentTime = time; });
vid.playbackRate = playbackRate;
// Ignore events which might be meant for controls
vid.addEventListener('mousedown', e => {
if (vid.hasAttribute('controls')) {
const { height, top } = vid.getBoundingClientRect();
let controlsBottomHeight = 0;
if (process.env.BUILD_TARGET === 'edge') controlsBottomHeight = 0.5 * height;
if (process.env.BUILD_TARGET === 'firefox') controlsBottomHeight = 40;
if ((height - controlsBottomHeight) < (e.clientY - top)) {
e.stopImmediatePropagation();
}
}
});
element.collapse = () => {
// Video is auto-paused when detached from DOM
if (!document.body.contains(vid)) return;
autoplay = !vid.paused;
if (!vid.paused) vid.pause();
time = vid.currentTime;
vid.setAttribute('src', ''); // vid.src has precedence over any child source element
vid.load();
};
element.expand = () => {
if (vid.hasAttribute('src')) {
vid.removeAttribute('src');
vid.load();
}
if (autoplay) vid.play();
};
element.emitResizeEvent = () => { vid.dispatchEvent(new CustomEvent('mediaResize', { bubbles: true })); };
element.ready = Promise.race([waitForEvent(vid, 'suspend'), waitForEvent(lastSource, 'error')]);
vid.addEventListener('loadedmetadata', element.emitResizeEvent);
setMediaMaxSize(vid);
makeMediaZoomable(vid);
setMediaControls(vid);
makeMediaMovable(player);
keepMediaVisible(player);
makeMediaIndependentOnResize(element, player);
return element;
}
export function moveMedia(ele, deltaX, deltaY, source = resizeSources.USER_MOVE) {
ele.style.marginLeft = `${((parseFloat(ele.style.marginLeft, 10) || 0) + deltaX).toFixed(2)}px`;
ele.style.marginTop = `${((parseFloat(ele.style.marginTop, 10) || 0) + deltaY).toFixed(2)}px`;
ele.dispatchEvent(new CustomEvent('mediaResize', { bubbles: true, detail: source }));
}
export function resizeMedia(ele, newWidth) {
ele.style.width = `${newWidth}px`;
ele.style.maxWidth = `${newWidth}px`;
ele.style.maxHeight = '';
ele.style.height = 'auto';
ele.dispatchEvent(new CustomEvent('mediaResize', { bubbles: true }));
}
function rotateMedia(ele, rotationState) {
ele.style.transformOrigin = 'top left';
// apply rotation
switch (positiveModulo(rotationState, 4)) {
case 0:
ele.style.transform = '';
break;
case 1:
ele.style.transform = 'rotate(90deg) translateY(-100%)';
break;
case 2:
ele.style.transform = 'rotate(180deg) translate(-100%, -100%)';
break;
case 3:
ele.style.transform = 'rotate(270deg) translateX(-100%)';
break;
default:
break;
}
ele.dispatchEvent(new CustomEvent('mediaResize', { bubbles: true }));
}
|
gpl-3.0
|
isuruf/piranha
|
pyranha/expose_polynomials_4.cpp
|
1351
|
/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com)
This file is part of the Piranha library.
The Piranha library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* 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.
or both in parallel, as here.
The Piranha library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the Piranha library. If not,
see https://www.gnu.org/licenses/. */
#include "python_includes.hpp"
#include "../src/polynomial.hpp"
#include "expose_polynomials.hpp"
#include "expose_utils.hpp"
#include "polynomial_descriptor.hpp"
namespace pyranha
{
void expose_polynomials_4()
{
series_exposer<piranha::polynomial,polynomial_descriptor,4u,5u,poly_custom_hook<polynomial_descriptor>> poly_exposer;
}
}
|
gpl-3.0
|
waikato-datamining/adams-base
|
adams-core/src/test/java/adams/flow/sink/NullTest.java
|
2774
|
/*
* 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/>.
*/
/*
* NullTest.java
* Copyright (C) 2010 University of Waikato, Hamilton, New Zealand
*/
package adams.flow.sink;
import junit.framework.Test;
import junit.framework.TestSuite;
import adams.core.base.BaseString;
import adams.env.Environment;
import adams.flow.AbstractFlowTest;
import adams.flow.control.Flow;
import adams.flow.core.Actor;
import adams.flow.source.StringConstants;
/**
* Tests the Null sink.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class NullTest
extends AbstractFlowTest {
/**
* Initializes the test.
*
* @param name the name of the test
*/
public NullTest(String name) {
super(name);
}
/**
* Used to create an instance of a specific actor.
*
* @return a suitably configured <code>Actor</code> value
*/
public Actor getActor() {
StringConstants ids = new StringConstants();
ids.setStrings(new BaseString[]{
new BaseString("1"),
new BaseString("2"),
new BaseString("3"),
new BaseString("4"),
new BaseString("5"),
new BaseString("6"),
new BaseString("7"),
new BaseString("8"),
new BaseString("9"),
new BaseString("10"),
new BaseString("11"),
new BaseString("12"),
new BaseString("13"),
new BaseString("14"),
new BaseString("15"),
new BaseString("16"),
new BaseString("17"),
new BaseString("18"),
new BaseString("19"),
new BaseString("20"),
new BaseString("21"),
new BaseString("22"),
new BaseString("23"),
new BaseString("24"),
new BaseString("25"),
new BaseString("26"),
new BaseString("27"),
new BaseString("28"),
new BaseString("29"),
new BaseString("30")
});
Null d = new Null();
Flow flow = new Flow();
flow.setActors(new Actor[]{ids, d});
return flow;
}
/**
* Returns a test suite.
*
* @return the test suite
*/
public static Test suite() {
return new TestSuite(NullTest.class);
}
/**
* Runs the test from commandline.
*
* @param args ignored
*/
public static void main(String[] args) {
Environment.setEnvironmentClass(Environment.class);
runTest(suite());
}
}
|
gpl-3.0
|
protonsint/geosdiera
|
web/src/main/java/it/geosdi/era/client/openlayers/layers/Layer.java
|
2126
|
/*
* GeoSDI ERA - The new era of webGIS
* http://code.google.com/p/geosdiera/
* ====================================================================
*
* Copyright (C) 2008-2009 GeoSDI Group (CNR IMAA).
*
* 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.
*
* ====================================================================
*
* This software consists of voluntary contributions made by developers
* of GeoSDI Group. For more information on GeoSDI, please see
* <http://www.geosdi.org/>.
*
*/
package it.geosdi.era.client.openlayers.layers;
import com.google.gwt.core.client.JavaScriptObject;
/**
* @author Giuseppe La Scaleia
* @author Francesco Izzi
*/
public abstract class Layer {
private JavaScriptObject obj;
public Layer(JavaScriptObject o) {
this.obj = o;
}
public JavaScriptObject getJsObject() {
return obj;
}
public void setOpacity(float opacity) {
_setOpacity(getJsObject(), opacity);
}
private static native void _setOpacity(JavaScriptObject obj, float opacity) /*-{
obj.setOpacity(opacity);
}-*/;
public void setVisibility(boolean isVisibility) {
_setVisibility(getJsObject(), isVisibility);
}
private static native void _setVisibility(JavaScriptObject obj,
boolean isVisibility) /*-{
obj.setVisibility(isVisibility);
}-*/;
public void redraw(boolean isRedraw) {
_redraw(getJsObject(), isRedraw);
}
private static native void _redraw(JavaScriptObject obj, boolean isRedraw) /*-{
obj.redraw(isRedraw);
}-*/;
}
|
gpl-3.0
|
giofrida/Hisense-enhancements
|
UI/hisenseUI/modulePages/boe/boeNetSetWPS.js
|
7779
|
/**
* Created by xuehongfeng on 2015/11/16.
*/
function getboeNetSetWPSPageData(opt){
opt.CaE = [
{
"id":"boeNetSetWPSCodeTitle",
"description":"PBCÌáʾÐÅÏ¢",
"CaEType":"span"
},
{
"id":"boeNetSetWPSIcon",
"description":"PBC img",
"CaEType":"img"
},
{
"id":"boeNetSetWPSProTitle",
"description":"PBC Á¬½ÓÌáʾÐÅÏ¢",
"CaEType":"span"
},
{
"id":"boeNetSetWPSConnProgressBar",
"description":"PBC Á¬½Ó½ø¶È",
"CaEType":"ProgressBar",
"CaE":[
{
"id": "boeNetSetWPSConnProgressing",
"description": "½ø¶ÈÌõ",
"CaEType": "div"
}
],
"classes":{
"normal":"boeWPSProgressFrame"
},
"ProgressBarConfig": {
PBProcessId: "boeNetSetWPSConnProgressing",//½ø¶ÈÌõµÄ½ø³Ìid
ShowTextId: "",//ÔÚ½ø¶ÈÌõÅÔ±ßÓðٷÖÊý»òÕß·ÖÊýÏÔʾ½ø¶ÈÓë·ñ, ĬÈÏΪ¿ÕÊDz»ÏÔʾ, ÓеÄʱºòÐèÒª½øÐÐÌṩid
ShowTextIsMoved: false,//ÏÔʾֵ±êÇ©ÊÇ·ñËæ×Žø¶ÈÌõÒÆ¶¯
PBType: "direction",//½ø¶ÈÀàÐÍ, ¡°animation¡±¶¯»Ä£Ê½ ¡°direction¡±Ö±½Óģʽ
// StepDuration: 20,// settimeoutµÄʱ¼ä²ÎÊý, µ¥Î»ms ±íʾÿÔö¼Ó1%dµÄʱ¼ä¼ä¸ô
// MinValue: 0, //×îСֵ, ²»É趨µÄ»°Ä¬ÈÏΪ0£»
// MaxValue: 100, //×î´óÖµ¡£²»É趨ĬÈÏΪ100£»
DefaultValue: 0,//ĬÈÏÖµ
Width: 840,//½ø¶ÈÌõ×Ü¿í¶È
TextFormat: "per",// ShowTextµÄÏÔʾÐÎʽ, ¡°per¡±±íʾ°Ù·ÖÊý, ¡°fra¡±±íʾ·ÖÊý, ÆäËûÔòΪ¡°×Ô¶¨Ò庯Êý¡±
CompleteCallBack: null//Èç¹û´ïµ½ÉèÖÃֵʱµÄ»Øµ÷º¯Êý¡£
}
},
{
"id":"boeNetSetWPSCancelBtn",
"description":"È¡ÏûÁ¬½Ó°´Å¥",
"CaEType":"div",
"classes":{
"normal":"boeWifiSetWPSCancleBtnNormal","focus":"boeWifiSetWPSCancleBtnFocus"
},
"handler":{
"aftEnterHandler":"boeNetSetWPSCancelHandle",
"befRightHandler":"boeWifiSetWPSPageTonNextPage"
}
}
];
boeInitSetNetWPSDialog();
return boeNetSetWPSPageData;
}
var boeNetSetWPSPageData={
//"settingNetSetPBCHeadTitle":{"Data":"PBC"},
"boeNetSetWPSCodeTitle":{"Data":"Press the WPS button on your router; this is marked with WPS or the following symbol:"},
"boeNetSetWPSIcon":{"Data":"img/PBC-WPS.png"},
"boeNetSetWPSProTitle":{"Data":"The configuration takes approximately 2 minutes"},
"boeNetSetWPSConnProgressBar":{
"Data":{},
"DefaultValue":0
},
"boeNetSetWPSCancelBtn":{"Data":"Cancel"},
"operateData":{
"connPercent":10,
"PBCConnTimer":0
},
"langData":{
"PBC":["PBC"],
"Press the WPS button on your router; this is marked with WPS or the following symbol:":["Press the WPS button on your router; this is marked with WPS or the following symbol:"],
"The configuration takes approximately 2 minutes":["The configuration takes approximately 2 minutes"],
"Cancel":["Cancel"]
},
rewrite:"boeRewriteNetSetWPS"
}
/*******************************************************************
name:boeInitSetNetWPSDialog
description:³õʼ»¯PINÁ¬½ÓÒ³Ãæ
input:
output:
return
*******************************************************************/
function boeInitSetNetWPSDialog(){
try{
var data = boeNetSetWPSPageData;
data.operateData.connPercent = 0;
data.operateData.PBCConnTimer = 0;
}catch (ex){
debugPrint("boeInitSetNetWPSDialog:"+ex.message,DebugLevel.ERROR);
}
}
function boeRewriteNetSetWPS(data){
try{
data.boeNetSetWPSConnProgressBar.DefaultValue = data.operateData.connPercent;
}catch (ex){
debugPrint("boeRewriteNetSetWPS:"+ex.message,DebugLevel.ERROR);
}
}
/*******************************************************************
name:boeNetSetWPSCancelHandle
description:È¡ÏûpinÁ¬½Ó
input:
output:
return
*******************************************************************/
function boeNetSetWPSCancelHandle(){
try{
var data = boeNetSetWPSPageData;
clearInterval(data.operateData.PBCConnTimer);
hiWebOsFrame.boe_NetworkWifiWPS.close();
hiWebOsFrame.boe_NetworkWifiSetPage.open();
hiWebOsFrame.boe_NetworkWifiSetPage.hiFocus();
hiWebOsFrame.boe_NetworkWifiWPS.destroy();
}catch (ex){
debugPrint("boeNetSetWPSCancelHandle:"+ex.message,DebugLevel.ERROR);
}
}
function boeNetSetWPSTimerOutHandle(){
var data = boeNetSetWPSPageData;
debugPrint("boeNetSetWPSTimerOutHandle:"+data.operateData.connPercent,DebugLevel.ALWAYS);
if(data.operateData.connPercent >= 100){
boeNetSetWPSToResDialog();
}else{
data.operateData.connPercent = data.operateData.connPercent+1;
hiWebOsFrame.boe_NetworkWifiWPS.rewriteDataOnly();
}
}
function boeNetSetWPSToResDialog(){
try{
var data = boeNetSetWPSPageData;
clearInterval(data.operateData.PBCConnTimer);
hiWebOsFrame.boe_netbg_page_id.hiBlur();
hiWebOsFrame.createPage('boe_NetworkConnResDialog',null, null, null,function(a){
hiWebOsFrame.boe_NetworkWifiWPS.close();
a.open();
a.hiFocus();
hiWebOsFrame.boe_NetworkConnResDialog = a;
hiWebOsFrame.boe_NetworkWifiWPS.destroy();
});
}catch (ex){
debugPrint("boeNetSetWPSToResDialog:"+ex.message,DebugLevel.ERROR);
}
}
function boeNetSetWPSConnStateCallBack(state){
debugPrint("boeNetSetWPSConnStateCallBack:state="+state,DebugLevel.ERROR);
switch (state){
case 0:
var networkAvailable = model.network.getEnumNetworkAvailable();
debugPrint("boeNetSetWPSConnStateCallBack:networkAailable="+networkAvailable,DebugLevel.ERROR);
boeNetSetWPSToResDialog();
break;
case 1://applying setting
case 2://connecting
break;
default :
break;
}
}
/*******************************************************************
name:wizardNetSetNetTypeListDialogEscHandle
description:·µ»Ø¼ü´¦Àí
input:
output:
return
*******************************************************************/
function boeNetSetWPSEscHandle(){
boeNetSetWPSCancelHandle();
}
function boeNetSetWPSPageOnClose(){
var data = boeNetSetWPSPageData;
data.operateData.PBCConnTimer = setInterval(boeNetSetWPSTimerOutHandle,1200);
if(tv == true){
model.network.onEnumLinkChaged = boeNetSetWPSConnStateCallBack;
model.network.WpsConnectStart(1);
}
}
function boeWifiSetWPSPageTonNextPage(){
hiWebOsFrame.boe_netbg_page_id.destroy();
hiWebOsFrame.boe_NetworkWifiWPS.destroy();
hiWebOsFrame.createPage('boe_complete_page_id',null, null, null,function(b){
hiWebOsFrame.boe_complete_page_id = b;
b.open();
b.hiFocus();
});
}
function boeNetSetWPSPageOnOpen(){
var data = boeNetSetWPSPageData;
data.operateData.PBCConnTimer = setInterval(boeNetSetWPSTimerOutHandle,1200);
if(tv == true){
model.network.onEnumLinkChaged = boeNetSetWPSConnStateCallBack;
model.network.WpsConnectStart(1);
}
}
function boeNetSetWPSPageOnDestroy(){
try{
var data = boeNetSetWPSPageData;
clearInterval(data.operateData.PBCConnTimer);
hiWebOsFrame.boe_NetworkWifiWPS = null;
if(tv == true){
model.network.onEnumLinkChaged = null;
}
}catch (ex){
debugE("boe_NetworkWifiWPSOnDestroy:"+ex.message);
}
}
|
gpl-3.0
|
budkit/budkit-framework
|
src/Budkit/Routing/Factory.php
|
2242
|
<?php
namespace Budkit\Routing;
class Factory
{
/**
*
* The route class to create.
*
* @param string
*
*/
protected $class = 'Budkit\Routing\Route';
/**
*
* A reusable Regex object.
*
* @param Regex
*
*/
protected $regex;
/**
*
* The default route specification.
*
* @var array
*
*/
protected $spec = [
'tokens' => [],
'server' => [],
'method' => [],
'accept' => [],
'values' => [],
'secure' => null,
'wildcard' => null,
'routable' => true,
'isMatch' => null,
'generate' => null,
'namePrefix' => null,
'pathPrefix' => null,
];
/**
*
* Constructor.
*
* @param string $class The route class to create.
*
*/
public function __construct($class = 'Budkit\Routing\Route')
{
$this->class = $class;
$this->regex = new Regex;
}
/**
*
* Returns a new instance of the route class.
*
* @param string $path The path for the route.
*
* @param string $name The name for the route.
*
* @param array $spec The spec for the new instance.
*
* @return Route
*
*/
public function newInstance($path, $name = null, array $spec = [])
{
$spec = array_merge($this->spec, $spec);
//var_dump($path, $name, $spec);
$path = $spec['pathPrefix'] . $path;
$name = ($spec['namePrefix'] && $name)
? $spec['namePrefix'] . '.' . $name
: $name;
$class = $this->class;
$route = new $class($path, $name, [], new Regex);
$route->addTokens($spec['tokens']);
$route->addServer($spec['server']);
$route->addMethod($spec['method']);
$route->addAccept($spec['accept']);
$route->addValues($spec['values']);
$route->setSecure($spec['secure']);
$route->setWildcard($spec['wildcard']);
$route->setRoutable($spec['routable']);
$route->setIsMatchCallable($spec['isMatch']);
$route->setGenerateCallable($spec['generate']);
//var_dump($route);
return $route;
}
}
|
gpl-3.0
|
Lumeer/web-ui
|
src/app/shared/blockly/blockly-editor/blocks/iso-to-ms-blockly-component.ts
|
2339
|
/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {BlocklyComponent} from './blockly-component';
import {BlocklyUtils, MasterBlockType} from '../blockly-utils';
import {COLOR_PINK} from '../../../../core/constants';
declare var Blockly: any;
export class IsoToMsBlocklyComponent extends BlocklyComponent {
private tooltip: string;
public constructor(public blocklyUtils: BlocklyUtils) {
super(blocklyUtils);
this.tooltip = $localize`:@@blockly.tooltip.isoToMsBlock:Converts date in an ISO string to milliseconds since epoch (Unix time).`;
}
public getVisibility(): MasterBlockType[] {
return [MasterBlockType.Rule, MasterBlockType.Link, MasterBlockType.Function];
}
public registerBlock(workspace: any) {
const this_ = this;
Blockly.Blocks[BlocklyUtils.ISO_TO_MS] = {
init: function () {
this.jsonInit({
type: BlocklyUtils.ISO_TO_MS,
message0: '%{BKY_BLOCK_ISO_TO_MILLIS}', // ISO to millis %1
args0: [
{
type: 'input_value',
name: 'ISO',
},
],
output: '',
colour: COLOR_PINK,
tooltip: this_.tooltip,
helpUrl: '',
});
},
};
Blockly.JavaScript[BlocklyUtils.ISO_TO_MS] = function (block) {
const argument0 = Blockly.JavaScript.valueToCode(block, 'ISO', Blockly.JavaScript.ORDER_ASSIGNMENT) || null;
if (!argument0) {
return '';
}
const code = `(new Date(${argument0})).getTime()`;
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
};
}
}
|
gpl-3.0
|
GuillaumeDD/scala99problems
|
src/main/scala/list/P22/P22.scala
|
1410
|
/*******************************************************************************
* Copyright (c) 2013 Guillaume DUBUISSON DUPLESSIS <guillaume.dubuisson_duplessis@insa-rouen.fr>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Guillaume DUBUISSON DUPLESSIS <guillaume.dubuisson_duplessis@insa-rouen.fr> - initial API and implementation
******************************************************************************/
package list.P22
import util.ExerciseTemplate
trait P22 extends ExerciseTemplate {
/*
P22 (*) Create a list containing all integers within a given range.
Example:
scala> range(4, 9)
res0: List[Int] = List(4, 5, 6, 7, 8, 9)
*/
val name = "P22 (Create a list containing all integers within a given range)"
def range(min: Int, max: Int): List[Int]
test("Invoking range with min=max gives a list with one element") {
assert(range(42, 42) == List(42))
}
test("Invoking range with min > max gives an IllegalArgumentException") {
intercept[IllegalArgumentException] {
range(5, 0)
}
}
test("Invoking range should produce an ordered list of element between min and max") {
assert(range(4, 9) == List(4, 5, 6, 7, 8, 9))
}
}
|
gpl-3.0
|
fiendishly/rsbot
|
scripts/FroltAnyChopper.java
|
9039
|
import java.awt.*;
import java.util.*;
import org.rsbot.script.*;
import org.rsbot.bot.*;
import org.rsbot.script.wrappers.*;
import org.rsbot.script.Skills;
import org.rsbot.event.listeners.*;
import org.rsbot.event.events.*;
import org.rsbot.util.*;
@ScriptManifest(authors = {"Frolt"}, category = "Woodcutting", name = "Frolt Any Chopper", version = 1.1, description = ("<html><head>" +
"<style type=\"text/css\">body {background:url(\"\") no-repeat}</style>"
+ "<html>\n"
+ "<b><center><h2>Frolt Any Chopper (1.1)</h2></center></b>"
+ "<font size=\"3\">"
+ "<b><u>Information:</u><br></b>"
+ "<b>This script is designed to just improve your woodcutting skill no matter what tree. If you just want your bot to woodcut then this script is it. This script will chop the supported logs shown below and then drop them. There is paint on this script so it will keep you updated on what is going on with the script. This will count the logs as well no matter what log it is. This script also supports almost all axes. Please look in under the supported trees and axes to see what is and what is not supported.<br><br></b>"
+ "<b><u>Select Tree Types:</u><br></b>"
+ "<select name=\"tree\"><option>Normal</option><option>Oak</option><option>Willow</option></select>"
+ "<br>"
+ "<b><u>Supported Axe Types:</u><br></b>"
+ "<b>- Bronze hatchet<br></b>"
+ "<b>- Iron hatchet<br></b>"
+ "<b>- Steel hatchet<br></b>"
+ "<b>- Black hatchet<br></b>"
+ "<b>- Mithril hatchet<br></b>"
+ "<b>- Adamant hatchet<br></b>"
+ "<b>- Rune hatchet<br></b>"
+ "<b>- Dragon hatchet<br></b>"
+ "</body></html>"))
public class FroltAnyChopper extends Script implements PaintListener, ServerMessageListener {
public int[] hatchets = {1351, 1349, 1353, 1361, 1355, 1357, 1359, 6739, 13470};
private long startTime;
private int WoodcuttingSkillIndex1, WoodcuttingStartingXP;
public String status = "Starting";
int logs = 0;
int loads = 0;
int levels = 0;
public int[] toChop;
public int[] NormalTree = {5004, 5005, 5045, 3879, 3881, 3882, 3883,
3885, 3886, 3887, 3888, 3889, 3890, 3891, 3892, 3893, 3928, 3967,
3968, 4048, 4049, 4050, 4051, 4052, 4053, 4054, 3033, 3034, 3035,
3036, 2409, 2447, 2448, 1330, 1331, 1332, 1310, 1305, 1304, 1303,
1301, 1276, 1277, 1278, 1279, 1280, 8742, 8743, 8973, 8974, 1315,
1316};
public int[] OakTree = {1281, 3037, 8462, 8463, 8464, 8465, 8466, 8467};
public int[] WillowTree = {1308, 5551, 5552, 5553, 8481, 8482, 8483,
8484, 8485, 8486, 8487, 8488};
protected int getMouseSpeed() {
return 5;
}
public boolean onStart(Map<String, String> args) {
log(".");
log("..");
log("...");
log("....");
log(".....");
log("Starting Frolt Any Chopper!");
startTime = System.currentTimeMillis();
WoodcuttingSkillIndex1 = Skills.getStatIndex("woodcutting");
WoodcuttingStartingXP = skills.getCurrentSkillExp(WoodcuttingSkillIndex1);
if (args.get("tree").equals("Normal"))
toChop = NormalTree;
else if (args.get("tree").equals("Oak"))
toChop = OakTree;
else if (args.get("tree").equals("Willow"))
toChop = WillowTree;
else
return false;
return true;
}
public void onFinish() {
ScreenshotUtil.takeScreenshot(true);
Bot.getEventManager().removeListener(PaintListener.class, this);
}
public int antiBan() {
status = "AntiBan activated";
final int gamble = random(1, 15);
final int x = random(0, 750);
final int y = random(0, 500);
final int xx = random(554, 710);
final int yy = random(230, 444);
final int screenx = random(1, 510);
final int screeny = random(1, 450);
switch (gamble) {
case 1:
return random(500, 750);
case 2:
moveMouse(x, y);
return random(500, 750);
case 3:
openTab(Constants.TAB_INVENTORY);
return random(200, 400);
case 4:
if (getMyPlayer().isMoving()) {
return random(750, 1000);
}
case 5:
moveMouse(x, y);
int checkTime = 0;
long lastCheck = 0;
if (System.currentTimeMillis() - lastCheck >= checkTime) {
lastCheck = System.currentTimeMillis();
checkTime = random(60000, 180000);
}
case 6:
if (getCurrentTab() != Constants.TAB_STATS) {
openTab(Constants.TAB_STATS);
moveMouse(xx, yy);
return random(500, 800);
}
case 7:
if (random(1, 8) == 2) {
int angle = getCameraAngle() + random(-90, 90);
if (angle < 0) {
angle = 0;
}
if (angle > 359) {
angle = 0;
}
setCameraRotation(angle);
}
return random(500, 750);
case 8:
moveMouse(screenx, screeny);
return random(100, 320);
case 9:
moveMouse(screenx, screeny);
return random(100, 320);
case 10:
randomTab();
wait(random(4000, 6000));
return random(120, 250);
case 11:
wait(random(4000, 6000));
moveMouse(screenx, screeny);
return random(100, 320);
case 12:
wait(random(4000, 6000));
moveMouse(screenx, screeny);
return random(100, 320);
case 13:
wait(random(4500, 7000));
moveMouse(screenx, screeny);
return random(100, 320);
}
return random(500, 750);
}
public int randomTab() {
final int random1 = random(1, 23);
switch (random1) {
case 1:
openTab(Constants.TAB_STATS);
return random(100, 500);
case 2:
openTab(Constants.TAB_ATTACK);
return random(100, 500);
case 3:
openTab(Constants.TAB_QUESTS);
return random(100, 500);
case 4:
openTab(Constants.TAB_EQUIPMENT);
return random(100, 500);
case 5:
openTab(Constants.TAB_INVENTORY);
return random(100, 500);
case 6:
openTab(Constants.TAB_PRAYER);
return random(100, 500);
case 7:
openTab(Constants.TAB_MAGIC);
return random(100, 500);
case 8:
openTab(Constants.TAB_SUMMONING);
return random(100, 500);
case 9:
openTab(Constants.TAB_FRIENDS);
return random(100, 500);
case 10:
openTab(Constants.TAB_IGNORE);
return random(100, 500);
case 11:
openTab(Constants.TAB_CLAN);
return random(100, 500);
case 12:
openTab(Constants.TAB_CONTROLS);
return random(100, 500);
case 13:
openTab(Constants.TAB_MUSIC);
return random(100, 500);
case 14:
openTab(Constants.TAB_OPTIONS);
return random(100, 500);
}
return random(100, 300);
}
public void onRepaint(Graphics g) {
if (isLoggedIn()) {
long millis = System.currentTimeMillis() - startTime;
long hours = millis / (1000 * 60 * 60);
millis -= hours * (1000 * 60 * 60);
long minutes = millis / (1000 * 60);
millis -= minutes * (1000 * 60);
long seconds = millis / 1000;
if (getCurrentTab() == TAB_INVENTORY) {
g.setColor(new Color(0, 0, 0, 175));
g.fillRoundRect(555, 210, 175, 250, 10, 10);
g.setColor(Color.white);
g.drawString("Frolt Any Chopper:", 561, 225);
g.drawString("Version: 1.1", 561, 235);
g.drawString("Current Status:", 561, 255);
g.drawString("" + status + ".", 561, 265);
g.drawString("Current Chopping Log:", 561, 285);
g.drawString("Logs Chopped: " + logs, 561, 295);
g.drawString("Loads: " + loads, 561, 305);
g.drawString("Experience/Level Log:", 561, 325);
g.drawString("Levels Gained: " + levels, 561, 335);
g.drawString("XP Gained: " + (skills.getCurrentSkillExp(WoodcuttingSkillIndex1) - WoodcuttingStartingXP), 561, 345);
g.drawString("Current Level: " + skills.getCurrentSkillLevel(STAT_WOODCUTTING), 561, 355);
g.drawString("Percent Till Next Level: " + skills.getPercentToNextLevel(STAT_WOODCUTTING) + "%", 561, 365);
g.drawString("XP Untill Level: " + skills.getXPToNextLevel(STAT_WOODCUTTING), 561, 375);
g.drawString("Time Running:", 561, 395);
g.drawString("" + hours + ":" + minutes + ":" + seconds + "", 561, 405);
}
Point p = getMouseLocation();
long timeSince = Bot.getClient().getMouse().getMousePressTime();
if (timeSince > System.currentTimeMillis() - 500)
g.setColor(new Color(255, 255, 255, 125));
else
g.setColor(new Color(0, 0, 0, 125));
g.drawLine(0, p.y, 762, p.y);
g.drawLine(p.x, 0, p.x, 500);
}
}
public void serverMessageRecieved(final ServerMessageEvent arg0) {
String serverString = arg0.getMessage();
if (serverString.contains("You get some")) {
logs++;
}
if (serverString.contains("Your inventory is too full to hold")) {
loads++;
}
if (serverString.contains("You've just advanced a Woodcutting level!")) {
levels++;
}
}
public boolean chopping() {
if (!isIdle())
return true;
RSObject Tree = getNearestObjectByID(toChop);
if (Tree == null)
return false;
atObject(Tree, "hop");
return true;
}
public int loop() {
setCameraAltitude(true);
if (getEnergy() > random(30, 60)) {
setRun(true);
}
if (getMyPlayer().getAnimation() != -1) {
return random(800, 2000);
}
if (isInventoryFull()) {
status = "Inventory is full";
dropAllExcept(true, hatchets);
} else {
chopping();
status = "Cutting tree";
wait(2000);
antiBan();
wait(2000);
}
return 300;
}
}
|
gpl-3.0
|
j9recurses/whirld
|
vendor/assets/components/leaflet-illustrate/src/edit/handles/L.Illustrate.RotateHandle.js
|
1968
|
L.Illustrate.RotateHandle = L.Illustrate.EditHandle.extend({
options: {
TYPE: 'rotate'
},
initialize: function(shape, options) {
L.Illustrate.EditHandle.prototype.initialize.call(this, shape, options);
this._createPointer();
},
onAdd: function(map) {
L.Illustrate.EditHandle.prototype.onAdd.call(this, map);
this._map.addLayer(this._pointer);
},
onRemove: function(map) {
this._map.removeLayer(this._pointer);
L.Illustrate.EditHandle.prototype.onRemove.call(this, map);
},
_onHandleDrag: function(event) {
var handle = event.target,
latlng = handle.getLatLng(),
center = this._handled.getLatLng(),
point = this._map.latLngToLayerPoint(latlng).subtract(this._map.latLngToLayerPoint(center)),
theta;
if (point.y > 0) {
theta = Math.PI - Math.atan(point.x / point.y);
} else {
theta = - Math.atan(point.x / point.y);
}
/* rotate the textbox */
this._handled.setRotation(theta);
},
updateHandle: function() {
this._handleOffset = new L.Point(0, -this._handled.getSize().y);
this._updatePointer();
L.Illustrate.EditHandle.prototype.updateHandle.call(this);
},
_createPointer: function() {
var options = {
color: this._handled.options.borderColor,
weight: Math.round(this._handled.options.borderWidth)
};
this._pointerStart = this._handleOffset.multiplyBy(0.5);
this._pointer = new L.Illustrate.Pointer(this._handled.getLatLng(), [
this._pointerStart,
this._handleOffset
], options);
this._handled.on({ 'update': this._updatePointer }, this);
},
_updatePointer: function() {
var map = this._handled._map,
center = this._handled.getLatLng(),
origin = map.latLngToLayerPoint(center);
this._pointerStart = this._handleOffset.multiplyBy(0.5);
this._pointer.setLatLng(center);
this._pointer.setPoints([
this._textboxCoordsToLayerPoint(this._pointerStart).subtract(origin),
this._textboxCoordsToLayerPoint(this._handleOffset).subtract(origin)
]);
}
});
|
gpl-3.0
|
isaac-benson-powell/ibp_software
|
projects/language/test/test_io/for_ag_tests/input/parse_tree_nodes/Node_Function_Call/expect_parser_pass/function_call_with_one_argument/expected_cpp_translation/function_call_with_one_argument.cpp
|
466
|
#include "function_call_with_one_argument.h"
/*!
* \brief code_being_tested
*
* The code in this function is the scenario being tested.
*
* \return ibp::Integer
*/
ibp::Integer
code_being_tested()
{
ibp::Integer num = bar( 4_i );
// OK to ignore return value.
return num;
}
/*!
* \brief bar
*
* Mandatory function comment.
*
* \param ibp::Integer x
*
* \return ibp::Integer
*/
ibp::Integer
bar( ibp::Integer x )
{
return x;
}
|
gpl-3.0
|
VladKha/CodeWars
|
7 kyu/Alphabet symmetry/solve.py
|
156
|
from string import ascii_lowercase as alphabet
def solve(arr):
return [sum(c == alphabet[i] for i,c in enumerate(word[:26].lower())) for word in arr]
|
gpl-3.0
|
eafkhami/cbrain
|
BrainPortal/lib/scir_pbs.rb
|
4849
|
#
# CBRAIN Project
#
# Copyright (C) 2008-2012
# The Royal Institution for the Advancement of Learning
# McGill University
#
# 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 is a replacement for the drmaa.rb library; this particular subclass
# of class Scir implements the PBS interface.
#
# Original author: Pierre Rioux
class ScirPbs < Scir
Revision_info=CbrainFileRevision[__FILE__] #:nodoc:
class Session < Scir::Session #:nodoc:
def update_job_info_cache
out, err = bash_this_and_capture_out_err("qstat -f")
raise "Cannot get output of 'qstat -f' ?!?" if out.blank? && ! err.blank?
jid = 'Dummy'
@job_info_cache = {}
out.split(/\s*\n\s*/).each do |line|
line.force_encoding('ASCII-8BIT') # some pbs 'qstat' commands output junk binary data!
if line =~ /^Job\s+id\s*:\s*(\S+)/i
jid = Regexp.last_match[1]
if jid =~ /^(\d+)/
jid = Regexp.last_match[1]
end
next
end
next unless line =~ /^\s*job_state\s*=\s*(\S+)/i
state = statestring_to_stateconst(Regexp.last_match[1])
@job_info_cache[jid.to_s] = { :drmaa_state => state }
end
true
end
def statestring_to_stateconst(state)
return Scir::STATE_RUNNING if state.match(/R/i)
return Scir::STATE_QUEUED_ACTIVE if state.match(/Q/i)
return Scir::STATE_USER_ON_HOLD if state.match(/H/i)
return Scir::STATE_USER_SUSPENDED if state.match(/S/i)
return Scir::STATE_UNDETERMINED
end
def hold(jid)
IO.popen("qhold #{shell_escape(jid)} 2>&1","r") do |i|
p = i.readlines
raise "Error holding: #{p.join("\n")}" if p.size > 0
return
end
end
def release(jid)
IO.popen("qrls #{shell_escape(jid)} 2>&1","r") do |i|
p = i.readlines
raise "Error releasing: #{p.join("\n")}" if p.size > 0
return
end
end
def suspend(jid)
raise "There is no 'suspend' action available for PBS clusters"
end
def resume(jid)
raise "There is no 'resume' action available for PBS clusters"
end
def terminate(jid)
IO.popen("qdel #{shell_escape(jid)} 2>&1","r") do |i|
p = i.readlines
raise "Error deleting: #{p.join("\n")}" if p.size > 0
return
end
end
def queue_tasks_tot_max
queue = Scir.cbrain_config[:default_queue]
queue = "default" if queue.blank?
queueinfo = `qstat -Q #{shell_escape(queue)} | tail -1`
# Queue Max Tot Ena Str Que Run Hld Wat Trn Ext T
# ---------------- --- --- --- --- --- --- --- --- --- --- -
# brain 90 33 yes yes 0 33 0 0 0 0 E
fields = queueinfo.split(/\s+/)
[ fields[2], fields[1] ]
rescue
[ "exception", "exception" ]
end
private
def qsubout_to_jid(txt)
if txt && txt =~ /^(\d+)/
return Regexp.last_match[1]
end
raise "Cannot find job ID from qsub output.\nOutput: #{txt}"
end
end
class JobTemplate < Scir::JobTemplate #:nodoc:
def qsub_command
raise "Error, this class only handle 'command' as /bin/bash and a single script in 'arg'" unless
self.command == "/bin/bash" && self.arg.size == 1
raise "Error: stdin not supported" if self.stdin
command = "qsub "
command += "-S /bin/bash " # Always
command += "-r n " # Always
command += "-d #{shell_escape(self.wd)} " if self.wd
command += "-N #{shell_escape(self.name)} " if self.name
command += "-o #{shell_escape(self.stdout)} " if self.stdout
command += "-e #{shell_escape(self.stderr)} " if self.stderr
command += "-j oe " if self.join
command += "-q #{shell_escape(self.queue)} " unless self.queue.blank?
command += " #{Scir.cbrain_config[:extra_qsub_args]} " unless Scir.cbrain_config[:extra_qsub_args].blank?
command += "-l walltime=#{self.walltime.to_i} " unless self.walltime.blank?
command += "#{shell_escape(self.arg[0])}"
command += " 2>&1"
return command
end
end
end
|
gpl-3.0
|
RaisingTheDerp/raisingthebar
|
root/Tracker/TrackerUI/SubPanelFindBuddyResults.cpp
|
7816
|
//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "SubPanelFindBuddyResults.h"
#include "ServerSession.h"
#include "Tracker.h"
#include "TrackerDoc.h"
#include "TrackerProtocol.h"
#include <VGUI_WizardPanel.h>
#include <VGUI_KeyValues.h>
#include <VGUI_Label.h>
#include <VGUI_ListPanel.h>
#include <VGUI_Controls.h>
#include <VGUI_ILocalize.h>
using namespace vgui;
#include <stdio.h>
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSubPanelFindBuddyResults::CSubPanelFindBuddyResults(vgui::Panel *parent, const char *panelName) : WizardSubPanel(parent, panelName)
{
ServerSession().AddNetworkMessageWatch(this, TSVC_FRIENDSFOUND);
ServerSession().AddNetworkMessageWatch(this, TSVC_NOFRIENDS);
m_pTable = new ListPanel(this, "Table");
m_iAttemptID = 0;
m_pTable->AddColumnHeader(0, "UserName", "User name", 150);
m_pTable->AddColumnHeader(1, "FirstName", "First name", 150);
m_pTable->AddColumnHeader(2, "LastName", "Last name", 150);
m_pInfoText = new Label(this, "InfoText", "");
LoadControlSettings("Friends/SubPanelFindBuddyResults.res");
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CSubPanelFindBuddyResults::~CSubPanelFindBuddyResults()
{
ServerSession().RemoveNetworkMessageWatch(this);
}
//-----------------------------------------------------------------------------
// Purpose: Returns a pointer to the panel to move to next
//-----------------------------------------------------------------------------
WizardSubPanel *CSubPanelFindBuddyResults::GetNextSubPanel()
{
// return dynamic_cast<WizardSubPanel *>(GetWizardPanel()->FindChildByName("SubPanelFindBuddyRequestAuth"));
// just skip the request auth dialog for now
return dynamic_cast<WizardSubPanel *>(GetWizardPanel()->FindChildByName("SubPanelFindBuddyComplete"));
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSubPanelFindBuddyResults::OnDisplayAsNext()
{
GetWizardPanel()->SetNextButtonEnabled(false);
GetWizardPanel()->SetTitle("#TrackerUI_FriendsSearchingTitle", false);
m_pInfoText->SetText("#TrackerUI_Searching");
// reset count and clear table
m_iFound = 0;
m_pTable->DeleteAllItems();
m_pTable->SetVisible(true);
// post a message to ourselves to finish the search
m_iAttemptID++;
PostMessage(this, new KeyValues("NoFriends", "attempt", m_iAttemptID), 5.0f);
// Start the searching by sending the network message
KeyValues *doc = GetWizardData();
ServerSession().SearchForFriend(0, doc->GetString("Email"), doc->GetString("UserName"), doc->GetString("FirstName"), doc->GetString("LastName"));
}
//-----------------------------------------------------------------------------
// Purpose: sets the finish button enabled whenever we're displayed
//-----------------------------------------------------------------------------
void CSubPanelFindBuddyResults::OnDisplay()
{
GetWizardPanel()->SetFinishButtonEnabled(false);
}
//-----------------------------------------------------------------------------
// Purpose: Network message handler, with details of another friend that has been found.
//-----------------------------------------------------------------------------
void CSubPanelFindBuddyResults::OnFriendFound(KeyValues *friendData)
{
if ((unsigned int)friendData->GetInt("UID") == GetDoc()->GetUserID())
{
// don't show ourselves in results list
return;
}
// add the friend to drop down list
m_pTable->AddItem(friendData->MakeCopy());
m_iFound++;
m_pInfoText->SetText("#TrackerUI_SelectFriendFromList");
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose: Network message handler, indicating no more friends have been found
//-----------------------------------------------------------------------------
void CSubPanelFindBuddyResults::OnNoFriends(int attemptID)
{
// make sure this message is from the right attempt
if (attemptID != m_iAttemptID)
return;
if (m_iFound == 0)
{
m_iFound = -1;
m_pInfoText->SetText("#TrackerUI_SearchFailed");
}
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSubPanelFindBuddyResults::PerformLayout()
{
if (m_iFound == -1)
{
GetWizardPanel()->SetTitle("#TrackerUI_FriendsFinishedSearchTitle", false);
}
else if (m_iFound == 1)
{
GetWizardPanel()->SetTitle("#TrackerUI_FriendsFoundMatchTitle", false);
}
else if (m_iFound > 1)
{
char buf[256];
sprintf(buf, "Friends - Found %d matches", m_iFound);
GetWizardPanel()->SetTitle(buf, false);
//tagES
// char number[32];
// wchar_t unicode[256], unicodeFound[32];
// itoa( m_iFound, number, 10 );
// localize()->ConvertANSIToUnicode( number, unicodeFound, sizeof( unicodeFound ) / sizeof( wchar_t ) );
// localize()->ConstructString(unicode, sizeof( unicode ) / sizeof( wchar_t ), localize()->Find("#TrackerUI_FriendsFoundMatchesTitle"), 1, unicodeFound );
// GetWizardPanel()->SetTitle(unicode, false);
}
else
{
GetWizardPanel()->SetTitle("#TrackerUI_FriendsSearchingTitle", false);
m_pInfoText->SetText("#TrackerUI_Searching");
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CSubPanelFindBuddyResults::OnNextButton()
{
// don't advance unless there is a row selected
if (!m_pTable->GetNumSelectedRows())
return false;
// write the data to the doc
KeyValues *doc = GetWizardData();
KeyValues *users = doc->FindKey("Users", true);
users->Clear();
// walk through
for (int i = 0; i < m_pTable->GetNumSelectedRows(); i++)
{
int row = m_pTable->GetSelectedRow(i);
KeyValues *user = m_pTable->GetItem(row);
KeyValues *dest = users->CreateNewKey();
dest->SetInt("UID", user->GetInt("UID"));
dest->SetString("UserName", user->GetString("UserName"));
dest->SetString("FirstName", user->GetString("FirstName"));
dest->SetString("LastName", user->GetString("LastName"));
}
doc->SetInt("UserCount", i);
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSubPanelFindBuddyResults::OnRowSelected(int startIndex, int endIndex)
{
if (startIndex > -1)
{
// they've selected an item so allow the user to move forward
GetWizardPanel()->SetNextButtonEnabled(true);
}
else
{
// nothing selected, so no next
GetWizardPanel()->SetNextButtonEnabled(false);
}
GetWizardPanel()->ResetDefaultButton();
}
//-----------------------------------------------------------------------------
// Purpose: Message map
//-----------------------------------------------------------------------------
MessageMapItem_t CSubPanelFindBuddyResults::m_MessageMap[] =
{
// obseleted
// MAP_MSGID( CSubPanelFindBuddyResults, TSVC_NOFRIENDS, OnNoFriends ),
MAP_MSGID_PARAMS( CSubPanelFindBuddyResults, TSVC_FRIENDSFOUND, OnFriendFound ),
MAP_MESSAGE_INT( CSubPanelFindBuddyResults, "NoFriends", OnNoFriends, "attempt" ),
MAP_MESSAGE_INT_INT( CSubPanelFindBuddyResults, "RowSelected", OnRowSelected, "startIndex", "endIndex" ),
};
IMPLEMENT_PANELMAP( CSubPanelFindBuddyResults, Panel );
|
gpl-3.0
|
cedricms/MobileFrameZeroTools
|
assets/www/js/mof0Game.js
|
3908
|
var gameModel;
var companies;
var gameRefreshIntervalId;
function initGame() {
// Init DB connection
var db = window.openDatabase("mof0DB", dbVersion,
"Mobile Frame Zero Tools", dbSize);
// Load game data
gameModel = new GameModel();
var companyIds = getUrlVars()['companyIds'];
var companyIdsArray = companyIds.split('|');
var companyService = new CompanyService(db);
companies = gameModel.companies;
for ( var companyIdsArrayIndex = 0; companyIdsArrayIndex < companyIdsArray.length; companyIdsArrayIndex++) {
var companyId = companyIdsArray[companyIdsArrayIndex];
var companyModel = companyService.getById(companyId, addCompany);
//ko.applyBindings(companyModel);
} // for
ko.applyBindings(gameModel);
//gameModel.updateScorePerAsset();
gameRefreshIntervalId = window.setInterval(updateGame, 1000);
}
function addCompany(companyModel) {
companies.push(companyModel);
}
function updateGame() {
gameModel.updateCurrentTime();
if ((gameModel.doomsdayClock() === 11) && (!gameModel.isUpdateScorePerAssetCalculated)) {
gameModel.updateScorePerAsset();
gameModel.isUpdateScorePerAssetCalculated = true;
} // if
}
function nextRound() {
if (gameModel.getDoomsdayClock() > 0) {
gameModel.decrimentDoomsdayClock();
if (gameModel.getDoomsdayClock() > 0) {
var companies = gameModel.companies();
for ( var companyIndex = 0; companyIndex < companies.length; companyIndex++) {
var company = companies[companyIndex];
var companyName = company.name();
jQuery.i18n.prop('doYouWantToCountDownTheDoomsDayClockMessage');
var countDownConfirmationMessage = companyName + doYouWantToCountDownTheDoomsDayClockMessage + ' ' + parseFloat(gameModel.getDoomsdayClock()) + ')';
var countDownAction = confirm(countDownConfirmationMessage);
if (countDownAction == true) {
gameModel.saveGameScoresPerTurn();
gameModel.decrimentDoomsdayClock();
if (gameModel.getDoomsdayClock() > 0) {
continue;
}
else {
endOfGame();
break;
} // if
}
else {
continue;
} // if
} // for
} else {
// End of the game
endOfGame();
} // if
} else {
// End of the game
endOfGame();
} // if
}
function endOfGame() {
window.clearInterval(gameRefreshIntervalId);
//Get the context of the canvas element we want to select
var ctx = document.getElementById("endOfGameChart").getContext("2d");
var data = new Array();
var labels = new Array();
var iLabel = 0;
while (iLabel < 11) {
labels[iLabel] = 11 - iLabel;
iLabel++;
} // while
data['labels'] = labels;
var datasets = new Array();
var lCompanies = gameModel.companies();
for ( var companyIndex = 0; companyIndex < lCompanies.length; companyIndex++) {
var company = lCompanies[companyIndex];
var dataset = new Array();
var redLineColor = 150 - (companyIndex * 20);
var greenLineColor = 200 - (companyIndex * 15);
var blueLineColor = 250 - (companyIndex * 10);
dataset['fillColor'] = 'rgba(' + redLineColor + ',' + greenLineColor + ',' + blueLineColor + ',0.5)';
dataset['strokeColor'] = 'rgba(' + redLineColor + ',' + greenLineColor + ',' + blueLineColor + ',1)';
dataset['pointColor'] = 'rgba(' + redLineColor + ',' + greenLineColor + ',' + blueLineColor + ',1)';
dataset['pointStrokeColor'] = '#fff';
dataset['data'] = new Array();
datasets[companyIndex] = dataset;
} // for
var turn = 11;
while (turn > 0) {
var scores = gameModel.gameScoresPerTurn[11 - turn];
for (var scoreIndex = 0; scoreIndex < scores.length; scoreIndex++) {
var score = scores[scoreIndex];
var dataset = datasets[scoreIndex];
var dataValues = dataset['data'];
dataValues[11 - turn] = score;
} // for
turn--;
} // while
data['datasets'] = datasets;
var endOfGameChart = new Chart(ctx).Line(data);
gameModel.endTime(new Date());
$('#endOfGameModal').modal('show');
}
|
gpl-3.0
|
Pr0Wolf29/subi
|
subi.cpp
|
1548
|
/* subi by Pr0Wolf29 */
/*
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 <iostream>
#include <algorithm>
#include <fstream>
#include <climits>
#include <vector>
#include <unistd.h>
#include "Pr0Wolf29/libwolfstring.hpp"
int main(int argc, char* argv[])
{
for(int a = 1; a < argc; a++)
{
if(access(argv[a], F_OK) != -1)
{
// file exists
wolfstring::TextFileVectorObject text_array;
if(text_array.safe(argv[a]))
{
//Sort and unqiue the text.
std::sort(text_array.vText.begin(), text_array.vText.end());
text_array.vText.erase(std::unique(text_array.vText.begin(), text_array.vText.end()), text_array.vText.end());
}
//Get expanded path.
char rp[PATH_MAX];
realpath(argv[a], rp);
std::ofstream ofs;
ofs.open(rp);
for(const std::string &line : text_array.vText)
{
ofs << line << std::endl;
}
ofs.close();
}
else
{
std::cerr << "No such file: " << argv[a] << std::endl;
}
}
return 0;
}
|
gpl-3.0
|
diego-gimenes/MXTires.Microdata.Core
|
CreativeWorks/Atlas.cs
|
1551
|
#region License
// Copyright (c) 2016 1010Tires.com
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace MXTires.Microdata.Core.CreativeWorks
{
/// <summary>
/// Defined in the bib.schema.org extension. (This is an initial exploratory release.)
/// Canonical URL: http://schema.org/Atlas
/// A collection or bound volume of maps, charts, plates or tables, physical or in media form illustrating any subject.
/// </summary>
public class Atlas : CreativeWork
{
}
}
|
gpl-3.0
|
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
|
src/finiteVolume/finiteVolume/adjConvectionSchemes/explicitAdjConvectionScheme/explicitAdjConvectionScheme.H
|
3893
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::fv::explicitAdjConvectionScheme
Description
AdjConvection scheme used to make adjConvection explicit without
recompilation
Author
Hrvoje Jasak, Wikki Ltd. All rights reserved.
SourceFiles
explicitAdjConvectionScheme.C
\*---------------------------------------------------------------------------*/
#ifndef explicitAdjConvectionScheme_H
#define explicitAdjConvectionScheme_H
#include "adjConvectionScheme.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace fv
{
/*---------------------------------------------------------------------------*\
Class explicitAdjConvectionScheme Declaration
\*---------------------------------------------------------------------------*/
template<class Type>
class explicitAdjConvectionScheme
:
public fv::adjConvectionScheme<Type>
{
// Private Member Functions
//- Disallow default bitwise copy construct
explicitAdjConvectionScheme(const explicitAdjConvectionScheme&);
//- Disallow default bitwise assignment
void operator=(const explicitAdjConvectionScheme&);
public:
//- Runtime type information
TypeName("explicit");
// Constructors
//- Construct from flux and interpolation scheme
explicitAdjConvectionScheme
(
const fvMesh& mesh,
const volVectorField& Up
)
:
adjConvectionScheme<Type>(mesh, Up)
{}
//- Construct from flux and Istream
explicitAdjConvectionScheme
(
const fvMesh& mesh,
const volVectorField& Up,
Istream& is
)
:
adjConvectionScheme<Type>(mesh, Up)
{}
// Member Functions
tmp<fvMatrix<Type> > fvmAdjDiv
(
const volVectorField&,
GeometricField<Type, fvPatchField, volMesh>&
) const;
tmp<GeometricField<Type, fvPatchField, volMesh> > fvcAdjDiv
(
const volVectorField&,
const GeometricField<Type, fvPatchField, volMesh>&
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace fv
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
# include "explicitAdjConvectionScheme.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
gpl-3.0
|
ztdroid/overtime
|
ot/models.py
|
472
|
#! -*- coding:utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class Date(models.Model):
CHOICES = (('n', '值班'), ('a', '加班'),)
date = models.DateField()
user = models.ForeignKey(User)
kind = models.CharField(max_length=1, choices=CHOICES)
def __unicode__(self):
return '%s %s' % (self.user.username,self.date)
class Meta:
unique_together = (('date','user'),)
|
gpl-3.0
|
ZelphirKaltstahl/rst-internal-links-to-raw-latex
|
RSTInternalLinks/RSTInternalLinksParser.py
|
11504
|
import re
class RSTInternalLinksParser():
"""parses rst files and exchanges internal links with latex internal hyperlinks"""
def __init__(self, headings):
super().__init__()
self.headings = headings
self.rst_reference_definition_regex = re.compile(
r'\.\. _(?P<link_key>[^\[\]_`:]+):',
re.UNICODE
)
self.rst_target_single_word_regex = re.compile(
r'''
(?<!\.\.[ ]) # exclude link definitions
(?<!__[ ]) # exclude anonymous link definitions
(?<=[\s^]) # there must be either the beginning of the line
# before OR whitespace
# (this excludes backticks for example)
_ # underscore
(?P<link_key>[a-zA-Z0-9ßäöüÄÖÜ()-]+) # letters
# numbers
# parentheses
# underscores
# dashes
''',
re.VERBOSE | re.UNICODE
)
self.rst_reference_single_word_regex = re.compile(
r'''
(?<!__[ ]) # exclude anonymous link definitions
(?<=[\s^]) # there must be either the beginning of the line
# before OR whitespace
# (this excludes backticks for example)
(?P<link_key>[a-zA-Z0-9ßäöüÄÖÜ()-]+) # letters
# numbers
# parentheses
# underscores
# dashes
_ # underscore
(?=(\s|[.,:;/?!]|$)) # not a word like: abc_def
''',
re.VERBOSE | re.UNICODE)
self.rst_target_multi_word_regex = re.compile(
r'''
(?<=[\s^])
_
`
(?P<link_key>[a-zA-Z0-9ßäöüÄÖÜ()_ -]+)
`
''',
re.VERBOSE | re.UNICODE
)
self.rst_reference_multi_word_regex = re.compile(
r'''
(?<=[\s^(\[])
`
(?P<link_key>[a-zA-Z0-9ßäöüÄÖÜ()_ -]+)
`
_
(?=(\s|[\)\(\]\[.,:;/?!]|$))
''',
re.VERBOSE | re.UNICODE
)
def parse(self, rst_file_content):
found_rst_link_definitions_keys = self.find_reference_definitions(rst_file_content)
print('[DEBUG:Result] found link definition keys:', found_rst_link_definitions_keys)
rst_file_content = self.replace_heading_references(rst_file_content)
rst_file_content = self.replace_single_word_targets(rst_file_content)
rst_file_content = self.replace_single_word_references(rst_file_content)
rst_file_content = self.replace_multi_word_targets(rst_file_content)
rst_file_content = self.replace_multi_word_references(rst_file_content)
return rst_file_content
def find_reference_definitions(self, rst_file_content):
rst_reference_definition_keys = []
for lineno, line in enumerate(rst_file_content):
if self.rst_reference_definition_regex.match(line):
rst_reference_definition_keys.append(
self.rst_reference_definition_regex.match(line).group('link_key'))
return rst_reference_definition_keys
def replace_heading_references(self, rst_file_content):
print('[DEBUG]: searching for heading references ...')
for lineno, line in enumerate(rst_file_content):
match_objects = self.rst_reference_multi_word_regex.finditer(line)
for match_object in match_objects:
link_key = match_object.group('link_key')
if link_key in self.headings.keys():
# if there is such a heading then it is actually a link to a HEADING!!!
heading_link = link_key
print('[DEBUG]:', 'found a link to a heading!', heading_link)
# get the latex code for the reference to the heading (to
# the label at the heading)
latex_heading_label_reference = self.heading_link_to_latex_label_reference(
heading_link)
# get the raw latex text role of rst with the filled in
# latex code
rst_raw_latex_link_reference = self.to_rst_raw_latex(
latex_heading_label_reference)
# replace the match object in the line
print('[DEBUG]:',
' now replacing heading reference in line:\n|',
line,
'|',
sep='')
rst_file_content[lineno] = line.replace(
match_object.group(),
rst_raw_latex_link_reference)
line = rst_file_content[lineno]
print('[DEBUG]:', ' line is now:\n|', rst_file_content[lineno], '|', sep='')
return rst_file_content
def heading_link_to_latex_label_reference(self, heading_link):
return '\hyperref[{key}]{{{text}}}' \
.format(
key=self.headings[heading_link],
text=heading_link
)
def replace_single_word_targets(self, rst_file_content):
print('[DEBUG]: searching for single word targets ...')
for lineno, line in enumerate(rst_file_content):
match_objects = self.rst_target_single_word_regex.finditer(line)
for match_object in match_objects:
link_key = match_object.group('link_key')
print('[DEBUG]:', 'found a single word hypertarget!', link_key)
latex_hypertarget = self.link_key_to_latex_hypertarget(link_key)
rst_raw_latex_hypertarget = self.to_rst_raw_latex(latex_hypertarget)
print('[DEBUG]:', ' now replacing hypertarget in line:\n|', line, '|', sep='')
rst_file_content[lineno] = line.replace(
match_object.group(),
rst_raw_latex_hypertarget
)
line = rst_file_content[lineno]
print('[DEBUG]:', ' line is now:\n|', rst_file_content[lineno], '|', sep='')
return rst_file_content
def replace_single_word_references(self, rst_file_content):
print('[DEBUG]: searching for SINGLE word REFERENCES ...')
for lineno, line in enumerate(rst_file_content):
match_objects = self.rst_reference_single_word_regex.finditer(line)
for match_object in match_objects:
link_key = match_object.group('link_key')
print('[DEBUG]: found a SINGLE word hyperlink! |', link_key, '|', sep='')
latex_hyperlink = self.link_key_to_latex_hyperlink(link_key)
rst_raw_latex_hyperlink = self.to_rst_raw_latex(latex_hyperlink)
print(
'[DEBUG]:',
' now replacing hyperlink in line ',
lineno,
':\n|',
line,
'|',
sep=''
)
rst_file_content[lineno] = line.replace(
match_object.group(),
rst_raw_latex_hyperlink
)
line = rst_file_content[lineno]
print('[DEBUG]:', ' line is now:\n|', rst_file_content[lineno], '|', sep='')
return rst_file_content
def replace_multi_word_targets(self, rst_file_content):
print('[DEBUG]: searching for MULTI word TARGETS ...')
for lineno, line in enumerate(rst_file_content):
match_objects = self.rst_target_multi_word_regex.finditer(line)
for match_object in match_objects:
link_key = match_object.group('link_key')
print('[DEBUG]: found a MULTI word hyperTARGET! |', link_key, '|', sep='')
latex_hypertarget = self.link_key_to_latex_hypertarget(link_key)
rst_raw_latex_hypertarget = self.to_rst_raw_latex(latex_hypertarget)
print(
'[DEBUG]:',
' now replacing hypertarget in line ', lineno, ':\n',
'|', line, '|',
sep=''
)
rst_file_content[lineno] = line.replace(
match_object.group(),
rst_raw_latex_hypertarget
)
line = rst_file_content[lineno]
print('[DEBUG]:', ' line is now:\n|', rst_file_content[lineno], '|', sep='')
return rst_file_content
def replace_multi_word_references(self, rst_file_content):
print('[DEBUG]: searching for MULTI word REFERENCES ...')
for lineno, line in enumerate(rst_file_content):
match_objects = self.rst_reference_multi_word_regex.finditer(line)
for match_object in match_objects:
link_key = match_object.group('link_key')
if link_key not in self.headings.keys():
print('[DEBUG]: found a MULTI word hyperREFERENCE! |', link_key, '|', sep='')
latex_hyperlink = self.link_key_to_latex_hyperlink(link_key)
rst_raw_latex_hyperlink = self.to_rst_raw_latex(latex_hyperlink)
print(
'[DEBUG]:', ' now replacing hyperlink in line ', lineno, ':\n',
'|', line, '|',
sep=''
)
rst_file_content[lineno] = line.replace(
match_object.group(),
rst_raw_latex_hyperlink
)
line = rst_file_content[lineno]
print('[DEBUG]:', ' line is now:\n|', rst_file_content[lineno], '|', sep='')
return rst_file_content
def link_key_to_latex_hypertarget(self, link_key, link_text=None):
if link_text:
return '\hypertarget{{{link_key}}}{{{link_text}}}'.format(
link_key=link_key,
link_text=link_text
)
else:
return '\hypertarget{{{link_key}}}{{{link_text}}}'.format(
link_key=link_key,
link_text=link_key
)
def link_key_to_latex_hyperlink(self, link_key, link_text=None):
if link_text:
return '\hyperlink{{{link_key}}}{{{link_text}}}'.format(
link_key=link_key,
link_text=link_text
)
else:
return '\hyperlink{{{link_key}}}{{{link_text}}}'.format(
link_key=link_key,
link_text=link_key
)
def to_rst_raw_latex(self, latex_content):
return ':raw-latex:`' + latex_content + '`'
|
gpl-3.0
|
JosePineiro/LittleZip
|
LittleZip/Program.cs
|
464
|
using System;
using System.Windows.Forms;
namespace LittleZipTest
{
static class Program
{
/// <summary>
/// Punto de entrada principal para la aplicación.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LittleZipTest());
}
}
}
|
gpl-3.0
|
janisozaur/OpenRCT2
|
src/openrct2/actions/RideCreateAction.cpp
|
9607
|
/*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include "RideCreateAction.h"
#include "../Cheats.h"
#include "../core/Memory.hpp"
#include "../core/MemoryStream.h"
#include "../interface/Window.h"
#include "../localisation/Date.h"
#include "../localisation/StringIds.h"
#include "../rct1/RCT1.h"
#include "../ride/Ride.h"
#include "../ride/RideData.h"
#include "../ride/ShopItem.h"
#include "../ride/Station.h"
#include "../scenario/Scenario.h"
#include "../world/Park.h"
#include <algorithm>
RideCreateGameActionResult::RideCreateGameActionResult()
: GameActions::Result(GameActions::Status::Ok, STR_NONE)
{
}
RideCreateGameActionResult::RideCreateGameActionResult(GameActions::Status error, rct_string_id message)
: GameActions::Result(error, STR_CANT_CREATE_NEW_RIDE_ATTRACTION, message)
{
}
RideCreateAction::RideCreateAction(int32_t rideType, ObjectEntryIndex subType, int32_t colour1, int32_t colour2)
: _rideType(rideType)
, _subType(subType)
, _colour1(colour1)
, _colour2(colour2)
{
}
void RideCreateAction::AcceptParameters(GameActionParameterVisitor& visitor)
{
visitor.Visit("rideType", _rideType);
visitor.Visit("rideObject", _subType);
visitor.Visit("colour1", _colour1);
visitor.Visit("colour2", _colour2);
}
int32_t RideCreateAction::GetRideType() const
{
return _rideType;
}
int32_t RideCreateAction::GetRideObject() const
{
return _subType;
}
uint16_t RideCreateAction::GetActionFlags() const
{
return GameAction::GetActionFlags() | GameActions::Flags::AllowWhilePaused;
}
void RideCreateAction::Serialise(DataSerialiser& stream)
{
GameAction::Serialise(stream);
stream << DS_TAG(_rideType) << DS_TAG(_subType) << DS_TAG(_colour1) << DS_TAG(_colour2);
}
GameActions::Result::Ptr RideCreateAction::Query() const
{
auto rideIndex = GetNextFreeRideId();
if (rideIndex == RIDE_ID_NULL)
{
// No more free slots available.
return MakeResult(GameActions::Status::NoFreeElements, STR_TOO_MANY_RIDES);
}
if (_rideType >= RIDE_TYPE_COUNT)
{
return MakeResult(GameActions::Status::InvalidParameters, STR_INVALID_RIDE_TYPE);
}
int32_t rideEntryIndex = ride_get_entry_index(_rideType, _subType);
if (rideEntryIndex >= MAX_RIDE_OBJECTS)
{
return MakeResult(GameActions::Status::InvalidParameters, STR_INVALID_RIDE_TYPE);
}
const auto& colourPresets = GetRideTypeDescriptor(_rideType).ColourPresets;
if (_colour1 >= colourPresets.count)
{
return MakeResult(GameActions::Status::InvalidParameters, STR_NONE);
}
rct_ride_entry* rideEntry = get_ride_entry(rideEntryIndex);
if (rideEntry == nullptr)
{
return MakeResult(GameActions::Status::InvalidParameters, STR_NONE);
}
vehicle_colour_preset_list* presetList = rideEntry->vehicle_preset_list;
if ((presetList->count > 0 && presetList->count != 255) && _colour2 >= presetList->count)
{
return MakeResult(GameActions::Status::InvalidParameters, STR_NONE);
}
return MakeResult();
}
GameActions::Result::Ptr RideCreateAction::Execute() const
{
rct_ride_entry* rideEntry;
auto res = MakeResult();
int32_t rideEntryIndex = ride_get_entry_index(_rideType, _subType);
auto rideIndex = GetNextFreeRideId();
res->rideIndex = rideIndex;
auto ride = GetOrAllocateRide(rideIndex);
rideEntry = get_ride_entry(rideEntryIndex);
if (rideEntry == nullptr)
{
log_warning("Invalid request for ride %u", rideIndex);
res->Error = GameActions::Status::Unknown;
res->ErrorMessage = STR_UNKNOWN_OBJECT_TYPE;
return res;
}
ride->id = rideIndex;
ride->type = _rideType;
ride->subtype = rideEntryIndex;
ride->SetColourPreset(_colour1);
ride->overall_view.setNull();
ride->SetNameToDefault();
for (int32_t i = 0; i < MAX_STATIONS; i++)
{
ride->stations[i].Start.setNull();
ride_clear_entrance_location(ride, i);
ride_clear_exit_location(ride, i);
ride->stations[i].TrainAtStation = RideStation::NO_TRAIN;
ride->stations[i].QueueTime = 0;
}
for (auto& vehicle : ride->vehicles)
{
vehicle = SPRITE_INDEX_NULL;
}
ride->status = RIDE_STATUS_CLOSED;
ride->lifecycle_flags = 0;
ride->vehicle_change_timeout = 0;
ride->num_stations = 0;
ride->num_vehicles = 1;
ride->proposed_num_vehicles = 32;
ride->max_trains = 32;
ride->num_cars_per_train = 1;
ride->proposed_num_cars_per_train = 12;
ride->min_waiting_time = 10;
ride->max_waiting_time = 60;
ride->depart_flags = RIDE_DEPART_WAIT_FOR_MINIMUM_LENGTH | 3;
if (ride->GetRideTypeDescriptor().HasFlag(RIDE_TYPE_FLAG_MUSIC_ON_DEFAULT))
{
ride->lifecycle_flags |= RIDE_LIFECYCLE_MUSIC;
}
ride->music = ride->GetRideTypeDescriptor().DefaultMusic;
const auto& operatingSettings = ride->GetRideTypeDescriptor().OperatingSettings;
ride->operation_option = (operatingSettings.MinValue * 3 + operatingSettings.MaxValue) / 4;
ride->lift_hill_speed = ride->GetRideTypeDescriptor().LiftData.minimum_speed;
ride->measurement = {};
ride->excitement = RIDE_RATING_UNDEFINED;
ride->cur_num_customers = 0;
ride->num_customers_timeout = 0;
ride->chairlift_bullwheel_rotation = 0;
for (auto& price : ride->price)
{
price = 0;
}
if (!(gParkFlags & PARK_FLAGS_NO_MONEY))
{
for (auto i = 0; i < NUM_SHOP_ITEMS_PER_RIDE; i++)
{
ride->price[i] = ride->GetRideTypeDescriptor().DefaultPrices[i];
}
if (rideEntry->shop_item[0] == ShopItem::None)
{
if (!park_ride_prices_unlocked())
{
ride->price[0] = 0;
}
}
else
{
ride->price[0] = GetShopItemDescriptor(rideEntry->shop_item[0]).DefaultPrice;
}
if (rideEntry->shop_item[1] != ShopItem::None)
{
ride->price[1] = GetShopItemDescriptor(rideEntry->shop_item[1]).DefaultPrice;
}
if (gScenarioObjective.Type == OBJECTIVE_BUILD_THE_BEST)
{
ride->price[0] = 0;
}
if (ride->type == RIDE_TYPE_TOILETS)
{
if (shop_item_has_common_price(ShopItem::Admission))
{
money32 price = ride_get_common_price(ride);
if (price != MONEY32_UNDEFINED)
{
ride->price[0] = static_cast<money16>(price);
}
}
}
for (auto i = 0; i < NUM_SHOP_ITEMS_PER_RIDE; i++)
{
if (rideEntry->shop_item[i] != ShopItem::None)
{
if (shop_item_has_common_price(rideEntry->shop_item[i]))
{
money32 price = shop_item_get_common_price(ride, rideEntry->shop_item[i]);
if (price != MONEY32_UNDEFINED)
{
ride->price[i] = static_cast<money16>(price);
}
}
}
}
// Set the on-ride photo price, whether the ride has one or not (except shops).
if (!ride->GetRideTypeDescriptor().HasFlag(RIDE_TYPE_FLAG_IS_SHOP) && shop_item_has_common_price(ShopItem::Photo))
{
money32 price = shop_item_get_common_price(ride, ShopItem::Photo);
if (price != MONEY32_UNDEFINED)
{
ride->price[1] = static_cast<money16>(price);
}
}
}
std::fill(std::begin(ride->num_customers), std::end(ride->num_customers), 0);
ride->value = RIDE_VALUE_UNDEFINED;
ride->satisfaction = 255;
ride->satisfaction_time_out = 0;
ride->satisfaction_next = 0;
ride->popularity = 255;
ride->popularity_time_out = 0;
ride->popularity_next = 0;
ride->window_invalidate_flags = 0;
ride->total_customers = 0;
ride->total_profit = 0;
ride->num_riders = 0;
ride->slide_in_use = 0;
ride->maze_tiles = 0;
ride->build_date = gDateMonthsElapsed;
ride->music_tune_id = 255;
ride->breakdown_reason = 255;
ride->upkeep_cost = MONEY16_UNDEFINED;
ride->reliability = RIDE_INITIAL_RELIABILITY;
ride->unreliability_factor = 1;
ride->inspection_interval = RIDE_INSPECTION_EVERY_30_MINUTES;
ride->last_inspection = 0;
ride->downtime = 0;
std::fill_n(ride->downtime_history, sizeof(ride->downtime_history), 0x00);
ride->no_primary_items_sold = 0;
ride->no_secondary_items_sold = 0;
ride->last_crash_type = RIDE_CRASH_TYPE_NONE;
ride->income_per_hour = MONEY32_UNDEFINED;
ride->profit = MONEY32_UNDEFINED;
ride->connected_message_throttle = 0;
ride->entrance_style = 0;
ride->num_block_brakes = 0;
ride->guests_favourite = 0;
ride->num_circuits = 1;
ride->mode = ride->GetDefaultMode();
ride->SetMinCarsPerTrain(rideEntry->min_cars_in_train);
ride->SetMaxCarsPerTrain(rideEntry->max_cars_in_train);
ride_set_vehicle_colours_to_random_preset(ride, _colour2);
window_invalidate_by_class(WC_RIDE_LIST);
res->Expenditure = ExpenditureType::RideConstruction;
return res;
}
|
gpl-3.0
|
mikel-egana-aranguren/SADI-Galaxy-Docker
|
galaxy-dist/test/unit/jobs/test_runner_local.py
|
5600
|
import os
import threading
import time
from unittest import TestCase
from galaxy.util import bunch
from galaxy.jobs.runners import local
from galaxy.jobs import metrics
from galaxy import model
from tools_support import (
UsesApp,
UsesTools
)
class TestLocalJobRunner( TestCase, UsesApp, UsesTools ):
def setUp( self ):
self.setup_app()
self._init_tool()
self.app.job_metrics = metrics.JobMetrics()
self.job_wrapper = MockJobWrapper( self.app, self.test_directory, self.tool )
def tearDown( self ):
self.tear_down_app()
def test_run( self ):
self.job_wrapper.command_line = "echo HelloWorld"
runner = local.LocalJobRunner( self.app, 1 )
runner.queue_job( self.job_wrapper )
assert self.job_wrapper.stdout.strip() == "HelloWorld"
def test_galaxy_lib_on_path( self ):
self.job_wrapper.command_line = '''python -c "import galaxy.util"'''
runner = local.LocalJobRunner( self.app, 1 )
runner.queue_job( self.job_wrapper )
assert self.job_wrapper.exit_code == 0
def test_default_slots( self ):
self.job_wrapper.command_line = '''echo $GALAXY_SLOTS'''
runner = local.LocalJobRunner( self.app, 1 )
runner.queue_job( self.job_wrapper )
assert self.job_wrapper.stdout.strip() == "1"
def test_slots_override( self ):
# Set local_slots in job destination to specify slots for
# local job runner.
self.job_wrapper.job_destination.params[ "local_slots" ] = 3
self.job_wrapper.command_line = '''echo $GALAXY_SLOTS'''
runner = local.LocalJobRunner( self.app, 1 )
runner.queue_job( self.job_wrapper )
assert self.job_wrapper.stdout.strip() == "3"
def test_exit_code( self ):
self.job_wrapper.command_line = '''sh -c "exit 4"'''
runner = local.LocalJobRunner( self.app, 1 )
runner.queue_job( self.job_wrapper )
assert self.job_wrapper.exit_code == 4
def test_metadata_gets_set( self ):
runner = local.LocalJobRunner( self.app, 1 )
runner.queue_job( self.job_wrapper )
assert os.path.exists( self.job_wrapper.mock_metadata_path )
def test_metadata_gets_set_if_embedded( self ):
self.job_wrapper.job_destination.params[ "embed_metadata_in_job" ] = "True"
# Kill off cruft for _handle_metadata_externally and make sure job stil works...
self.job_wrapper.external_output_metadata = None
self.app.datatypes_registry.set_external_metadata_tool = None
runner = local.LocalJobRunner( self.app, 1 )
runner.queue_job( self.job_wrapper )
assert os.path.exists( self.job_wrapper.mock_metadata_path )
def test_stopping_job( self ):
self.job_wrapper.command_line = '''python -c "import time; time.sleep(15)"'''
runner = local.LocalJobRunner( self.app, 1 )
def queue():
runner.queue_job( self.job_wrapper )
t = threading.Thread(target=queue)
t.start()
while True:
if self.job_wrapper.external_id:
break
time.sleep( .01 )
external_id = self.job_wrapper.external_id
mock_job = bunch.Bunch(
get_external_output_metadata=lambda: None,
get_job_runner_external_id=lambda: str(external_id),
get_id=lambda: 1
)
runner.stop_job( mock_job )
t.join(1)
class MockJobWrapper( object ):
def __init__( self, app, test_directory, tool ):
working_directory = os.path.join( test_directory, "workdir" )
os.makedirs( working_directory )
self.app = app
self.tool = tool
self.state = model.Job.states.QUEUED
self.command_line = "echo HelloWorld"
self.prepare_called = False
self.write_version_cmd = None
self.dependency_shell_commands = None
self.working_directory = working_directory
self.requires_setting_metadata = True
self.job_destination = bunch.Bunch( id="default", params={} )
self.galaxy_lib_dir = os.path.abspath( "lib" )
self.job_id = 1
self.external_id = None
self.output_paths = [ '/tmp/output1.dat' ]
self.mock_metadata_path = os.path.abspath( os.path.join( test_directory, "METADATA_SET" ) )
self.metadata_command = "touch %s" % self.mock_metadata_path
# Cruft for setting metadata externally, axe at some point.
self.external_output_metadata = bunch.Bunch(
set_job_runner_external_pid=lambda pid, session: None
)
self.app.datatypes_registry.set_external_metadata_tool = bunch.Bunch(
build_dependency_shell_commands=lambda: []
)
def prepare( self ):
self.prepare_called = True
def set_job_destination( self, job_destination, external_id ):
self.external_id = external_id
def get_command_line( self ):
return self.command_line
def get_id_tag( self ):
return "1"
def get_state( self ):
return self.state
def change_state( self, state ):
self.state = state
def get_output_fnames( self ):
return []
def get_job( self ):
return model.Job()
def setup_external_metadata( self, **kwds ):
return self.metadata_command
def get_env_setup_clause( self ):
return ""
def has_limits( self ):
return False
def finish( self, stdout, stderr, exit_code ):
self.stdout = stdout
self.stderr = stderr
self.exit_code = exit_code
|
gpl-3.0
|
Kunzisoft/RememBirthday
|
RememBirthday-UI/src/main/java/com/kunzisoft/remembirthday/factory/MenuFactoryPro.java
|
1032
|
package com.kunzisoft.remembirthday.factory;
import android.content.Context;
import com.kunzisoft.remembirthday.preference.PreferencesManager;
/**
* Menu Factory for Pro version of application. <br />
* Automatically hides the daemon-dependent buttons when they are inactive
*/
public class MenuFactoryPro extends MenuFactoryBase {
public MenuFactoryPro(Context context, boolean asPhoneNumber) {
super(context, asPhoneNumber);
if(PreferencesManager.isDaemonsActive(context)) {
listMenuAction.add(new MenuActionGift());
if(asPhoneNumber) {
listMenuAction.add(new MenuActionAutoMessage());
}
} else {
if(!PreferencesManager.isButtonsForInactiveFeaturesHidden(context)) {
listMenuAction.add(new MenuActionGift(MenuAction.STATE.INACTIVE));
if (asPhoneNumber) {
listMenuAction.add(new MenuActionAutoMessage(MenuAction.STATE.INACTIVE));
}
}
}
}
}
|
gpl-3.0
|
apruden/mica2
|
mica-core/src/main/java/org/obiba/mica/file/event/FileUnPublishedEvent.java
|
631
|
/*
* Copyright (c) 2016 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.mica.file.event;
import org.obiba.mica.core.event.PersistablePublishedEvent;
import org.obiba.mica.file.AttachmentState;
public class FileUnPublishedEvent extends PersistablePublishedEvent<AttachmentState> {
public FileUnPublishedEvent(AttachmentState state) {
super(state);
}
}
|
gpl-3.0
|
oprogramador/TicketsOnline
|
src/Mondo/BookingBundle/MondoBookingBundle.php
|
247
|
<?php
/**************************************
*
* Author: Piotr Sroczkowski
*
**************************************/
namespace Mondo\BookingBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MondoBookingBundle extends Bundle {
}
|
gpl-3.0
|
danielbonetto/twig_MVC
|
lang/ar/lesson.php
|
22792
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'lesson', language 'ar', branch 'MOODLE_22_STABLE'
*
* @package lesson
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['accesscontrol'] = 'تحكم الدخول';
$string['actionaftercorrectanswer'] = 'العمل بعد الاجابة الصحيحة';
$string['actions'] = 'إجراءات';
$string['activitylink'] = 'رابط لنشاط';
$string['activitylinkname'] = 'أذهب ألى: {$a}';
$string['addabranchtable'] = 'أضف جدول فرعي';
$string['addanendofbranch'] = 'أضف نهاية الفرع';
$string['addanewpage'] = 'أضف صفخة جديدة';
$string['addaquestionpage'] = 'أضف سؤال إلى الصفحة';
$string['addaquestionpagehere'] = 'أضف سؤال لهذه الصفحة';
$string['addcluster'] = 'أضف عنقود';
$string['addedabranchtable'] = 'تم أضافة جدول فرعي';
$string['addedanendofbranch'] = 'تم أضافة فرع نهائي';
$string['addedaquestionpage'] = 'تم أضافة صفحة سئوال';
$string['addedcluster'] = 'نم أضافة عنقود';
$string['addedendofcluster'] = 'تم إضافة نهاية العنقود';
$string['addendofcluster'] = 'أضف نهاية العنقود';
$string['addpage'] = 'اضف صفحة';
$string['anchortitle'] = 'ابداء المحتوى الاساسي';
$string['and'] = 'و';
$string['answer'] = 'أجب';
$string['answeredcorrectly'] = 'الأجابة صحيحة';
$string['answersfornumerical'] = 'الاجابات على الأسئلة العددية ينبغي أن تكون أزواج مطابقة لقيم الحد الأدنى والحد الأقصى.';
$string['arrangebuttonshorizontally'] = 'ترتيب الأزرار الفرعية أفقياً؟';
$string['attempt'] = 'محاولة: {$a}';
$string['attempts'] = 'محاولات';
$string['attemptsdeleted'] = 'حذف المحاولات';
$string['attemptsremaining'] = 'لديك {$a} محاولة(محاولات) متبقية';
$string['available'] = 'متاح من';
$string['averagescore'] = 'متوسط الدرجة';
$string['averagetime'] = 'متوسط الوقت';
$string['branch'] = 'محتوى';
$string['branchtable'] = 'محتوى';
$string['cancel'] = 'إلغاء';
$string['canretake'] = '{$a} يستطيع إعادة أخذ';
$string['casesensitive'] = 'استخدم التعابير المعتادة';
$string['checkbranchtable'] = 'تأكد من الجدول فرعي';
$string['checkedthisone'] = 'أختر هذا';
$string['checknavigation'] = 'تأكد من روابط التنقل';
$string['checkquestion'] = 'أفحص السؤال';
$string['classstats'] = 'أحصائيات صف';
$string['clicktodownload'] = 'اضغط على الرابط التالي لتحميل الملف';
$string['clicktopost'] = 'اضغط هنا لارسال درجتك الى قائمة النتائج العالية';
$string['cluster'] = 'عنقود';
$string['clusterjump'] = 'السؤال الخفي ضمن كتلة';
$string['clustertitle'] = 'عنقود';
$string['collapsed'] = 'إنهار';
$string['comments'] = 'تعليقاتك';
$string['completed'] = 'تم';
$string['completederror'] = 'اتم الدرس';
$string['completethefollowingconditions'] = 'يجب اكمال الشرط (الشروط ) التالي في <b>{$a}</b> الدرس قبل المضي قدماً';
$string['conditionsfordependency'] = 'شرط(شروط)التبعية';
$string['confirmdeletionofthispage'] = 'تأكيد حذف هذه الصفحة';
$string['congratulations'] = 'مبروك - لقد وصلت إلى نهاية الدرس';
$string['continue'] = 'استمر';
$string['continuetoanswer'] = 'استمر في تغير الأجابات';
$string['correctanswerjump'] = 'قفز الأجابة الصحيحة';
$string['correctanswerscore'] = 'درجة الأجابة الصحيحة';
$string['correctresponse'] = 'الاجابة الصحيحة';
$string['credit'] = 'رصيد';
$string['customscoring'] = 'سجل مخصص';
$string['deadline'] = 'خر موعد لإنجاز العمل';
$string['defaultessayresponse'] = 'سيتم إدراج مقالك بواسطة محاضر المقرر';
$string['deleteallattempts'] = 'حذف كل محاولات الدرس';
$string['deletedefaults'] = 'تم حذف {$a} x درس';
$string['deletedpage'] = 'حذف صفحة';
$string['deleting'] = 'حذف';
$string['deletingpage'] = 'حذف الصفحة: {$a}';
$string['dependencyon'] = 'يعتمد على';
$string['description'] = 'وصف';
$string['detailedstats'] = 'إحصائيات تفصيلية';
$string['didnotanswerquestion'] = 'لم تتم أجابة هذا السؤال';
$string['didnotreceivecredit'] = 'لم يتم استلام الرصيد';
$string['displaydefaultfeedback'] = 'عرض التغذية الراجعة الافتراضية';
$string['displayhighscores'] = 'أعرض أعلى درجة';
$string['displayinleftmenu'] = 'أعرض في القائمة اليسرى';
$string['displayleftif'] = 'عرض القائمة اليسرى فقط إذا كانت الدرجة أكبر من :';
$string['displayleftmenu'] = 'أعرض القائمة اليسرى';
$string['displayofgrade'] = 'أعرض الدرجة (للطلاب فقط)';
$string['displayreview'] = 'أعرض زر المراجعة';
$string['displayscorewithessays'] = 'حصلت على {$a->score} من أصل {$a->tempmaxgrade} للأسئلة المُدرجة تلقائياً.<br />لديك {$a->essayquestions} سؤال(أسئلة) مقالي ستُدرج وتضاف <br /> لدرجتك النهائية في وقت لاحق .<br /><br />درجتك الحالية بدون السؤال(الأسئلة) المقالي هي {$a->s} من أصل {$a->grade}';
$string['displayscorewithoutessays'] = 'نتيجتك هي {$a->score} ( من أصل {$a->grade}) .';
$string['edit'] = 'تحرير';
$string['editlessonsettings'] = 'حرر إدادات الدرس';
$string['editpagecontent'] = 'حرر محتوى الصفحة';
$string['email'] = 'بريد الإلكتروني';
$string['emailallgradedessays'] = 'أرسال جميع <br /> المقالات المصححة بالبريد الإلكتروني';
$string['emailgradedessays'] = 'أرسال المقالات المصححة بالبريد الإلكتروني';
$string['emailsuccess'] = 'تم إسال البريد الإلكتروني بنجاح';
$string['endofbranch'] = 'نهاية تفرع';
$string['endofclustertitle'] = 'نهاية عنقود';
$string['endoflesson'] = 'نهاية الدرس';
$string['enteredthis'] = 'تم أدخال هذا';
$string['entername'] = 'ادخال الكنية لقائمة الدرجات العالية';
$string['enterpassword'] = 'الرجاء إدخال كلمة المرور';
$string['eolstudentoutoftime'] = 'تنبية :';
$string['eolstudentoutoftimenoanswers'] = 'لم تجب على أيه أسئلة . وقد حصلت على 0 لهذا الدرس';
$string['essay'] = 'مقالى';
$string['essayemailmessage'] = '<p> مقال موجة: <blockquote>{$a->question}</blockquote></p><p> ردك:<blockquote><em>{$a->response}</em></blockquote></p><p>{$a->teacher}\'s تعليقات:<blockquote><em>{$a->comment}</em></blockquote></p><p> حصلت على :{$a->earned} من أصل {$a->outof} لهذا السؤال المقالي .</p><p> درجتك لهذا الدرس قد تغيرت الى {$a->newgrade}%.</p>';
$string['essayemailsubject'] = 'درجتك للسؤال {$a}';
$string['essays'] = 'مقالات';
$string['essayscore'] = 'درجة المقالة';
$string['fileformat'] = 'صيغة ملف';
$string['firstanswershould'] = 'لابد أن الإجابة الأولى تنقلك الى صفحة "التصحيح"';
$string['firstwrong'] = 'للأسف لا يمكنك الحصول على هذة النقطة , لأن إجابتك لم تكن صحيحة .هل ترغب بالإحتفاظ في التخمين , لمجرد التعلم ( ولكن ليست لرصيد الدرجة)؟';
$string['flowcontrol'] = 'التحكم في التدفق';
$string['full'] = 'وسع';
$string['general'] = 'عام';
$string['grade'] = 'درجة';
$string['gradebetterthan'] = 'درجة أفضل من (%)';
$string['gradebetterthanerror'] = 'كسب على درجة أفضل من {$a} بالمئة';
$string['gradeessay'] = 'صحح الاسءلة المقالية';
$string['gradeis'] = 'الدرجة هي {$a}';
$string['gradeoptions'] = 'نقاط الدرجة';
$string['handlingofretakes'] = 'التعامل مع إعاد الأخذ';
$string['havenotgradedyet'] = 'لم تصحح بعد';
$string['here'] = 'هناء';
$string['highscore'] = 'الدرجة القصوى';
$string['highscores'] = 'الدرجة القصوى';
$string['hightime'] = 'الوقت الاقصى';
$string['importcount'] = 'يتم استيراد {$a} الأسئله';
$string['importppt'] = 'إستيراد بوربوينت';
$string['importquestions'] = 'استيراد اسئلة';
$string['insertedpage'] = 'إدراج صفحة';
$string['jump'] = 'قفز';
$string['jumps'] = 'قفزات';
$string['jumpsto'] = 'القفز إلى <em>{$a}</em>';
$string['leftduringtimed'] = 'غادرت أثناء وقت الدرس . <br /> الرجاء النقر على استمرار لإعادة الدرس.';
$string['leftduringtimednoretake'] = 'غادرت أثناء وقت الدرس وأنت<br /> غير مسموح لإستعادة او الاستمرار في الدرس';
$string['lesson:edit'] = 'حرر أنشطة درس';
$string['lesson:manage'] = 'إدارة أنشطة درس';
$string['lessonattempted'] = 'محاولة الدرس';
$string['lessonclosed'] = 'تم أغلاق هذا الدرس في {$a}';
$string['lessoncloses'] = 'اغلاق الدرس';
$string['lessoncloseson'] = 'اغلاق الدرس في {$a}';
$string['lessonformating'] = 'تنسيق درس';
$string['lessonmenu'] = 'قائمة الدرس';
$string['lessonnotready'] = 'هذا الدرس ليس جاهزاً لأخذه . يرجى الاتصال ب {$a}';
$string['lessonopen'] = 'سيتم اتاحة هذا الدرس في {$a}';
$string['lessonopens'] = 'الدرس يفتح';
$string['lessonpagelinkingbroken'] = 'الصفحة الأولى غير موجودة .لابد من تعطيل ربط صفحة الدرس .الرجاء الاتصال بالمشرف.';
$string['lessonstats'] = 'أحصائيات درس';
$string['linkedmedia'] = 'ربط الوسائط';
$string['loginfail'] = 'فشلت عملية الدخول، اعد المحاولة';
$string['lowscore'] = 'أقل درجة';
$string['lowtime'] = 'أقل وقت';
$string['manualgrading'] = 'اعطاء درجات للمقالات';
$string['matchesanswer'] = 'طابق مع الاجابة';
$string['matching'] = 'مطابقة';
$string['matchingpair'] = 'مطابقة أزواج {$a}';
$string['maxgrade'] = 'الدرجة القصوى';
$string['maxhighscores'] = 'عدد أعلى درجات معروض';
$string['maximumnumberofanswersbranches'] = 'الحد الأقصى لعدد الاجابات / التفريعات';
$string['maximumnumberofattempts'] = 'الحد الأقصى لعدد المحاولات';
$string['maximumnumberofattemptsreached'] = 'بلغت الحد الأقصى من عدد المحاولات - انتقل للصفحة التالية.';
$string['maxtime'] = 'الوقت المحدد (دقائق)';
$string['maxtimewarning'] = 'تبقى لديك {$a} دقيقة لإنهاء الدرس';
$string['mediaclose'] = 'أظهار أزرار الأغلاق';
$string['mediafile'] = 'منبثق إلى ملف أو صفحة ويب';
$string['mediafilepopup'] = 'أنقر هنا لتعايين';
$string['mediaheight'] = 'ارتفاع نافذه:';
$string['mediawidth'] = 'عرض:';
$string['minimumnumberofquestions'] = 'الحد الأقصى لعدد الأسئلة';
$string['missingname'] = 'الرجاء أدخال الكنية';
$string['modattempts'] = 'اسمح بالمراجعة للطالب';
$string['modattemptsnoteacher'] = 'معاينة الطالب تعمل فقط للطلاب';
$string['modulename'] = 'درس';
$string['modulenameplural'] = 'دروس';
$string['movedpage'] = 'حرك الصفحة';
$string['movepagehere'] = 'أنقل الصفحة إلى هناء';
$string['moving'] = 'نقل الصفحة: {$a}';
$string['multianswer'] = 'متعدد الاجابة';
$string['multipleanswer'] = 'متعدد الاجابة';
$string['nameapproved'] = 'تم الموافقة على الاسم';
$string['namereject'] = 'عذرا,لقد تم رفض اسمك . <br /> الرجاء المجاولة باسم آخر';
$string['nextpage'] = 'الصفحة التلية';
$string['noanswer'] = 'لم تعطى إجابة';
$string['noattemptrecordsfound'] = 'لم يتم العثور على أي سجلات للمحاولة: لذا لم تعطى درجة';
$string['nobranchtablefound'] = 'لم يتم العثور على جدول فرعي';
$string['nocommentyet'] = 'لا يوجد أي تعليق بعد';
$string['nocoursemods'] = 'لم يتم العثور على أنشطة';
$string['nocredit'] = 'لا يوجد رصيد';
$string['nodeadline'] = 'لا يوجد موعد نهائي';
$string['noessayquestionsfound'] = 'لا يوجد أسئله مقاليه في هذا الدرس';
$string['nohighscores'] = 'لا توجد درجة قصوى';
$string['nolessonattempts'] = 'لم يتم إجراء محاولات مسبقة في هذا الدرس';
$string['nooneansweredcorrectly'] = 'لم يقم أي شخص بإعطاء الاجابة الصحيحة';
$string['nooneansweredthisquestion'] = 'لم يقم أي شخص بإعطاء الاجابة الصحيحة لهذا السؤال';
$string['noonecheckedthis'] = 'لم يقم أي شخص بالتحقق من هذا';
$string['nooneenteredthis'] = 'لم يقم أي شخص بادخال هذا';
$string['noonehasanswered'] = 'لم يقم أي شخص بالإجابة على السؤال المقالي بعد';
$string['noretake'] = 'غير مسموح لك بإعادة هذا الدرس';
$string['normal'] = 'عادي - تابع مسار الدرس';
$string['notcompleted'] = 'لم يتم انهائه';
$string['notdefined'] = 'لم يعرف';
$string['nothighscore'] = 'لم تقم بعمل أعلى {$a} درجات في قائمة الدرجات.';
$string['notitle'] = 'لا يوجد عنوان';
$string['numberofcorrectanswers'] = 'عدد الاجابات الصحيحة: {$a}';
$string['numberofcorrectmatches'] = 'عدد الاجابات الصحيصة المتطابقة: {$a}';
$string['numberofpagestoshow'] = 'عدد الصفحات (البطاقات) التي تظهر: {$a}';
$string['numberofpagesviewed'] = 'عدد الصفحات التي تم مشاهدتها: {$a}';
$string['numberofpagesviewednotice'] = 'عدد الأسئلة التي أجبت عليها : {$a->nquestions},(يجب أن تجيب عل الأقل {$a->minquestions})';
$string['numerical'] = 'رقمي';
$string['ongoing'] = 'عرض النتيجة الجارية';
$string['ongoingcustom'] = 'لقد حصلت على {$a->score} نقطة(نقاط) من أصل {$a->currenthigh} نقطة(نقاط) حتى الآن';
$string['ongoingnormal'] = 'لقد اجبت على {$a->correct} بشكل صحيح من أصل {$a->viewed} محاولات';
$string['options'] = 'خيارات';
$string['or'] = 'أو';
$string['ordered'] = 'رتب';
$string['other'] = 'أخر';
$string['outof'] = 'من {$a}';
$string['overview'] = 'عرض عام';
$string['page'] = 'صفحة: {$a}';
$string['pagecontents'] = 'محتويات الصفحة';
$string['pages'] = 'صفحات';
$string['pagetitle'] = 'عنوان الصفحة';
$string['password'] = 'كلمة مرور';
$string['passwordprotectedlesson'] = '{$a} درس مؤمن بكلمة مرور';
$string['pleasecheckoneanswer'] = 'الرجاء اختيار إجابة واحدة';
$string['pleasecheckoneormoreanswers'] = 'الرجاء اختيار إجابة واحدة أو أكثر';
$string['pleaseenteryouranswerinthebox'] = 'الرجاء إدخال إجابتك في الربع الحواري';
$string['pleasematchtheabovepairs'] = 'الرجاء مقابلة الزوجين السابقيين';
$string['pluginadministration'] = 'إدارة الدرس';
$string['pluginname'] = 'درس';
$string['pointsearned'] = 'النقاط المكتسبة';
$string['postsuccess'] = 'تمت المشاركة بنجاح';
$string['practice'] = 'درس تدريبي';
$string['preview'] = 'معاينه';
$string['previewlesson'] = 'معاينة {$a}';
$string['previouspage'] = 'الصفحة السابقة';
$string['progressbar'] = 'شريط التقدم';
$string['progressbarteacherwarning'] = 'شريط التقدم لا يعرض ل {$a}';
$string['qtype'] = 'نوع الصفحة';
$string['question'] = 'سؤال';
$string['questionoption'] = 'خيار السؤال';
$string['questiontype'] = 'نوع السؤال';
$string['randombranch'] = 'محتوى صفحة عشوائي';
$string['randompageinbranch'] = 'سؤال عشوائي داخل الفرع';
$string['rank'] = 'مستوى';
$string['rawgrade'] = 'الدرجة الصافية';
$string['receivedcredit'] = 'استلام الرصيد';
$string['redisplaypage'] = 'إعادة عرض الصفحة';
$string['report'] = 'تقرير';
$string['reports'] = 'تقارير';
$string['response'] = 'إجابة';
$string['returnto'] = 'العودة الى {$a}';
$string['returntocourse'] = 'العودة إلى المنهج الدراسي';
$string['review'] = 'مراجعة';
$string['reviewlesson'] = 'مراجعة الدرس';
$string['reviewquestionback'] = 'نعم، أرغب في المحاولة ثانياً';
$string['reviewquestioncontinue'] = 'لا ،أريد فقط أن انتقل إلى السؤال التالي';
$string['sanitycheckfailed'] = 'فشل التحقق من سلامة العقل : لقد تم حذف هذه المحاولة';
$string['savechanges'] = 'أحفظ التغيرات';
$string['savechangesandeol'] = 'أحفظ كل التغيرات ثم أذهب إلى أخر الدرس';
$string['savepage'] = 'حفظ الصفحة';
$string['score'] = 'درجة';
$string['scores'] = 'درجات';
$string['secondpluswrong'] = 'ليس تماماً . هل ترغب بإعادة المحاولة ؟';
$string['selectaqtype'] = 'اختر نوع السؤال';
$string['shortanswer'] = 'إجابة قصيرة';
$string['showanunansweredpage'] = 'أظهر الصفحة التي لم يتم الإجابة عليها';
$string['showanunseenpage'] = 'أظهر الصفحة الغير مرئيه';
$string['singleanswer'] = 'إجابة مفردة';
$string['skip'] = 'تخطى التنقل';
$string['slideshow'] = 'عرض سلايدات';
$string['slideshowbgcolor'] = 'لون خلفية عرض الشرائح';
$string['slideshowheight'] = 'ارتفاع عرض الشرائح';
$string['slideshowwidth'] = 'عرض عرض الشرائح';
$string['startlesson'] = 'أبداء الدرس';
$string['studentattemptlesson'] = '{$a->lastname}, {$a->firstname}\'s عدد المحاولة {$a->attempt}';
$string['studentname'] = '{$a} الأسم';
$string['studentoneminwarning'] = 'تحذير : لديك دقيقة واحدة أو أقل لإنهاء الدرس.';
$string['studentresponse'] = '{$a}\'s رد';
$string['submitname'] = 'تقديم الاسم';
$string['teacherjumpwarning'] = 'An {$a->cluster} jump or an {$a->unseen} jump is being used in this lesson. The Next Page jump will be used instead. Login as a student to test these jumps.';
$string['teacherongoingwarning'] = 'يتم عرض الدرجة الجارية للطلاب فقط . الدخول كطالب لاختبار الدرجة الجارية';
$string['teachertimerwarning'] = 'المؤقت يعمل فقط للطلاب. اختبار الموقت عن طريق تسجيل الدخول كطالب';
$string['thatsthecorrectanswer'] = 'هذه إجابة صحيحة';
$string['thatsthewronganswer'] = 'هذه إجابة خاطئة';
$string['thefollowingpagesjumptothispage'] = 'الصفحات التالية تقفز إلى هذه الصفحة';
$string['thispage'] = 'هذه الصفحة';
$string['timeremaining'] = 'الزمن المتبقى';
$string['timespenterror'] = 'قضى ما لا يقل عن {$a} دقائق في الدرس';
$string['timespentminutes'] = 'الوقت الذي تم قضاءه (دقائق)';
$string['timetaken'] = 'الزمن المستنفذ';
$string['topscorestitle'] = 'أعلى {$a} الدرجات العالية';
$string['truefalse'] = 'صح/خطاء';
$string['unseenpageinbranch'] = 'سؤال خفي ضمن الفرع';
$string['unsupportedqtype'] = 'نوع سؤال غير معتمد({$a})!';
$string['updatedpage'] = 'حدث الصفحة';
$string['updatefailed'] = 'تعثر التحديث';
$string['usemaximum'] = 'استخدم الحد الأقصى';
$string['usemean'] = 'استخدم المتوسط الحسابي';
$string['usepassword'] = 'درس محمي بكلمة مرور';
$string['viewgrades'] = 'عرض الدرجات';
$string['viewhighscores'] = 'عرض قائمة الدرجات العليا';
$string['viewreports'] = 'معاينة {$a->attempts} كاملة {$a->student} محاولات';
$string['welldone'] = 'أحسنت!';
$string['whatdofirst'] = 'ماذا تريد ان تفعل أولا؟';
$string['wronganswerjump'] = 'أقفز اجابة خاطئة';
$string['wronganswerscore'] = 'درجة الإجابة الخاطئة';
$string['wrongresponse'] = 'إجابة خاطئة';
$string['xattempts'] = '{$a} محاولات';
$string['youhaveseen'] = 'لقد شاهدت فعلياً أكثر من صفحة واحدة من هذا الدرس .<br /> هل ترغب بالبدء من آخر صفحه شاهدتها ؟';
$string['youmadehighscore'] = 'جعلته على أعلى {$a} قائمة الدرجات العالية';
$string['youranswer'] = 'إجابتك';
$string['yourcurrentgradeis'] = 'درجتك الحالية هي {$a}';
$string['yourcurrentgradeisoutof'] = 'درجتك الحالية هي {$a->grade} من أصل {$a->total}';
$string['youshouldview'] = 'على الأقل يمكنك مشاهدة {$a}';
|
gpl-3.0
|
jadhachem/ghost-wanderer
|
src/red_ghost.cpp
|
991
|
/**
* Copyright (C) 2014 Jad Hachem <jad.hachem@gmail.com>
*
* This file is part of Ghost Wanderer.
*
* Ghost Wanderer 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.
*
* Ghost Wanderer 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 "ghost.hpp"
#include "red_ghost.hpp"
#include <SFML/Graphics.hpp>
RedGhost::RedGhost() : Ghost() {
setColor( sf::Color::Magenta );
bounces = true;
}
BumpEvent RedGhost::bumpEvent() {
return BumpEvent::LOSE;
}
|
gpl-3.0
|
abmindiarepomanager/ABMOpenMainet
|
Mainet1.1/MainetServiceParent/MainetServiceRnL/src/main/java/com/abm/mainet/rnl/ui/controller/PropFreezeController.java
|
7149
|
package com.abm.mainet.rnl.ui.controller;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.abm.mainet.common.constant.MainetConstants;
import com.abm.mainet.common.constant.PrefixConstants;
import com.abm.mainet.common.service.ILocationMasService;
import com.abm.mainet.common.ui.controller.AbstractFormController;
import com.abm.mainet.common.ui.model.JQGridResponse;
import com.abm.mainet.common.utility.LookUp;
import com.abm.mainet.common.utility.UserSession;
import com.abm.mainet.common.utility.UtilityService;
import com.abm.mainet.rnl.service.IEstateBookingService;
import com.abm.mainet.rnl.service.IEstatePropertyService;
import com.abm.mainet.rnl.ui.model.PropFreezeModel;
/**
* @author ritesh.patil
*
*/
@Controller
@RequestMapping("/PropFreeze.html")
public class PropFreezeController extends AbstractFormController<PropFreezeModel> {
@Autowired
private ILocationMasService iLocationMasService;
@Autowired
private IEstateBookingService iEstateBookingService;
@Autowired
private IEstatePropertyService iEstatePropertyService;
@RequestMapping(method = RequestMethod.POST)
public String index(final Model uiModel, final HttpServletRequest httpServletRequest) {
sessionCleanup(httpServletRequest);
return MainetConstants.PropFreeze.PROP_FREEZE_LIST;
}
/**
* Get Freeze Property Grid data
* @param request
* @return
*/
@RequestMapping(params = "getGridData", produces = "application/json", method = RequestMethod.POST)
public @ResponseBody JQGridResponse<? extends Serializable> geGridResults(
final HttpServletRequest httpServletRequest, @RequestParam final String page,
@RequestParam final String rows) {
return getModel().paginate(httpServletRequest, page, rows, iEstateBookingService.findAllFreezeBookingProp(
UserSession.getCurrent().getOrganisation().getOrgid(), MainetConstants.RnLCommon.F_FLAG));
}
/**
* Shows a form page in order to create a new Estate
* @param model
* @return
*/
@RequestMapping(params = "form", method = RequestMethod.POST)
public ModelAndView formForCreate(@RequestParam(value = "propId", required = false) final Long propId,
@RequestParam(value = "type", required = false) final String modeType) {
final PropFreezeModel propFreezeModel = getModel();
propFreezeModel.setModeType(MainetConstants.RnLCommon.MODE_CREATE);
propFreezeModel.setLocationList(
iLocationMasService.getLocationNameByOrgId(UserSession.getCurrent().getOrganisation().getOrgid()));
return new ModelAndView(MainetConstants.PropFreeze.PROP_FREEZE_FORM, MainetConstants.FORM_NAME, propFreezeModel);
}
@ResponseBody
@RequestMapping(params = "propList", method = RequestMethod.POST)
public List<Object[]> getPropertyList(@RequestParam("esId") final Long esId) {
final List<Object[]> list = iEstatePropertyService.findPropertiesForEstate(
UserSession.getCurrent().getOrganisation().getOrgid(), esId, PrefixConstants.CPD_VALUE_RENT,
PrefixConstants.CATEGORY_PREFIX_NAME);
return list;
}
@ResponseBody
@RequestMapping(params = "getVisibleDates", method = RequestMethod.POST)
public List<String> getvisibledates(@RequestParam("propId") final long propId) {
final List<String> fromAndtoDate = iEstateBookingService.getEstateBookingFromAndToDates(propId,
UserSession.getCurrent().getOrganisation().getOrgid());
return fromAndtoDate;
}
@ResponseBody
@RequestMapping(params = "unFreezeProp", method = RequestMethod.POST)
public boolean deActiveEstateId(@RequestParam("id") final Long id) {
iEstateBookingService.updateFreezeProperty(id, UserSession.getCurrent().getEmployee().getEmpId());
return true;
}
@RequestMapping(params = "getShiftsBasedOnDate", method = { RequestMethod.GET, RequestMethod.POST })
public @ResponseBody List<LookUp> getShiftsBasedOnDate(@RequestParam("fromDate") final String fromDate,
@RequestParam("toDate") final String toDate,
@RequestParam("propId") final Long propId) {
List<LookUp> lookup = null;
try {
lookup = iEstateBookingService.getEstateBookingShifts(propId, fromDate, toDate,
UserSession.getCurrent().getOrganisation().getOrgid());
} catch (final Exception exception) {
logger.error("Exception found in getShiftsBasedOnDate method: ", exception);
}
return lookup;
}
@RequestMapping(params = "dateRangBetBookedDate", method = { RequestMethod.GET, RequestMethod.POST })
public @ResponseBody String dateRangBetBookedDate(@RequestParam("fromDate") final String fromDate,
@RequestParam("toDate") final String toDate,
@RequestParam("propId") final Long propId, final HttpServletRequest httpServletRequest) {
String flag = MainetConstants.EstateBooking.PASS;
try {
final List<String> fromAndtoDate = iEstateBookingService.getEstateBookingFromAndToDatesForGeneral(propId,
UserSession.getCurrent().getOrganisation().getOrgid());
final Calendar calendar = new GregorianCalendar();
final Date dateFrom = UtilityService.convertStringDateToDateFormat(fromDate);
final Date dateTo = UtilityService.convertStringDateToDateFormat(toDate);
calendar.setTime(dateFrom);
final List<String> bookedDate = new ArrayList<>();
while (calendar.getTime().before(dateTo) || calendar.getTime().equals(dateTo)) {
final Date result = calendar.getTime();
bookedDate.add(new SimpleDateFormat(MainetConstants.CommonConstants.DATE_F).format(result));
calendar.add(Calendar.DATE, 1);
}
for (final String date : bookedDate) {
if (fromAndtoDate.contains(date)) {
flag = MainetConstants.EstateBooking.FAIL;
;
break;
}
}
} catch (final Exception exception) {
logger.error("Exception found in dateRangBetBookedDate method: ", exception);
}
return flag;
}
}
|
gpl-3.0
|
hmemcpy/milewski-ctfp-pdf
|
src/content/1.9/code/scala/snippet05.scala
|
51
|
val greet: String => String =
catstr("Hello ", _)
|
gpl-3.0
|
biddingproject/OnlineBiddingSystem
|
BiddingSystem/ejb/src/main/java/com/bidding/model/Transaction.java
|
3229
|
package com.bidding.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
public class Transaction implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8948953875453666442L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name = "price_bought")
private Float priceBought;
@Size(min = 10, max = 1000)
@NotNull
private String description;
@ManyToOne
@JoinColumn(name="item_list_id")
private ItemList itemList;
@ManyToOne
@JoinColumn(name="customer_id")
private Customer customer;
@DecimalMax(value = "5")
private int rating;
@Size(max = 180)
private String customerReview;
@Temporal(TemporalType.TIMESTAMP)
private Date itemBoughtTime;
private int quantity;
private float disCountRate = 0.0f;
private boolean isRefunded = false;
private float transactionAmount;
@OneToOne
private Refund refund;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getPriceBought() {
return priceBought;
}
public void setPriceBought(Float priceBought) {
this.priceBought = priceBought;
}
public ItemList getItemList() {
return itemList;
}
public void setItemList(ItemList itemList) {
this.itemList = itemList;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getCustomerReview() {
return customerReview;
}
public void setCustomerReview(String customerReview) {
this.customerReview = customerReview;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public Date getItemBoughtTime() {
return itemBoughtTime;
}
public void setItemBoughtTime(Date itemBoughtTime) {
this.itemBoughtTime = itemBoughtTime;
}
public boolean isRefunded() {
return isRefunded;
}
public void setRefunded(boolean isRefunded) {
this.isRefunded = isRefunded;
}
public Refund getRefund() {
return refund;
}
public void setRefund(Refund refund) {
this.refund = refund;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getDisCountRate() {
return disCountRate;
}
public void setDisCountRate(float disCountRate) {
this.disCountRate = disCountRate;
}
public float getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(float transactionAmount) {
this.transactionAmount = transactionAmount;
}
}
|
gpl-3.0
|
BenjaminDHorne/Open-Source-Basketball-Heat-Map-Maker
|
GenerateHeatMap.py
|
18928
|
#matplotlib inline
#import requests
import sys
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf
import matplotlib
import pandas as pd
import seaborn as sns
from matplotlib.patches import Circle, Rectangle, Arc
from local_libs.option_d import test_cm as viridis # another file i have
#from PIL import Image
import os
import numpy as np
from scipy.misc import imread
from PyPDF2 import PdfFileMerger
''' libraries needed to run '''
'''
python 2.7
matplotlib
pandas
seaborn
option_d file (local file not library)
PIL
os
'''
''' ONLY CHANGE VARABLES WITHIN PROPERTIES COMMENT!!! '''
'''PROPERTIES BELOW'''
#Change this to input file name, must be CSV file created by StoreShots.py
input_file_name = "input.csv"
heat_map_type = "basic" #OPTIONS: basic, hex, coolwarm, blue
sections = True
expanded_shot_points = True
'''PROPERTIES ABOVE'''
basic_makes_and_misses = []
basic_points_per_shot = []
files = []
position_locations = [(0,23),(120,23),(0,120),(-120,23),(-185,23),(-145,140),(0,200),(145,140),(185,23),(245,23),(200,210),(0,275),(-200,210),(-245,23)]
position_points = [2,2,2,2,2,2,2,2,2,3,3,3,3,3]
def draw_court(ax=None, color='black', lw=3, outer_lines=False):
# If an axes object isn't provided to plot onto, just get current one
if ax is None:
ax = plt.gca()
# Create the various parts of an NBA basketball court
# Create the basketball hoop
# Diameter of a hoop is 18" so it has a radius of 9", which is a value
# 7.5 in our coordinate system
hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False)
# Create backboard
backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color)
# The paint
# Create the outer box 0f the paint, width=16ft, height=19ft
outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color,
fill=False)
# Create the inner box of the paint, widt=12ft, height=19ft
inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color,
fill=False)
# Create free throw top arc
top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180,
linewidth=lw, color=color, fill=False)
# Create free throw bottom arc
bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0,
linewidth=lw, color=color, linestyle='dashed')
# Restricted Zone, it is an arc with 4ft radius from center of the hoop
restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw,
color=color)
# Three point line
# Create the side 3pt lines, they are 14ft long before they begin to arc
corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw,
color=color)
corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color)
# 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop
# I just played around with the theta values until they lined up with the
# threes
three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw,
color=color)
# Center Court
center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0,
linewidth=lw, color=color)
center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0,
linewidth=lw, color=color)
# List of the court elements to be plotted onto the axes
court_elements = [hoop, backboard, outer_box, inner_box, top_free_throw,
bottom_free_throw, restricted, corner_three_a,
corner_three_b, three_arc, center_outer_arc,
center_inner_arc]
if outer_lines:
# Draw the half court line, baseline and side out bound lines
outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw,
color=color, fill=False)
court_elements.append(outer_lines)
''' bens attempt at making section lines '''
if sections:
sec_color = "white"
s1 = Circle((0, 0), radius=70, linewidth=3, color=sec_color, fill=False)
court_elements.append(s1)
s2 = Circle((0, 0), radius=165, linewidth=3, color=sec_color, fill=False)
court_elements.append(s2)
s3 = Arc((80, 81), 95, 0, angle=50, linewidth=3, color=sec_color)
court_elements.append(s3)
s4 = Arc((-80, 81), 95, 0, angle=-50, linewidth=3, color=sec_color)
court_elements.append(s4)
s3 = Arc((89, 176), 76, 0, angle=50, linewidth=3, color=sec_color)
court_elements.append(s3)
s4 = Arc((-89, 176), 76, 0, angle=-50, linewidth=3, color=sec_color)
court_elements.append(s4)
s5 = three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=3, color="black")
court_elements.append(s5)
s6 = Rectangle((-220, -47.5), 0, 140, linewidth=3, color="black")
court_elements.append(s6)
s7 = Rectangle((220, -47.5), 0, 140, linewidth=3, color="black")
court_elements.append(s7)
s8 = Arc((185, 75), 86, 0, angle=50, linewidth=3, color=sec_color)
court_elements.append(s8)
s9 = Arc((-185, 75), 86, 0, angle=-50, linewidth=3, color=sec_color)
court_elements.append(s9)
s10 = Circle((0, 0), radius=350, linewidth=3, color=sec_color, fill=False)
court_elements.append(s10)
s11 = Arc((232, 94), 30, 0, angle=0, linewidth=3, color=sec_color)
court_elements.append(s11)
s12 = Arc((-232, 94), 30, 0, angle=0, linewidth=3, color=sec_color)
court_elements.append(s12)
s13 = Arc((110, 270), 120, 0, angle=50, linewidth=3, color=sec_color)
court_elements.append(s13)
s14 = Arc((-110, 270), 120, 0, angle=-50, linewidth=3, color=sec_color)
court_elements.append(s14)
# Add the court elements onto the axes
for element in court_elements:
ax.add_patch(element)
return ax
def get_norm(made, avgs, stds, avgs_pt, stds_pt):
basic_makes_and_misses = []
basic_points_per_shot = []
i=0
while i < len(position_num):
if stds[i] == 0:
stds[i]+=0.000001 #almost no stddev, this is a bad solution, but yeah.
percent = (float(made[i]) - avgs[i])/stds[i]
basic_makes_and_misses.append(percent)
#print made[i], avgs[i], stds[i], avgs_pt[i], stds_pt[i]
if stds_pt[i] == 0:
stds_pt[i]+=0.000001
points_eff = ((float(made[i])*float(position_points[i])/10)-avgs_pt[i])/stds_pt[i]
basic_points_per_shot.append(points_eff)
i+=1
return basic_makes_and_misses, basic_points_per_shot
def convert_input_file(input_file_name):
with open(input_file_name) as f:
content = [x.strip().split(",") for x in f]
kids = content.pop(0)
del kids[0]
kids.append(None) # dummy
position_num = [x[0] for x in content]
makes = []
y=0
for k in kids:
makes.append([x[y] for x in content])
y+=1
del makes[0]
return kids, makes, position_num
def setup_stats(made):
i=0
basic_makes_and_misses = []
basic_points_per_shot = []
while i < len(position_num):
percent = float(made[i])/10
basic_makes_and_misses.append(percent)
points_eff = float(made[i])*int(position_points[i])
basic_points_per_shot.append(points_eff)
i+=1
return basic_makes_and_misses, basic_points_per_shot
if __name__ == "__main__":
print "Generating plot from input.csv..."
try:
os.remove("./converted_input_file.temp.csv")
except OSError:
pass
kids, makes, position_num = convert_input_file(input_file_name)
points = []
running_sum = [0]*len(makes[0]); running_sum2 = [0]*len(makes[0])
if heat_map_type != "basic":
data = pd.read_csv(input_file_name)
#shot_df = pd.DataFrame(shots, columns=headers)
shot_df = data
# View the head of the DataFrame and all its columns
from IPython.display import display
with pd.option_context('display.max_columns', None):
display(shot_df.head())
if heat_map_type == "basic":
#store_all_scores("all_makes_and_misses.csv", "all_points.csv")
# heatmap based on makes vs misses
#norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
k_num = 0
while k_num < len(kids)-1:
print "Processing...", kids[k_num]
plt.clf()
basic_makes_and_misses, basic_points_per_shot = setup_stats(makes[k_num])
ax = plt.subplot()#joint_shot_chart.ax_joint
draw_court(ax)
basic_makes_and_misses = [float(u) for u in basic_makes_and_misses]
xs = [p[0] for p in position_locations]
ys = [p[1] for p in position_locations]
plt.scatter(xs, ys, s=800, c=basic_makes_and_misses, cmap="coolwarm")
plt.clim(0,1)
cbar = plt.colorbar(ticks=[0, 0.5, 1])
cbar.ax.set_yticklabels(['0%', '50%', '100%'])
img = imread("./images/wood.jpg")
plt.imshow(img, extent=[-450, 450, 450, -450])
# Adjust the axis limits and orientation of the plot in order
# to plot half court, with the hoop by the top of the plot
ax.set_xlim(-250,250)
ax.set_ylim(422.5, -47.5)
# Get rid of axis labels and tick marks
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')
plt.title("%s Makes per Location"%(kids[k_num]))
with matplotlib.backends.backend_pdf.PdfPages("%s_temp.pdf"%(kids[k_num])) as pdf:
files.append("%s_temp.pdf"%(kids[k_num]))
pdf.savefig()
plt.close()
#plt.show()
#heatmap based on points
plt.clf()
ax = plt.subplot()#joint_shot_chart.ax_joint
draw_court(ax)
basic_points_per_shot = [float(u)/10 for u in basic_points_per_shot]
xs = [p[0] for p in position_locations]
ys = [p[1] for p in position_locations]
plt.scatter(xs, ys, s=800, c=basic_points_per_shot, cmap="coolwarm")
plt.clim(0,3)
cbar = plt.colorbar(ticks=[0, 1.5, 3])
#cbar.ax.set_yticklabels(['0%', '50%', '100%'])
img = imread("./images/wood.jpg")
plt.imshow(img, extent=[-450, 450, 450, -450])
# Adjust the axis limits and orientation of the plot in order
# to plot half court, with the hoop by the top of the plot
ax.set_xlim(-250,250)
ax.set_ylim(422.5, -47.5)
# Get rid of axis labels and tick marks
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')
plt.title("%s Point Efficiency (Points per Shot)"%(kids[k_num]))
with matplotlib.backends.backend_pdf.PdfPages("%s_temp2.pdf"%(kids[k_num])) as pdf:
files.append("%s_temp2.pdf"%(kids[k_num]))
pdf.savefig()
plt.close()
#plt.show()
k_num+=1
bb = 0
for b in basic_makes_and_misses:
running_sum[bb]+=b
bb+=1
pp = 0
for p in basic_points_per_shot:
running_sum2[pp]+=p
pp+=1
points.append(basic_points_per_shot)
makes_avgs = [float(rs)/len(kids) for rs in running_sum]
#makes_avgs = ["{0:.2f}".format(fl) for fl in makes_avgs]
makes_avgs = [float(fl) for fl in makes_avgs]
makes_avgs = makes_avgs[:14]
pts_avgs = [float(rs2)/len(kids) for rs2 in running_sum2]
pts_avgs = pts_avgs[:14]
plt.clf()
ax = plt.subplot()#joint_shot_chart.ax_joint
draw_court(ax)
xs = [p[0] for p in position_locations]
ys = [p[1] for p in position_locations]
plt.scatter(xs, ys, s=800, c=makes_avgs, cmap="coolwarm")
plt.clim(0,1)
cbar = plt.colorbar(ticks=[0, 0.5, 1])
cbar.ax.set_yticklabels(['0%', '50%', '100%'])
img = imread("./images/wood.jpg")
plt.imshow(img, extent=[-450, 450, 450, -450])
# Adjust the axis limits and orientation of the plot in order
# to plot half court, with the hoop by the top of the plot
ax.set_xlim(-250,250)
ax.set_ylim(422.5, -47.5)
# Get rid of axis labels and tick marks
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')
plt.title("Average Makes per Location")
with matplotlib.backends.backend_pdf.PdfPages("average_temp.pdf") as pdf:
files.append("average_temp.pdf")
pdf.savefig()
plt.close()
plt.clf()
ax = plt.subplot()#joint_shot_chart.ax_joint
draw_court(ax)
xs = [p[0] for p in position_locations]
ys = [p[1] for p in position_locations]
plt.scatter(xs, ys, s=800, c=pts_avgs, cmap="coolwarm")
plt.clim(0,3)
cbar = plt.colorbar(ticks=[0, 1.5, 3])
#cbar.ax.set_yticklabels(['0%', '50%', '100%'])
img = imread("./images/wood.jpg")
plt.imshow(img, extent=[-450, 450, 450, -450])
# Adjust the axis limits and orientation of the plot in order
# to plot half court, with the hoop by the top of the plot
ax.set_xlim(-250,250)
ax.set_ylim(422.5, -47.5)
# Get rid of axis labels and tick marks
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')
plt.title("Average Point Efficiency (Points per Shot)")
with matplotlib.backends.backend_pdf.PdfPages("average_temp2.pdf") as pdf:
files.append("average_temp2.pdf")
pdf.savefig()
plt.close()
## # get stds, this looks crazy, but I was in a hurry :(
## make_stds = [];pts_stds =[]
## flipped = []
## [flipped.append([]) for flip in xrange(14)]
## flippedp = []
## [flippedp.append([]) for flip in xrange(14)]
##
## for m_col in makes:
## el=0
## while el < len(m_col):
## flipped[el].append(m_col[el])
## el+=1
## for m_row in flipped:
## m_row = map(float, m_row)
## make_stds.append(np.std(m_row))
## # same logic as above, but var changes, this should be modularized
## for p_col in points:
## elp=0
## while elp < len(m_col):
## flippedp[elp].append(p_col[elp])
## elp+=1
## for p_row in flippedp:
## p_row = map(float,p_row)
## pts_stds.append(np.std(p_row))
##
## k_num = 0
## while k_num < len(kids)-1:
## plt.clf()
## norm_makes_and_misses, norm_points_per_shot = get_norm(makes[k_num],makes_avgs, make_stds, pts_avgs, pts_stds)
## ax = plt.subplot()#joint_shot_chart.ax_joint
## draw_court(ax)
## norm_points_per_shot = [int(u) for u in norm_points_per_shot]
## xs = [p[0] for p in position_locations]
## ys = [p[1] for p in position_locations]
## plt.scatter(xs, ys, s=800, c=norm_points_per_shot, cmap="coolwarm")
## plt.clim(0,5)
##
## plt.colorbar()
## img = imread("./images/wood.jpg")
## plt.imshow(img, extent=[-450, 450, 450, -450])
##
##
## # Adjust the axis limits and orientation of the plot in order
## # to plot half court, with the hoop by the top of the plot
## ax.set_xlim(-250,250)
## ax.set_ylim(422.5, -47.5)
##
## # Get rid of axis labels and tick marks
## ax.set_xlabel('')
## ax.set_ylabel('')
## ax.tick_params(labelbottom='off', labelleft='off')
## plt.title("Normalized %s Point Efficiency (Points per Shot)"%(kids[k_num]))
##
## with matplotlib.backends.backend_pdf.PdfPages("%s_temp2_norm.pdf"%(kids[k_num])) as pdf:
## files.append("%s_temp2_norm.pdf"%(kids[k_num]))
## pdf.savefig()
## plt.close()
##
## #plt.show()
##
## plt.clf()
## ax = plt.subplot()#joint_shot_chart.ax_joint
## draw_court(ax)
## norm_makes_and_misses = [float(u) for u in norm_makes_and_misses]
## xs = [p[0] for p in position_locations]
## ys = [p[1] for p in position_locations]
## plt.scatter(xs, ys, s=800, c=norm_makes_and_misses, cmap="coolwarm")
## plt.clim(0,5)
##
## plt.colorbar()
## img = imread("./images/wood.jpg")
## plt.imshow(img, extent=[-450, 450, 450, -450])
##
##
## # Adjust the axis limits and orientation of the plot in order
## # to plot half court, with the hoop by the top of the plot
## ax.set_xlim(-250,250)
## ax.set_ylim(422.5, -47.5)
##
## # Get rid of axis labels and tick marks
## ax.set_xlabel('')
## ax.set_ylabel('')
## ax.tick_params(labelbottom='off', labelleft='off')
## plt.title("Normalized %s Makes per Location"%(kids[k_num]))
##
## with matplotlib.backends.backend_pdf.PdfPages("%s_temp_norm.pdf"%(kids[k_num])) as pdf:
## files.append("%s_temp_norm.pdf"%(kids[k_num]))
## pdf.savefig()
## plt.close()
## k_num+=1
print "removing temp files... do not close...."
pdfs = files
pdfs.sort()
outfile = PdfFileMerger()
[outfile.append(open(f, 'rb')) for f in pdfs]
outfile.write(open('result.pdf', 'wb'))
[os.remove(fo) for fo in pdfs]
outfile.close()
plt.close('all')
#sys.exit(-1) #yeah i shouldnt have to do this but whatever
|
gpl-3.0
|
Construo/construo
|
src/save_gui_manager.hpp
|
1056
|
// Construo - A wire-frame construction game
// Copyright (C) 2002 Ingo Ruhnke <grumbel@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef HEADER_CONSTRUO_SAVE_GUI_MANAGER_HPP
#define HEADER_CONSTRUO_SAVE_GUI_MANAGER_HPP
#include "gui_manager.hpp"
/** */
class SaveGUIManager : public GUIManager
{
private:
GUIFileManager* file_manager;
public:
SaveGUIManager ();
void draw_overlay ();
void run_once ();
};
#endif
/* EOF */
|
gpl-3.0
|
sorab2142/sorabpithawala-magicgrove
|
source/Grove/Gameplay/Effects/ExileCard.cs
|
350
|
namespace Grove.Gameplay.Effects
{
public class ExileCard : Effect
{
private readonly DynParam<Card> _card;
private ExileCard() {}
public ExileCard(DynParam<Card> card)
{
_card = card;
RegisterDynamicParameters(card);
}
protected override void ResolveEffect()
{
_card.Value.Exile();
}
}
}
|
gpl-3.0
|
smap-consulting/smapserver
|
sdDAL/src/org/smap/sdal/model/EmailServer.java
|
259
|
package org.smap.sdal.model;
/*
* Form Class
* Used for storing details of an email server
*/
public class EmailServer {
public String smtpHost;
public String emailDomain;
public String emailUser;
public String emailPassword;
public int emailPort;
}
|
gpl-3.0
|
Victor-Haefner/polyvr
|
src/core/utils/zipper/filesystem.cpp
|
1395
|
#include "filesystem.h"
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
bool FILESYSTEM::isFile(const string& path) {
return fs::is_regular_file(path);
}
bool FILESYSTEM::isDir(const string& path) {
return fs::is_directory(path);
}
bool FILESYSTEM::exist(const string& path) {
return fs::exists(path);
}
string FILESYSTEM::baseName(const string& path) {
fs::path p(path);
return p.stem().string();
}
string FILESYSTEM::fileName(const string& path) {
fs::path p(path);
return p.filename().string();
}
string FILESYSTEM::dirName(const string& path) {
fs::path p(path);
return p.parent_path().string();
}
string FILESYSTEM::suffix(const string& path) {
return fs::extension(path);
}
bool FILESYSTEM::createDir(const string & dir) {
fs::path p(dir);
return fs::create_directories(p);
}
bool FILESYSTEM::remove(const string & path) {
return fs::remove_all(path);
}
string FILESYSTEM::normalize(const string & path) {
if (!exist(path)) return path;
return fs::canonical(path).string();
}
vector<string> FILESYSTEM::getFiles(const string& dir) {
vector<string> files;
fs::path path(dir);
fs::recursive_directory_iterator end;
for (fs::recursive_directory_iterator i(path); i != end; ++i) {
const fs::path cp = (*i);
files.push_back(cp.string());
}
return files;
}
|
gpl-3.0
|
lordohatred/GCC
|
World Domination/Assets/Scripts/Gameplay/AICountry.cs
|
2077
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AICountry : MonoBehaviour {
GameObject[] possibleTargets;
GameObject[] enemies;
public Vector2 target;
float speed;
int whatTarget;
int difficulty = 1;
bool canTravel;
int furtherDistance;
// Use this for initialization
void Start () {
if(GameObject.Find("Handler") != null)
SetDifficulty (GameObject.Find ("Handler").GetComponent<Handler> ().GetDifficulty ());
possibleTargets = GameObject.FindGameObjectsWithTag ("Population");
enemies = GameObject.FindGameObjectsWithTag ("Country");
}
// Update is called once per frame
void Update () {
furtherDistance = GetComponent<CountryMotor> ().GetPopulation () / 4;
if (target == null || target == new Vector2 (0, 0) || possibleTargets [whatTarget] == null)
FindNewTarget ();
if (Vector3.Distance (transform.position, target) > 200 + furtherDistance) {
canTravel = false;
FindNewTarget ();
} else
canTravel = true;
if (target != null && target != new Vector2(0,0) && canTravel) {
GetComponent<CountryMotor>().Movement(target);
}
if (enemies == null)
enemies = GameObject.FindGameObjectsWithTag ("Country");
else
CalculateEnemy ();
if (target == new Vector2(transform.position.x, transform.position.y))
FindNewTarget ();
}
void CalculateEnemy(){
for (int i = 0; i < enemies.Length; i++) {
if(enemies[i] != null){
if(Vector3.Distance(enemies[i].transform.position, transform.position) <= 200 + furtherDistance && Vector3.Distance(enemies[i].transform.position, transform.position) > 1) {
if(enemies[i].GetComponent<CountryMotor>().GetPopulation() < this.GetComponent<CountryMotor>().GetPopulation())
target = enemies[i].transform.position;
}
}
}
}
void FindNewTarget(){
possibleTargets = GameObject.FindGameObjectsWithTag ("Population");
whatTarget = Random.Range (0, possibleTargets.Length);
target = possibleTargets[whatTarget].transform.position;
}
public void SetDifficulty(int value){
difficulty = value;
}
}
|
gpl-3.0
|
Niky4000/UsefulUtils
|
projects/tutorials-master/tutorials-master/jackson/src/test/java/com/baeldung/jackson/annotation/extra/ExtraAnnotationUnitTest.java
|
6093
|
package com.baeldung.jackson.annotation.extra;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithAppend;
import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithoutAppend;
import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithIdentityReference;
import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithoutIdentityReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
public class ExtraAnnotationUnitTest {
@Test
public void whenNotUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutIdentityReference bean = new BeanWithoutIdentityReference(1, "Bean Without Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("Bean Without Identity Reference Annotation"));
}
@Test
public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertEquals("1", jsonString);
}
@Test
public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, not(containsString("version")));
assertThat(jsonString, not(containsString("1.0")));
}
@Test
public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, containsString("version"));
assertThat(jsonString, containsString("1.0"));
}
@Test
public void whenUsingJsonNamingAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
NamingBean bean = new NamingBean(3, "Naming Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("bean_name"));
}
@Test
public void whenUsingJsonPropertyDescriptionAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper wrapper = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(PropertyDescriptionBean.class, wrapper);
JsonSchema jsonSchema = wrapper.finalSchema();
String jsonString = mapper.writeValueAsString(jsonSchema);
System.out.println(jsonString);
assertThat(jsonString, containsString("This is a description of the name property"));
}
@Test
public void whenUsingJsonPOJOBuilderAnnotation_thenCorrect() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\":5,\"name\":\"POJO Builder Bean\"}";
POJOBuilderBean bean = mapper.readValue(jsonString, POJOBuilderBean.class);
assertEquals(5, bean.getIdentity());
assertEquals("POJO Builder Bean", bean.getBeanName());
}
@Test
public void whenUsingJsonTypeIdAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
TypeIdBean bean = new TypeIdBean(6, "Type Id Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("Type Id Bean"));
}
@Test
public void whenUsingJsonTypeIdResolverAnnotation_thenCorrect() throws IOException {
TypeIdResolverStructure.FirstBean bean1 = new TypeIdResolverStructure.FirstBean(1, "Bean 1");
TypeIdResolverStructure.LastBean bean2 = new TypeIdResolverStructure.LastBean(2, "Bean 2");
List<TypeIdResolverStructure.AbstractBean> beans = new ArrayList<>();
beans.add(bean1);
beans.add(bean2);
TypeIdResolverStructure.BeanContainer serializedContainer = new TypeIdResolverStructure.BeanContainer();
serializedContainer.setBeans(beans);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(serializedContainer);
assertThat(jsonString, containsString("bean1"));
assertThat(jsonString, containsString("bean2"));
TypeIdResolverStructure.BeanContainer deserializedContainer = mapper.readValue(jsonString, TypeIdResolverStructure.BeanContainer.class);
List<TypeIdResolverStructure.AbstractBean> beanList = deserializedContainer.getBeans();
assertThat(beanList.get(0), instanceOf(TypeIdResolverStructure.FirstBean.class));
assertThat(beanList.get(1), instanceOf(TypeIdResolverStructure.LastBean.class));
}
}
|
gpl-3.0
|
yoxjames/ColdSnap
|
app/src/main/java/com/yoxjames/coldsnap/ui/feed/FeedView.java
|
1159
|
package com.yoxjames.coldsnap.ui.feed;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import com.yoxjames.coldsnap.core.view.BaseColdsnapView;
public class FeedView extends RecyclerView implements BaseColdsnapView<FeedViewModel>
{
private final FeedViewAdapter adapter = new FeedViewAdapter();
public FeedView(@NonNull Context context)
{
super(context);
}
public FeedView(@NonNull Context context, @Nullable AttributeSet attrs)
{
super(context, attrs);
}
public FeedView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public void onFinishInflate()
{
super.onFinishInflate();
setAdapter(adapter);
setLayoutManager(new LinearLayoutManager(getContext()));
}
@Override
public void bindView(FeedViewModel viewModel)
{
adapter.bindView(viewModel);
}
}
|
gpl-3.0
|
hapit/brenda-web2
|
src/app2/landingPage/landing-page.component.ts
|
174
|
import {Component} from '@angular/core'
@Component({
selector: 'app-landing-page',
templateUrl: './landing-page.component.html'
})
export class LandingPageComponent {
}
|
gpl-3.0
|
FabioZumbi12/UltimateChat
|
UltimateChat-Spigot/src/main/java/br/net/fabiozumbi12/UltimateChat/Bukkit/config/UCConfig.java
|
13995
|
/*
Copyright @FabioZumbi12
This class is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any
damages arising from the use of this class.
Permission is granted to anyone to use this class for any purpose, including commercial plugins, and to alter it and
redistribute it freely, subject to the following restrictions:
1 - The origin of this class must not be misrepresented; you must not claim that you wrote the original software. If you
use this class in other plugins, an acknowledgment in the plugin documentation would be appreciated but is not required.
2 - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original class.
3 - This notice may not be removed or altered from any source distribution.
Esta classe é fornecida "como está", sem qualquer garantia expressa ou implícita. Em nenhum caso os autores serão
responsabilizados por quaisquer danos decorrentes do uso desta classe.
É concedida permissão a qualquer pessoa para usar esta classe para qualquer finalidade, incluindo plugins pagos, e para
alterá-lo e redistribuí-lo livremente, sujeito às seguintes restrições:
1 - A origem desta classe não deve ser deturpada; você não deve afirmar que escreveu a classe original. Se você usar esta
classe em um plugin, uma confirmação de autoria na documentação do plugin será apreciada, mas não é necessária.
2 - Versões de origem alteradas devem ser claramente marcadas como tal e não devem ser deturpadas como sendo a
classe original.
3 - Este aviso não pode ser removido ou alterado de qualquer distribuição de origem.
*/
package br.net.fabiozumbi12.UltimateChat.Bukkit.config;
import br.net.fabiozumbi12.UltimateChat.Bukkit.UCChannel;
import br.net.fabiozumbi12.UltimateChat.Bukkit.UChat;
import br.net.fabiozumbi12.UltimateChat.Bukkit.util.UCUtil;
import br.net.fabiozumbi12.UltimateChat.Bukkit.util.UChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Map.Entry;
public class UCConfig {
private static UCCommentedConfig comConfig;
private static YamlConfiguration Prots = new YamlConfiguration();
private final UChat plugin;
public UCConfig(UChat plugin) throws IOException {
this.plugin = plugin;
File main = UChat.get().getDataFolder();
File protections = new File(UChat.get().getDataFolder(), "protections.yml");
if (!main.exists()) {
main.mkdir();
plugin.getUCLogger().info("Created folder: " + UChat.get().getDataFolder());
}
if (!protections.exists()) {
UCUtil.saveResource("/assets/ultimatechat/protections.yml", new File(UChat.get().getDataFolder(), "protections.yml"));
plugin.getUCLogger().info("Created protections file: " + protections.getPath());
//load protections file
Prots = updateFile(protections);
}
//------------------------------ Add default Values ----------------------------//
comConfig = new UCCommentedConfig();
comConfig.addDefaults();
/*------------------------------------------------------------------------------------*/
/* Load Channels */
loadChannels();
/*------------------------------------------------------------------------------------*/
//----------------------------------------------------------------------------------------//
save();
plugin.getUCLogger().info("All configurations loaded!");
}
private static YamlConfiguration updateFile(File saved) {
YamlConfiguration finalyml = new YamlConfiguration();
YamlConfiguration tempProts = new YamlConfiguration();
try {
finalyml.load(saved);
tempProts.load(new InputStreamReader(UChat.get().getResource("assets/ultimatechat/protections.yml"), StandardCharsets.UTF_8));
} catch (Exception e) {
e.printStackTrace();
}
for (String key : tempProts.getKeys(true)) {
Object obj = tempProts.get(key);
if (finalyml.get(key) != null) {
obj = finalyml.get(key);
}
finalyml.set(key, obj);
}
return finalyml;
}
/* Channels */
private void loadChannels() throws IOException {
File chfolder = new File(UChat.get().getDataFolder(), "channels");
if (!chfolder.exists()) {
chfolder.mkdir();
UChat.get().getUCLogger().info("Created folder: " + chfolder.getPath());
}
if (UChat.get().getChannels() == null) {
UChat.get().setChannels(new HashMap<>());
}
File[] listOfFiles = chfolder.listFiles();
YamlConfiguration channel;
if (Objects.requireNonNull(listOfFiles).length == 0) {
//create default channels
File g = new File(chfolder, "global.yml");
channel = YamlConfiguration.loadConfiguration(g);
channel.set("name", "Global");
channel.set("alias", "g");
channel.set("color", "&2");
channel.set("jedis", false);
channel.set("dynmap.enable", true);
channel.save(g);
File l = new File(chfolder, "local.yml");
channel = YamlConfiguration.loadConfiguration(l);
channel.set("name", "Local");
channel.set("alias", "l");
channel.set("color", "&e");
channel.set("jedis", false);
channel.set("across-worlds", false);
channel.set("distance", 40);
channel.save(l);
File ad = new File(chfolder, "admin.yml");
channel = YamlConfiguration.loadConfiguration(ad);
channel.set("name", "Admin");
channel.set("alias", "ad");
channel.set("color", "&b");
channel.set("jedis", false);
channel.save(ad);
listOfFiles = chfolder.listFiles();
}
for (File file : Objects.requireNonNull(listOfFiles)) {
if (file.getName().endsWith(".yml")) {
channel = YamlConfiguration.loadConfiguration(file);
UCChannel ch = new UCChannel(channel.getValues(true));
try {
addChannel(ch);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void delChannel(UCChannel ch) {
for (Entry<List<String>, UCChannel> ch0 : UChat.get().getChannels().entrySet()) {
if (ch0.getValue().getName().equals(ch.getName())) {
UChat.get().getChannels().remove(ch0.getKey());
break;
}
}
File defch = new File(UChat.get().getDataFolder(), "channels" + File.separator + ch.getName().toLowerCase() + ".yml");
if (defch.exists()) {
defch.delete();
}
}
public void addChannel(UCChannel ch) throws IOException {
File defch = new File(UChat.get().getDataFolder(), "channels" + File.separator + ch.getName().toLowerCase() + ".yml");
YamlConfiguration chFile = YamlConfiguration.loadConfiguration(defch);
chFile.options().header(""
+ "###################################################\n"
+ "############## Channel Configuration ##############\n"
+ "###################################################\n"
+ "\n"
+ "This is the channel configuration.\n"
+ "You can change and copy this file to create as many channels you want.\n"
+ "This is the default options:\n"
+ "\n"
+ "name: Global - The name of channel.\n"
+ "alias: g - The alias to use the channel\n"
+ "across-worlds: true - Send messages of this channel to all worlds?\n"
+ "distance: 0 - If across worlds is false, distance to receive this messages.\n"
+ "color: &b - The color of channel\n"
+ "tag-builder: ch-tags,world,clan-tag,marry-tag,group-prefix,nickname,group-suffix,message - Tags of this channel\n"
+ "need-focus: false - Player can use the alias or need to use '/ch g' to use this channel?\n"
+ "canLock: true - Change if the player can use /<channel> to lock on channel."
+ "receivers-message: true - Send chat messages like if 'no players near to receive the message'?\n"
+ "cost: 0.0 - Cost to player use this channel.\n"
+ "use-this-builder: false - Use this tag builder or use the 'config.yml' tag-builder?\n"
+ "channelAlias - Use this channel as a command alias.\n"
+ " enable: true - Enable this execute a command alias?\n"
+ " sendAs: player - Send the command alias as 'player' or 'console'?\n"
+ " cmd: '' - Command to send on every message send by this channel.\n"
+ "available-worlds - Worlds and only this world where this chat can be used and messages sent/received.\n"
+ "discord:\n"
+ " mode: NONE - The options are NONE, SEND, LISTEN, BOTH. If enabled and token code set and the channel ID matches with one discord channel, will react according the choosen mode.\n"
+ " hover: &3Discord Channel: &a{dd-channel}\\n&3Role Name: {dd-rolecolor}{dd-rolename}\n"
+ " format-to-mc: {ch-color}[{ch-alias}]&b{dd-rolecolor}[{dd-rolename}]{sender}&r: \n"
+ " format-to-dd: :thought_balloon: **{sender}**: {message} \n"
+ " allow-server-cmds: false - Use this channel to send commands from discord > minecraft.\n"
+ " channelID: '' - The IDs of your Discord Channels. Enable debug on your discord to get the channel ID.\n"
+ " Note: You can add more than one discord id, just separate by \",\" like: 13246579865498,3216587898754\n");
ch.getProperties().forEach((key, value) -> chFile.set((String) key, value));
chFile.save(defch);
if (UChat.get().getChannel(ch.getName()) != null) {
ch.setMembers(UChat.get().getChannel(ch.getName()).getMembers());
UChat.get().getChannels().remove(Arrays.asList(ch.getName().toLowerCase(), ch.getAlias().toLowerCase()));
}
UChat.get().getChannels().put(Arrays.asList(ch.getName().toLowerCase(), ch.getAlias().toLowerCase()), ch);
}
public List<String> getTagList() {
List<String> tags = new ArrayList<>();
for (String key : plugin.getConfig().getKeys(true)) {
if (key.startsWith("tags.") && key.split("\\.").length == 2) {
tags.add(key.replace("tags.", ""));
}
}
tags.addAll(getStringList("general.custom-tags"));
return tags;
}
public String[] getDefBuilder() {
return getString("general.default-tag-builder").replace(" ", "").split(",");
}
public List<String> getBroadcastAliases() {
return Arrays.asList(plugin.getConfig().getString("broadcast.aliases", "").replace(" ", "").split(","));
}
public List<String> getTellAliases() {
return Arrays.asList(plugin.getConfig().getString("tell.cmd-aliases", "").replace(" ", "").split(","));
}
public List<String> getMsgAliases() {
return Arrays.asList(plugin.getConfig().getString("general.umsg-cmd-aliases", "").replace(" ", "").split(","));
}
public boolean getBoolean(String key) {
return plugin.getConfig().getBoolean(key, false);
}
public void setConfig(String key, Object value) {
plugin.getConfig().set(key, value);
}
public String getString(String key) {
return plugin.getConfig().getString(key, "");
}
public int getInt(String key, int def) {
return plugin.getConfig().getInt(key, def);
}
public List<String> getStringList(String key) {
return plugin.getConfig().getStringList(key);
}
public void save() {
try {
comConfig.saveConfig();
Prots.save(new File(UChat.get().getDataFolder(), "protections.yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
//protection methods
public ConfigurationSection getProtReplecements() {
return Prots.getConfigurationSection("chat-protection.censor.replace-words");
}
public void delFilter(String word) {
Prots.set("chat-protection.censor.replace-words." + word, null);
save();
}
public void addFilter(String word) {
String[] pair = word.split(":");
Prots.set("chat-protection.censor.replace-words." + pair[0], pair[1]);
save();
}
public int getProtInt(String key) {
return Prots.getInt(key);
}
public boolean getProtBool(String key) {
return Prots.getBoolean(key);
}
public List<String> getProtStringList(String key) {
return Prots.getStringList(key);
}
public String getProtString(String key) {
return Prots.getString(key);
}
public String getProtMsg(String key) {
return UChatColor.translateAlternateColorCodes(Prots.getString(key));
}
public String getColorStr(String key) {
return UChatColor.translateAlternateColorCodes(plugin.getConfig().getString(key));
}
public boolean hasBlackListed(ItemStack itemStack) {
return plugin.getConfig().getStringList("general.item-hand.blacklist").stream().anyMatch(i -> i.equalsIgnoreCase(itemStack.getType().name()));
}
}
|
gpl-3.0
|
Asurvovor/adsStudy
|
sinaads/src/sinaads/main.js
|
2065
|
/*!
* sinaads
* 新浪统一商业广告脚本
* 负责使用pdps(新浪广告资源管理码)向广告引擎请求数据并处理广告渲染
* @author acelan <xiaobin8[at]staff.sina.com.cn>
* @version 1.8.0
* @date 2013-08-08
*/
/**
* @useage
* window.sinaadsPreloadData = [pdps1, pdps2, pdps3, ..., pdpsn]; 批量加载的代码
* (window.sinaads = window.sinaads || []).push({}); 投放一个位置
* (window.sinaads = window.sinaads || []).push({
* element : HTMLDOMElement,
* params : {
* sinaads_ad_width : xx,
* sinaads_ad_height : xxx,
* sinaads_ad_pdps : xxxx,
* ...
* }
* });
*
*
* @info
* _sinaadsTargeting : 保存本页中的定向信息
* _SINAADS_CONF_SAX_REQUEST_TIMEOUT = 10 //设置sax请求超时时间,单位秒
* _SINAADS_CONF_PAGE_MEDIA_ORDER = [] //广告展现顺序配置,PDPS列表
* _SINAADS_CONF_PRELOAD = [] //预加载的广告pdps列表
*/
window._sinaadsIsInited = window._sinaadsIsInited || (function (window, core, undefined) {
"use strict";
core.debug('sinaads:Init sinaads!');
//妈蛋,smash的正则不支持前面空格然后才import,必须直接第一个字符就是import
//
import "config";
import "controller";
import "model";
import "view";
import "postmessage";
import "view/bp";
import "view/couplet";
import "view/embed";
import "view/float";
import "view/follow";
import "view/fullscreen";
import "view/stream";
import "view/textlink";
import "view/tip";
import "view/turning";
import "view/videoWindow";
import "view/bg";
import "view/pop";
import "view/skyscraper.js";
import "view/leftsuspend.js";
import "view/shopWindow.js";
import "view/shop.js";
import "view/bottomstream.js";
import "view/magicmap";
import "view/followbutton";
import "init";
import "exports";
//增加统计正文页的包含图片正文监测,图森合作项目
//import "plugin/articleImgCount.js";
return true; //初始化完成
})(window, window.sinaadToolkit);
|
gpl-3.0
|
xavierh/minecolonies
|
src/main/java/com/minecolonies/coremod/client/gui/WindowTownHallNameEntry.java
|
1780
|
package com.minecolonies.coremod.client.gui;
import com.minecolonies.blockout.controls.Button;
import com.minecolonies.blockout.controls.TextField;
import com.minecolonies.blockout.views.Window;
import com.minecolonies.coremod.colony.ColonyView;
import com.minecolonies.coremod.lib.Constants;
import org.jetbrains.annotations.NotNull;
/**
* Window for a town hall name entry.
*/
public class WindowTownHallNameEntry extends Window implements Button.Handler
{
private static final String BUTTON_DONE = "done";
private static final String BUTTON_CANCEL = "cancel";
private static final String INPUT_NAME = "name";
private static final String TOWNHALL_NAME_RESOURCE_SUFFIX = ":gui/windowtownhallnameentry.xml";
private final ColonyView colony;
/**
* Constructor for a town hall rename entry window.
*
* @param c {@link ColonyView}
*/
public WindowTownHallNameEntry(final ColonyView c)
{
super(Constants.MOD_ID + TOWNHALL_NAME_RESOURCE_SUFFIX);
this.colony = c;
}
@Override
public void onOpened()
{
findPaneOfTypeByID(INPUT_NAME, TextField.class).setText(colony.getName());
}
@Override
public void onButtonClicked(@NotNull final Button button)
{
if (button.getID().equals(BUTTON_DONE))
{
final String name = findPaneOfTypeByID(INPUT_NAME, TextField.class).getText();
if (!name.isEmpty())
{
colony.setName(name);
}
}
else if (!button.getID().equals(BUTTON_CANCEL))
{
return;
}
if (colony.getTownHall() != null)
{
colony.getTownHall().openGui();
}
}
}
|
gpl-3.0
|
scrmtrey91/EARS
|
src/org/um/feri/ears/algorithms/moo/spea2/DistanceNode.java
|
1522
|
// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
package org.um.feri.ears.algorithms.moo.spea2;
public class DistanceNode {
/**
* Indicates the position of a <code>Solution</code> in a
* <code>SolutionSet</code>.
*/
private int reference_;
/**
* Indicates the distance to the <code>Solution</code> represented by
* <code>reference_</code>.
*/
private double distance_;
/**
* Constructor.
*
* @param distance The distance to a <code>Solution</code>.
* @param reference The position of the <code>Solution</code>.
*/
public DistanceNode(double distance, int reference) {
distance_ = distance;
reference_ = reference;
}
/**
* Sets the distance to a <code>Solution</code>
*
* @param distance
* The distance
*/
public void setDistance(double distance) {
distance_ = distance;
}
/**
* Sets the reference to a <code>Solution</code>
*
* @param reference The reference
*/
public void setReferece(int reference) {
reference_ = reference;
}
/**
* Gets the distance
*
* @return the distance
*/
public double getDistance() {
return distance_;
}
/**
* Gets the reference
*
* @return the reference
*/
public int getReference() {
return reference_;
}
}
|
gpl-3.0
|
SanderMertens/opensplice
|
demos/iShapes/Shape.hpp
|
959
|
#ifndef _SHAPE_HPP
#define _SHAPE_HPP
/** @file */
/**
* @addtogroup demos_iShapes
*/
/** @{*/
#include <QtCore/QRect>
#include <QtGui/QPen>
#include <QtGui/QBrush>
#include <dds/core/refmacros.hpp>
namespace demo { namespace ishapes {
class Shape
{
public:
Shape(const QRect& bounds,
const QPen& pen,
const QBrush& brush,
bool targeted = false);
virtual ~Shape();
public:
virtual void update() = 0;
virtual void paint(QPainter& painter) = 0;
public:
virtual void setPen(const QPen& pen);
virtual void setBrush(const QBrush& brush);
virtual void setBounds(const QRect& bounds);
virtual void set_targeted(bool b);
public:
typedef ::dds::core::smart_ptr_traits<Shape>::ref_type ref_type;
private:
Shape(const Shape&);
Shape& operator=(const Shape&);
protected:
QRect bounds_;
QPen pen_;
QBrush brush_;
bool targeted_;
};
}
}
/** @}*/
#endif /* _SHAPE_HPP */
|
gpl-3.0
|
mooniak/animager
|
src/genImages.py
|
1174
|
### generate temporary images using GIT commits
### dependencies : imagemagick
import os
def genTempImage( gitImage, options,
outputName, outputExt, outputDir ):
os.system( 'convert ' + gitImage
+ ' ' + options
+ ' ' + outputDir
+ outputName
+ outputExt )
def gitCommitArray( image ):
os.system( 'git log --pretty=%h '+ image + ' > log' )
commits = open('log').read().splitlines()
return commits
def gitCheckoutOld( commitHash ):
os.system( 'git checkout ' + commitHash )
def gitGenTempImages( image, outputDir ):
os.system( 'mkdir -p ' + outputDir )
commits = gitCommitArray( image )
commits.reverse()
count = 1
for commitHash in commits:
gitCheckoutOld( commitHash )
genTempImage( gitImage = image,
options = '',
outputDir = outputDir,
outputName = str('%05d'%(count)),
outputExt = '.png' )
count += 1
print ("\nRolling changes back to master branch...\n")
os.system( 'git checkout master' )
|
gpl-3.0
|
SGKhmCs/wBoard
|
src/main/java/ua/sgkhmja/wboard/config/ElasticsearchConfiguration.java
|
1640
|
package ua.sgkhmja.wboard.config;
import java.io.IOException;
import org.elasticsearch.client.Client;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.EntityMapper;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class ElasticsearchConfiguration {
@Bean
public ElasticsearchTemplate elasticsearchTemplate(Client client, Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
return new ElasticsearchTemplate(client, new CustomEntityMapper(jackson2ObjectMapperBuilder.createXmlMapper(false).build()));
}
public class CustomEntityMapper implements EntityMapper {
private ObjectMapper objectMapper;
public CustomEntityMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
}
@Override
public String mapToString(Object object) throws IOException {
return objectMapper.writeValueAsString(object);
}
@Override
public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
return objectMapper.readValue(source, clazz);
}
}
}
|
gpl-3.0
|
tkasp/osmose-backend
|
modules/OsmoseLog.py
|
5282
|
#-*- coding: utf-8 -*-
###########################################################################
## ##
## Copyrights Etienne Chové <chove@crans.org> 2009 ##
## ##
## This program is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## (at your option) any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <http://www.gnu.org/licenses/>. ##
## ##
###########################################################################
import time
import sys
import subprocess
class logger:
def __init__(self, out = sys.stdout, showall = True):
self._out = out
self._showall = showall
self.log_av_r = u'\033[0;31m' # red
self.log_av_b = u'\033[0;34m' # blue
self.log_av_green = u'\033[0;32m' # green
self.log_ap = u'\033[0m' # reset color
def _log(self, txt, level):
pre = u""
pre += time.strftime("%Y-%m-%d %H:%M:%S ")
pre += u" "*level
suf = u""
print(u'{0}{1}{2}'.format(pre, txt, suf), file=self._out)
self._out.flush()
def log(self, txt):
self._log(txt, 0)
def _err(self, txt, level):
self._log(u'{0}{1}{2}{3}'.format(self.log_av_r, u'error: ', txt, self.log_ap), level)
def err(self, txt):
self._err(txt, 0)
def _warn(self, txt, level):
self._log(u'{0}{1}{2}{3}'.format(self.log_av_r, u'warning: ', txt, self.log_ap), level)
def warn(self, txt):
self._warn(txt, 0)
def sub(self):
return sublog(self, 1)
def execute_err(self, cmd, valid_return_code=(0,)):
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
cerr = proc.stderr.readline().decode('utf-8').strip()
if cerr == '' and proc.poll() is not None:
break
if cerr == '':
continue
if self._showall:
self._out.write(u'{0} {1}\n'.format(time.strftime("%Y-%m-%d %H:%M:%S"), cerr))
self._out.flush()
proc.wait()
if proc.returncode not in valid_return_code:
raise RuntimeError("'%s' exited with status %s" % (' '.join(cmd), repr(proc.returncode)))
return proc.returncode
def execute_out(self, cmd, cwd=None, valid_return_code=(0,)):
proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
cerr = proc.stdout.readline().decode('utf-8').strip()
if cerr == '' and proc.poll() is not None:
break
if cerr == '':
continue
if self._showall:
self._out.write(u'{0} {1}\n'.format(time.strftime("%Y-%m-%d %H:%M:%S "), cerr))
self._out.flush()
proc.wait()
if proc.returncode not in valid_return_code:
raise RuntimeError("'%s' exited with status %s :\n%s" % (' '.join(cmd), repr(proc.returncode), proc.stderr.read()))
return proc.returncode
def send_alert_email(self, email_to, err_msg):
if not email_to:
return
import smtplib
import socket
from email.mime.text import MIMEText
hostname = socket.getfqdn()
email_from = "osmose@%s" % hostname
msg = MIMEText(err_msg)
msg['Subject'] = '%s - osmose failure - %s' % (hostname, err_msg)
msg['From'] = email_from
msg['To'] = ", ".join(email_to)
s = smtplib.SMTP('127.0.0.1')
s.sendmail(email_from, email_to, msg.as_string())
s.quit()
class sublog:
def __init__(self, root, level):
self._root = root
self._level = level
def log(self, txt):
self._root._log(txt, self._level)
def err(self, txt):
self._root._err(txt, self._level)
def warn(self, txt):
self._root._warn(txt, self._level)
def sub(self):
return sublog(self._root, self._level + 1)
if __name__ == "__main__":
a = logger()
a.log("coucou")
a.sub().log("test")
a.sub().sub().log("test")
a.sub().log("test")
a.log(a.log_av_r + "red" + a.log_ap)
a.log(a.log_av_green + "green" + a.log_ap)
a.log(a.log_av_b + "blue" + a.log_ap)
a.err("test 1")
a.sub().err("test 2")
a.sub().sub().err("test 3")
|
gpl-3.0
|
zxul767/LomasNaucalpan
|
frontend/create-user/js/create-user.js
|
102
|
$(document).ready(function() {
$('#menu-create-user').children().css('background', 'beige');
});
|
gpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.