code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* Global variables */ var _languagesHashOld = new Array(); var _languagesHash = new Array(); var _languagesRegexHash = new Array(); /* Initialize the languages arrays */ /* Order alphabetically by _languagesHash key */ /* Based in ISO 639-3 codes */ /* source: http://www-01.sil.org/iso639-3/iso-639-3.tab */ /* alt source: https://github.com/wikimedia/mediawiki/blob/7458dc32d99e6dd569b1629762443d074b6a3c52/languages/Names.php */ _languagesHash = { 'aar': 'Afaraf', 'arz': 'اللغة المصرية العامية', 'abk': 'аҧсуа бызшәа, аҧсшәа', 'ace': 'بهسا اچيه', 'aeb': 'زَوُن', 'afr': 'Afrikaans', 'aka': 'Akan', 'amh': 'አማርኛ', 'ang': 'Old English', 'ara': 'العربية', 'arg': 'Aragonés', 'asm': 'অসমীয়া', 'ava': 'авар мацӀ, магӀарул мацӀ', 'ave': 'avesta', 'aym': 'aymar aru', 'ary': 'الدارجة', 'arc': 'Imperial Aramaic', 'ast': 'Asturianu', 'aze': 'azərbaycanca', 'azb': 'South Azerbaijani', 'bak': 'Bašqort', 'bar': 'Boarisch', 'bam': 'Bamanankan', 'bpy': 'বিষ্ণুপ্রিয়া মণিপুরী', 'bcl': 'Bikol Sentral', 'bel': 'Беларуская', 'ben': 'বাংলা', 'bho': 'भोजपुरी', 'bis': 'Bislama', 'bod': 'བོད་ཡིག', 'bos': 'bosanski jezik', 'bre': 'Brezhoneg', 'bul': 'Български', 'bus': 'Bisã', 'bxr': 'буряад хэлэн', 'bcc': 'balojî Balójí', 'bel-tasrask': 'тарашкевіца, клясычны правапіс', 'bjn': 'Bahasa Banjar', 'cat': 'Català', 'cdo': '平話', 'ces': 'Česky', 'ceb': 'Sinugboanon', 'cha': 'Chamoru', 'che': 'нохчийн мотт', 'chy': 'Tsėhésenėstsestȯtse', 'chu': 'ѩзыкъ словѣньскъ', 'chv': 'Чӑвашла', 'cbk-zam': 'Chavacano', 'cor': 'Kernewek', 'cos': 'corsu, lingua corsa', 'cre': 'ᓀᐦᐃᔭᐍᐏᐣ', 'cym': 'Cymraeg', 'chr': 'ᏣᎳᎩ ᎦᏬᏂᎯᏍᏗ', 'crh': 'Къырымтатарджа', 'ckb': 'کوردیی ناوەندی', 'csb': 'Kaszëbsczi jãzëk', 'dan': 'Dansk', 'dsb': 'Dolnoserbski', 'deu': 'Deutsch', 'div': 'ދިވެހި', 'dzo': ' རྫོང་ཁ', 'ell': 'Ελληνικά', 'eng': 'English', 'epo': 'Esperanto', 'est': 'Eesti', 'eus': 'euskara', 'ewe': 'Eʋegbe', 'ext': 'estremeñu', 'eml': 'emiliân-rumagnōl', 'ebn': 'বাংলা', 'fao': 'Føroyskt', 'fas': 'فارسی', 'fij': 'vosa Vakaviti', 'fin': 'Suomi', 'fra': 'Français', 'fry': 'Frysk', 'ful': 'Fulfulde', 'fur': 'Furlan', 'frp': 'Provençau', 'frr': 'Nordfriisk', 'gag': 'Gagauz dili', 'gan': '贛語', 'gla': 'Gàidhlig', 'gle': 'Gaeilge', 'glg': 'Galego', 'glv': 'Gaelg', 'glk': 'گیلکی', 'got': 'Gothic', 'grn': 'Avañe\'ẽ', 'guj': 'ગુજરાતી', 'gsw': 'Schwyzerdütsch', 'hak': '客家語/Hak-kâ-ngî', 'haw': 'ʻŌlelo Hawaiʻi', 'hat': 'Kreyol ayisyen', 'hau': 'Hausa', 'heb': 'עברית', 'her': 'Otjiherero', 'hin': 'हिन्दी', 'hmo': 'Hiri Motu', 'hrv': 'Олык Марий', 'hun': 'Magyar', 'hye': 'Հայերեն', 'hif-latn': 'Fiji Baat', 'hif': 'फिजी बात', 'hrx': 'Riograndenser Hunsrückisch', 'hsb': 'Hornjoserbsce', 'ibo': 'Asụsụ Igbo', 'ido': 'Ido', 'iii': 'ꆈꌠ꒿ Nuosuhxop', 'iku': 'ᐃᓄᒃᑎᑐᑦ', 'ile': 'Interlingue', 'ina': 'Interlingua', 'ind': 'Bahasa Indonesia', 'ipk': 'Iñupiaq', 'isl': 'Íslenska', 'ita': 'Italiano', 'ilo': 'Ilokano', 'jav': 'Basa Jawa', 'jpn': '日本語', 'jbo': 'la .lojban.', 'kaa': 'Қарақалпақ тили', 'kal': 'Kalaallisut', 'kan': 'ಕನ್ನಡ', 'kas': 'कश्मीरी', 'kat': 'ქართული', 'kau': 'Kanuri', 'kaz': 'Қазақша', 'khm': 'ភាសាខ្មែរ', 'kik': 'Gĩkũyũ', 'kin': 'Ikinyarwanda', 'kir': 'قىرعىز تىلى', 'kom': 'коми кыв', 'kon': 'Kikongo', 'kor': '한국어', 'kor-kp': '조선어', 'kua': 'Kuanyama', 'kur': 'kurdî', 'ksh': 'Ripoarisch', 'kab': 'Taqbaylit', 'kbd': 'Адыгэбзэ', 'koi': 'Перем коми кыв', 'krc': 'Къарачай-Малкъар тил', 'lad': 'Judeo-Español', 'lbe': 'лакку маз', 'lez': 'Лезги чӏал Lezgi č’al', 'lij': 'Lìgure, Zenéize', 'lki': 'لوری', 'lmo': 'Lumbaart', 'ltg': 'latgalīšu volūda', 'lzh': '古文', 'mai': 'मैथिली, মৈথিলী', 'mdf': 'Мокшень кяль / mokšenj kälj', 'mhr': 'Meadow Mari', 'min': 'باسو مينڠكاباو', 'mrj': 'Мары йӹлмӹ', 'mwl': 'Mirandés', 'myv': 'Morafa', 'mzn': 'مازندرانی', 'nah': 'Asteca', 'nan': '閩南語 / 闽南语', 'nap': 'Napulitano', 'nds': 'Plattdüütsch', 'nds-nl': 'Nederlaands Leegsaksies', 'nov': 'Novial', 'nrm': 'Narom', 'nso': 'Pedi', 'pag': 'Pangasinense', 'pam': 'Amánung Sísuan', 'pap': 'Papiamentu', 'pfl': 'Pfälzisch', 'pih': 'Pitkern-Norfolk', 'lao': 'ພາສາລາວ', 'lat': 'Lingua Latīna', 'lav': 'Latviešu', 'lim': 'Limburgs', 'lin': 'Lingála', 'lit': 'Lietuvių', 'ltz': 'Lëtzebuergesch', 'lub': 'Tshiluba', 'lug': 'Luganda', 'mah': 'Kajin M̧ajeļ', 'mal': 'മലയാളം', 'mar': 'मराठी', 'map-bms': 'Basa Banyumasan', 'mkd': 'Македонски', 'mlg': 'Malagasy', 'mlt': 'Malti', 'mon': 'Монгол хэл', 'mri': 'Te reo Māori', 'msa': 'Bahasa Melayu', 'mul': 'multilingual', 'mya': 'မြန်မာဘာသာ', 'nau': 'Ekakairũ Naoero', 'nav': 'Diné bizaad', 'nbl': 'isiNdebele', 'nde': 'isiNdebele', 'ndo': 'Owambo', 'nep': 'नेपाली', 'nld': 'Nederlands', 'nno': 'Norsk (nynorsk)', 'nob': 'Norsk (bokmål)', 'nor': 'Norsk (bokmål)', 'nya': 'ChiCheŵa', 'new': 'नेपाल भाषा', 'oci': 'Occitan', 'oji': 'ᐊᓂᔑᓈᐯᒧᐎᓐ', 'ori': 'ଓଡ଼ିଆ', 'orm': 'Afaan Oromoo', 'oss': 'ирон æвзаг', 'pan': 'ਪੰਜਾਬੀ', 'pcd': 'Picard', 'pli': 'पाऴि', 'pol': 'Język polski', 'por': 'Português', 'por-pt': 'Português do Brasil', 'pus': 'پښتو', 'pdc': 'Pennsilfaanisch Deitsch', 'pms': 'Piemontèis', 'que': 'Runa Simi', 'roh': 'Rumantsch', 'ron': 'Română', 'run': 'Ikirundi', 'rus': 'Русский', 'rue': 'Русиньскый', 'pnb': 'شاہ مکھی پنجابی', 'pnt': 'ποντιακά', 'rmy': 'Vlax Romani', 'roa-tara': 'Tarandíne', 'rup': 'armãneashce, armãneashti, rrãmãneshti', 'sah': 'Саха тыла', 'scn': 'Sicilianu', 'sco': '(Braid) Scots, Lallans', 'sgs': 'Žemaičių tarmė', 'srn': 'Sranan Tongo', 'stq': 'Seeltersk', 'szl': 'ślōnskŏ gŏdka', 'tet': 'Lia-Tetun', 'tpi': 'Tok Pisin', 'tum': 'chiTumbuka', 'tyv': 'тыва дыл tyva dyl', 'udm': 'удмурт кыл udmurt kyl', 'vep': 'vepsän kel’', 'vls': 'West-Vlaams', 'vro': 'võro kiil', 'wuu': '吳語/吴语', 'xal': 'ᡆᡕᡅᠷᠠᡑ ᡘᡄᠯᡄᠨ', 'xmf': 'მარგალური ნინა', 'yue': '廣州話 / 广州话', 'zea': 'Zeêuws', 'zh-min-nan': '閩南語 / 闽南语', 'sag': 'yângâ tî sängö', 'san': 'संस्कृतम्', 'sin': 'සිංහල', 'skr': 'सराइकी', 'slk': 'Slovenčina', 'slv': 'Slovenščina', 'sme': 'Davvisámegiella', 'smo': 'gagana fa\'a Samoa', 'sna': 'chiShona', 'snd': 'सिन्धी', 'som': 'Soomaaliga', 'sot': 'Sesotho', 'spa': 'Español', 'sqi': 'Mirësevini', 'tha': 'ภาษาไทย', 'srd': 'sardu', 'srp': 'Српски', 'srp-ec': 'Српски (ћирилица)', 'srp-el': 'Srpski (latinica)', 'ssw': 'SiSwati', 'sun': 'Basa Sunda', 'swa': 'Kiswahili', 'swe': 'Svenska', 'ses': 'Koyraboro Senni', 'sh': 'Srpskohrvatski / Српскохрватски', 'tah': 'Reo Tahiti', 'tam': 'தமிழ்', 'tat': 'татар теле', 'tel': 'తెలుగు', 'tgk': 'тоҷикӣ', 'tgl': 'Wikang Tagalog', 'tir': 'ትግርኛ', 'ton': 'faka Tonga', 'tsn': 'Setswana', 'tso': 'Xitsonga', 'tuk': 'Türkmen dili', 'tur': 'Türkçe', 'twi': 'Twi', 'tcy': 'ತುಳು', 'tly': 'толышә зывон', 'tt-cyrl': 'Татарча', 'uig': 'ئۇيغۇرچە', 'ug-arab': 'ئۇيغۇرچە', 'ukr': 'Українська', 'urd': 'اردو', 'uzb': 'Oʻzbekcha', 'ven': 'Tshivenḓa', 'vec': 'Vèneto', 'vie': 'Tiếng Việt', 'vol': 'Volapük', 'wln': 'walon', 'wol': 'Wolof', 'xho': 'isiXhosa', 'yid': 'ייִדיש', 'yor': 'Yorùbá', 'zha': 'Saɯ cueŋƅ', 'zho': '中文', 'zho-hans': '中文(简体)', 'zho-hant': '中文(繁體)', 'zho-hk': '中文(香港)', 'zul': 'isiZulu', 'zza': 'Zāzākī' }; /* Based in ISO 639-1 and 639-2 codes */ _languagesHashOld = { 'ay': _languagesHash.aym, 'aa': _languagesHash.aar, 'ab': _languagesHash.abk, 'af': _languagesHash.afr, 'ak': _languagesHash.aka, 'am': _languagesHash.amh, 'an': _languagesHash.arg, 'ar': _languagesHash.ara, 'as': _languagesHash.asm, 'az': _languagesHash.aze, 'ba': _languagesHash.bak, 'bh': _languagesHash.bho, 'bm': _languagesHash.bam, 'be': _languagesHash.bel, 'bi': _languagesHash.bis, 'bo': _languagesHash.bod, 'bn': _languagesHash.ben, 'br': _languagesHash.bre, 'bs': _languagesHash.bos, 'bg': _languagesHash.bul, 'be-tarask': _languagesHash['bel-tasrask'], 'ca': _languagesHash.cat, 'ce': _languagesHash.che, 'co': _languagesHash.cos, 'cs': _languagesHash.ces, 'cv': _languagesHash.chv, 'cy': _languagesHash.cym, 'cu': _languagesHash.chu, 'cr': _languagesHash.cre, 'crh-latn': _languagesHash.crh, 'ch': _languagesHash.cha, 'da': _languagesHash.dan, 'de': _languagesHash.deu, 'dv': _languagesHash.div, 'dz': _languagesHash.dzo, 'ee': _languagesHash.ewe, 'el': _languagesHash.ell, 'en': _languagesHash.eng, 'eo': _languagesHash.epo, 'eu': _languagesHash.eus, 'et': _languagesHash.est, 'fo': _languagesHash.fao, 'fa': _languagesHash.fas, 'fi': _languagesHash.fin, 'fy': _languagesHash.fry, 'fj': _languagesHash.fij, 'fr': _languagesHash.fra, 'ff': _languagesHash.ful, 'gl': _languagesHash.glg, 'gd': _languagesHash.gla, 'ga': _languagesHash.gle, 'gn': _languagesHash.grn, 'gu': _languagesHash.guj, 'gv': _languagesHash.glv, 'ht': _languagesHash.hat, 'ha': _languagesHash.hau, 'he': _languagesHash.heb, 'hi': _languagesHash.hin, 'hr': _languagesHash.hrv, 'hu': _languagesHash.hun, 'hy': _languagesHash.hye, 'ie': _languagesHash.ile, 'ig': _languagesHash.ibo, 'ia': _languagesHash.ina, 'id': _languagesHash.ind, 'it': _languagesHash.ita, 'ik': _languagesHash.ipk, 'io': _languagesHash.ido, 'iu': _languagesHash.iku, 'is': _languagesHash.isl, 'jv': _languagesHash.jav, 'ja': _languagesHash.jpn, 'kn': _languagesHash.kan, 'ki': _languagesHash.kik, 'kv': _languagesHash.kom, 'kw': _languagesHash.cor, 'lg': _languagesHash.lug, 'ln': _languagesHash.lin, 'lo': _languagesHash.lao, 'mi': _languagesHash.mri, 'na': _languagesHash.nau, 'nv': _languagesHash.nav, 'ny': _languagesHash.nya, 'om': _languagesHash.orm, 'os': _languagesHash.oss, 'pa': _languagesHash.pan, 'pi': _languagesHash.pli, 'ka': _languagesHash.kat, 'kk': _languagesHash.kaz, 'km': _languagesHash.khm, 'ky': _languagesHash.kir, 'ko-kp': _languagesHash['kor-kp'], 'ku': _languagesHash.kur, 'kg': _languagesHash.kon, 'kl': _languagesHash.kal, 'ks': _languagesHash.kas, 'la': _languagesHash.lat, 'lv': _languagesHash.lav, 'li': _languagesHash.lim, 'lt': _languagesHash.lit, 'lb': _languagesHash.ltz, 'ml': _languagesHash.mal, 'mr': _languagesHash.mar, 'mk': _languagesHash.mkd, 'mg': _languagesHash.mlg, 'mt': _languagesHash.mlt, 'mn': _languagesHash.mon, 'ms': _languagesHash.msa, 'my': _languagesHash.mya, 'ne': _languagesHash.nep, 'nl': _languagesHash.nld, 'nn': _languagesHash.nno, 'nb': _languagesHash.nob, 'no': _languagesHash.nor, 'oc': _languagesHash.oci, 'or': _languagesHash.ori, 'pl': _languagesHash.pol, 'pt': _languagesHash.por, 'pt-br': _languagesHash['por-pt'], 'ps': _languagesHash.pus, 'qu': _languagesHash.que, 'rm': _languagesHash.roh, 'ro': _languagesHash.ron, 'ru': _languagesHash.rus, 'rn': _languagesHash.run, 'rw': _languagesHash.kin, 'sc': _languagesHash.srd, 'sd': _languagesHash.snd, 'se': _languagesHash.sme, 'sg': _languagesHash.sag, 'sm': _languagesHash.smo, 'sn': _languagesHash.sna, 'so': _languagesHash.som, 'ss': _languagesHash.ssw, 'st': _languagesHash.sot, 'tg': _languagesHash.tgk, 'ti': _languagesHash.tir, 'tn': _languagesHash.tsn, 'to': _languagesHash.ton, 'ts': _languagesHash.tso, 'tt': _languagesHash.tat, 'tw': _languagesHash.twi, 'ty': _languagesHash.tah, 'ug': _languagesHash.uig, 've': _languagesHash.ven, 'wa': _languagesHash.wln, 'wo': _languagesHash.wol, 'xh': _languagesHash.xho, 'za': _languagesHash.zha, 'zu': _languagesHash.zul, 'sa': _languagesHash.san, 'si': _languagesHash.sin, 'sk': _languagesHash.slk, 'sl': _languagesHash.slv, 'es': _languagesHash.spa, 'sq': _languagesHash.sqi, 'sr': _languagesHash.srp, 'sr-ec': _languagesHash['srp-ec'], 'sr-el': _languagesHash['srp-el'], 'su': _languagesHash.sun, 'sw': _languagesHash.swa, 'sv': _languagesHash.swe, 'ta': _languagesHash.tam, 'te': _languagesHash.tel, 'tl': _languagesHash.tgl, 'th': _languagesHash.tha, 'tk': _languagesHash.tuk, 'tr': _languagesHash.tur, 'uk': _languagesHash.ukr, 'ur': _languagesHash.urd, 'uz': _languagesHash.uzb, 'vi': _languagesHash.vie, 'yo': _languagesHash.wol, 'yi': _languagesHash.yid, 'zh': _languagesHash.zho, 'zh-hans': _languagesHash['zho-hans'], 'zh-hant': _languagesHash['zho-hant'], 'zh-hk': _languagesHash['zho-hk'], 'diq': _languagesHash.zza }; function getLanguageNameFromISO(code) { var language = _languagesHash[code] || _languagesHashOld[code] || ''; if (!language && code) { /* This js code might be used js runtime engine where * the dump() method is not available */ try { dump('"' + code + '" is not available in languages.js.\n'); } catch (error) {} } return language; } function getLanguageNameFromISOCodes(codes) { var result = ""; var codeArray = codes.split(','); for (var i in codeArray) { result += getLanguageNameFromISO(codeArray[i]); if (i < codeArray.length - 1) { result += ', '; } } return result; } /* Be careful, this function returns false, also if undefined - that * means nothing because the table _languagesHashOld is not complete */ function isOldLanguageCode(code) { return _languagesHashOld[iso] ? true : false; } function buildLanguagesRegexHash() { var code; for (code in _languagesHash) { _languagesRegexHash[_languagesHash[code]] = code; } for (code in _languagesHashOld) { var regex = _languagesRegexHash[_languagesHashOld[code]]; _languagesRegexHash[_languagesHashOld[code]] = '^(' + (regex ? regex + '|' : '') + code + ')$'; } } function getLanguageRegex(language) { return _languagesRegexHash[language] || ''; }
kiwix/kiwix_mirror
kiwix/chrome/content/main/js/languages.js
JavaScript
gpl-3.0
16,530
package tk.blackwolf12333.grieflog.compatibility.v1_6_R3; import java.util.HashSet; import org.bukkit.Chunk; import org.bukkit.entity.Player; import tk.blackwolf12333.grieflog.compatibility.ChangesSenderInterface; import tk.blackwolf12333.grieflog.rollback.SendChangesTask; public class ChangesSender implements ChangesSenderInterface { @SuppressWarnings("unchecked") @Override public void sendChanges(SendChangesTask task, HashSet<Chunk> chunks) { HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair> pairs = new HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair>(); for (Chunk c : chunks) { pairs.add(new net.minecraft.server.v1_6_R3.ChunkCoordIntPair(c.getX(), c.getZ())); } for (Player p : task.getPlayers()) { HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair> queued = new HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair>(); if (p != null) { net.minecraft.server.v1_6_R3.EntityPlayer ep = ((org.bukkit.craftbukkit.v1_6_R3.entity.CraftPlayer) p).getHandle(); for (Object o : ep.chunkCoordIntPairQueue) { queued.add((net.minecraft.server.v1_6_R3.ChunkCoordIntPair) o); } for (net.minecraft.server.v1_6_R3.ChunkCoordIntPair pair : pairs) { if (!queued.contains(pair)) { ep.chunkCoordIntPairQueue.add(pair); } } } } } }
doglover129/GriefLog
src/tk/blackwolf12333/grieflog/compatibility/v1_6_R3/ChangesSender.java
Java
gpl-3.0
1,314
/* * Copyright (C) 2010-2021 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.api.util; /** */ public interface ProgressWatcher { boolean okToContinue(final int progress); }
ckramp/structr
structr-db-driver-api/src/main/java/org/structr/api/util/ProgressWatcher.java
Java
gpl-3.0
857
import numpy as np import os from galry import log_debug, log_info, log_warn, get_color from fontmaps import load_font from visual import Visual __all__ = ['TextVisual'] VS = """ gl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x; gl_Position.y -= index * spacing.y / window_size.y; gl_Position.xy = gl_Position.xy + posoffset / window_size; gl_PointSize = point_size; flat_text_map = text_map; """ def FS(background_transparent=True): if background_transparent: background_transparent_shader = "letter_alpha" else: background_transparent_shader = "1." fs = """ // relative coordinates of the pixel within the sprite (in [0,1]) float x = gl_PointCoord.x; float y = gl_PointCoord.y; // size of the corresponding character float w = flat_text_map.z; float h = flat_text_map.w; // display the character at the left of the sprite float delta = h / w; x = delta * x; if ((x >= 0) && (x <= 1)) { // coordinates of the character in the font atlas vec2 coord = flat_text_map.xy + vec2(w * x, h * y); float letter_alpha = texture2D(tex_sampler, coord).a; out_color = color * letter_alpha; out_color.a = %s; } else out_color = vec4(0, 0, 0, 0); """ % background_transparent_shader return fs class TextVisual(Visual): """Template for displaying short text on a single line. It uses the following technique: each character is rendered as a sprite, i.e. a pixel with a large point size, and a single texture for every point. The texture contains a font atlas, i.e. all characters in a given font. Every point comes with coordinates that indicate which small portion of the font atlas to display (that portion corresponds to the character). This is all done automatically, thanks to a font atlas stored in the `fontmaps` folder. There needs to be one font atlas per font and per font size. Also, there is a configuration text file with the coordinates and size of every character. The software used to generate font maps is AngelCode Bitmap Font Generator. For now, there is only the Segoe font. """ def position_compound(self, coordinates=None): """Compound variable with the position of the text. All characters are at the exact same position, and are then shifted in the vertex shader.""" if coordinates is None: coordinates = (0., 0.) if type(coordinates) == tuple: coordinates = [coordinates] coordinates = np.array(coordinates) position = np.repeat(coordinates, self.textsizes, axis=0) return dict(position=position) def text_compound(self, text): """Compound variable for the text string. It changes the text map, the character position, and the text width.""" coordinates = self.coordinates if "\n" in text: text = text.split("\n") if type(text) == list: self.textsizes = [len(t) for t in text] text = "".join(text) if type(coordinates) != list: coordinates = [coordinates] * len(self.textsizes) index = np.repeat(np.arange(len(self.textsizes)), self.textsizes) text_map = self.get_map(text) # offset for all characters in the merging of all texts offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) # for each text, the cumsum of the length of all texts strictly # before d = np.hstack(([0], np.cumsum(self.textsizes)[:-1])) # compensate the offsets for the length of each text offset -= np.repeat(offset[d], self.textsizes) text_width = 0. else: self.textsizes = len(text) text_map = self.get_map(text) offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) text_width = offset[-1] index = np.zeros(len(text)) self.size = len(text) d = dict(text_map=text_map, offset=offset, text_width=text_width, index=index) d.update(self.position_compound(coordinates)) return d def initialize_font(self, font, fontsize): """Initialize the specified font at a given size.""" self.texture, self.matrix, self.get_map = load_font(font, fontsize) def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24, color=None, letter_spacing=None, interline=0., autocolor=None, background_transparent=True, prevent_constrain=False, depth=None, posoffset=None): """Initialize the text template.""" if prevent_constrain: self.constrain_ratio = False if autocolor is not None: color = get_color(autocolor) if color is None: color = self.default_color self.size = len(text) self.primitive_type = 'POINTS' self.interline = interline text_length = self.size self.initialize_font(font, fontsize) self.coordinates = coordinates point_size = float(self.matrix[:,4].max() * self.texture.shape[1]) # template attributes and varyings self.add_attribute("position", vartype="float", ndim=2, data=np.zeros((self.size, 2))) self.add_attribute("offset", vartype="float", ndim=1) self.add_attribute("index", vartype="float", ndim=1) self.add_attribute("text_map", vartype="float", ndim=4) self.add_varying("flat_text_map", vartype="float", flat=True, ndim=4) if posoffset is None: posoffset = (0., 0.) self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset) # texture self.add_texture("tex_sampler", size=self.texture.shape[:2], ndim=2, ncomponents=self.texture.shape[2], data=self.texture) # pure heuristic (probably bogus) if letter_spacing is None: letter_spacing = (100 + 17. * fontsize) self.add_uniform("spacing", vartype="float", ndim=2, data=(letter_spacing, interline)) self.add_uniform("point_size", vartype="float", ndim=1, data=point_size) # one color per if isinstance(color, np.ndarray) and color.ndim > 1: self.add_attribute('color0', vartype="float", ndim=4, data=color) self.add_varying('color', vartype="float", ndim=4) self.add_vertex_main('color = color0;') else: self.add_uniform("color", vartype="float", ndim=4, data=color) self.add_uniform("text_width", vartype="float", ndim=1) # compound variables self.add_compound("text", fun=self.text_compound, data=text) self.add_compound("coordinates", fun=self.position_compound, data=coordinates) # vertex shader self.add_vertex_main(VS, after='viewport') # fragment shader self.add_fragment_main(FS(background_transparent)) self.depth = depth
DavidTingley/ephys-processing-pipeline
installation/klustaviewa-0.3.0/galry/visuals/text_visual.py
Python
gpl-3.0
7,555
package simulator; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import cartago.OPERATION; import cartago.tools.GUIArtifact; public class House extends GUIArtifact { HouseView view; @Override public void init(){ view = new HouseView(); view.setVisible(true); } // Actions that simulate the building progress @OPERATION void prepareSite(){ view.addPart(new Site()); } @OPERATION void layFloors(){ await_time(1000); view.addPart(new Floor()); } @OPERATION void buildWalls(){ await_time(500); view.addPart(new Walls()); } @OPERATION void buildRoof(){ await_time(1000); view.addPart(new Roof()); } @OPERATION void fitDoors(){ await_time(300); view.addPart(new Doors()); } @OPERATION void fitWindows(){ await_time(300); view.addPart(new Windows()); } @OPERATION void paintExterior(){ await_time(2000); view.addPart(new ExteriorPainting()); } @OPERATION void installPlumbing(){ await_time(300); view.addPart(new Plumbing()); } @OPERATION void installElectricalSystem(){ await_time(300); view.addPart(new ElectricalSystem()); } @OPERATION void paintInterior(){ await_time(500); view.addPart(new InteriorPainting()); } class HouseView extends JFrame { HousePanel housePanel; ArrayList<HousePart> partsToDraw; public HouseView(){ setTitle(" -- Home Sweet Home -- "); setSize(800,600); partsToDraw = new ArrayList<HousePart>(); housePanel = new HousePanel(this); setContentPane(housePanel); } public synchronized void addPart(HousePart part){ partsToDraw.add(part); repaint(); } public synchronized ArrayList<HousePart> getParts(){ return (ArrayList<HousePart>)partsToDraw.clone(); } } class HousePanel extends JPanel { HouseView view; public HousePanel(HouseView view){ this.view = view; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); Dimension size = getSize(); g.fillRect(0, 0, size.width, size.height); for (HousePart part: view.getParts()){ part.draw(size,(Graphics2D)g); } } } }
jomifred/jacamo
examples/house-building/src/env/simulator/House.java
Java
gpl-3.0
2,704
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */ YUI.add('dataschema-json', function (Y, NAME) { /** Provides a DataSchema implementation which can be used to work with JSON data. @module dataschema @submodule dataschema-json **/ /** Provides a DataSchema implementation which can be used to work with JSON data. See the `apply` method for usage. @class DataSchema.JSON @extends DataSchema.Base @static **/ var LANG = Y.Lang, isFunction = LANG.isFunction, isObject = LANG.isObject, isArray = LANG.isArray, // TODO: I don't think the calls to Base.* need to be done via Base since // Base is mixed into SchemaJSON. Investigate for later. Base = Y.DataSchema.Base, SchemaJSON; SchemaJSON = { ///////////////////////////////////////////////////////////////////////////// // // DataSchema.JSON static methods // ///////////////////////////////////////////////////////////////////////////// /** * Utility function converts JSON locator strings into walkable paths * * @method getPath * @param locator {String} JSON value locator. * @return {String[]} Walkable path to data value. * @static */ getPath: function(locator) { var path = null, keys = [], i = 0; if (locator) { // Strip the ["string keys"] and [1] array indexes // TODO: the first two steps can probably be reduced to one with // /\[\s*(['"])?(.*?)\1\s*\]/g, but the array indices would be // stored as strings. This is not likely an issue. locator = locator. replace(/\[\s*(['"])(.*?)\1\s*\]/g, function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}). replace(/\[(\d+)\]/g, function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}). replace(/^\./,''); // remove leading dot // Validate against problematic characters. // commented out because the path isn't sent to eval, so it // should be safe. I'm not sure what makes a locator invalid. //if (!/[^\w\.\$@]/.test(locator)) { path = locator.split('.'); for (i=path.length-1; i >= 0; --i) { if (path[i].charAt(0) === '@') { path[i] = keys[parseInt(path[i].substr(1),10)]; } } /*} else { Y.log("Invalid locator: " + locator, "error", "dataschema-json"); } */ } return path; }, /** * Utility function to walk a path and return the value located there. * * @method getLocationValue * @param path {String[]} Locator path. * @param data {String} Data to traverse. * @return {Object} Data value at location. * @static */ getLocationValue: function (path, data) { var i = 0, len = path.length; for (;i<len;i++) { if (isObject(data) && (path[i] in data)) { data = data[path[i]]; } else { data = undefined; break; } } return data; }, /** Applies a schema to an array of data located in a JSON structure, returning a normalized object with results in the `results` property. Additional information can be parsed out of the JSON for inclusion in the `meta` property of the response object. If an error is encountered during processing, an `error` property will be added. The input _data_ is expected to be an object or array. If it is a string, it will be passed through `Y.JSON.parse()`. If _data_ contains an array of data records to normalize, specify the _schema.resultListLocator_ as a dot separated path string just as you would reference it in JavaScript. So if your _data_ object has a record array at _data.response.results_, use _schema.resultListLocator_ = "response.results". Bracket notation can also be used for array indices or object properties (e.g. "response['results']"); This is called a "path locator" Field data in the result list is extracted with field identifiers in _schema.resultFields_. Field identifiers are objects with the following properties: * `key` : <strong>(required)</strong> The path locator (String) * `parser`: A function or the name of a function on `Y.Parsers` used to convert the input value into a normalized type. Parser functions are passed the value as input and are expected to return a value. If no value parsing is needed, you can use path locators (strings) instead of field identifiers (objects) -- see example below. If no processing of the result list array is needed, _schema.resultFields_ can be omitted; the `response.results` will point directly to the array. If the result list contains arrays, `response.results` will contain an array of objects with key:value pairs assuming the fields in _schema.resultFields_ are ordered in accordance with the data array values. If the result list contains objects, the identified _schema.resultFields_ will be used to extract a value from those objects for the output result. To extract additional information from the JSON, include an array of path locators in _schema.metaFields_. The collected values will be stored in `response.meta`. @example // Process array of arrays var schema = { resultListLocator: 'produce.fruit', resultFields: [ 'name', 'color' ] }, data = { produce: { fruit: [ [ 'Banana', 'yellow' ], [ 'Orange', 'orange' ], [ 'Eggplant', 'purple' ] ] } }; var response = Y.DataSchema.JSON.apply(schema, data); // response.results[0] is { name: "Banana", color: "yellow" } // Process array of objects + some metadata schema.metaFields = [ 'lastInventory' ]; data = { produce: { fruit: [ { name: 'Banana', color: 'yellow', price: '1.96' }, { name: 'Orange', color: 'orange', price: '2.04' }, { name: 'Eggplant', color: 'purple', price: '4.31' } ] }, lastInventory: '2011-07-19' }; response = Y.DataSchema.JSON.apply(schema, data); // response.results[0] is { name: "Banana", color: "yellow" } // response.meta.lastInventory is '2001-07-19' // Use parsers schema.resultFields = [ { key: 'name', parser: function (val) { return val.toUpperCase(); } }, { key: 'price', parser: 'number' // Uses Y.Parsers.number } ]; response = Y.DataSchema.JSON.apply(schema, data); // Note price was converted from a numeric string to a number // response.results[0] looks like { fruit: "BANANA", price: 1.96 } @method apply @param {Object} [schema] Schema to apply. Supported configuration properties are: @param {String} [schema.resultListLocator] Path locator for the location of the array of records to flatten into `response.results` @param {Array} [schema.resultFields] Field identifiers to locate/assign values in the response records. See above for details. @param {Array} [schema.metaFields] Path locators to extract extra non-record related information from the data object. @param {Object|Array|String} data JSON data or its string serialization. @return {Object} An Object with properties `results` and `meta` @static **/ apply: function(schema, data) { var data_in = data, data_out = { results: [], meta: {} }; // Convert incoming JSON strings if (!isObject(data)) { try { data_in = Y.JSON.parse(data); } catch(e) { data_out.error = e; return data_out; } } if (isObject(data_in) && schema) { // Parse results data data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out); // Parse meta data if (schema.metaFields !== undefined) { data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out); } } else { Y.log("JSON data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-json"); data_out.error = new Error("JSON schema parse failure"); } return data_out; }, /** * Schema-parsed list of results from full data * * @method _parseResults * @param schema {Object} Schema to parse against. * @param json_in {Object} JSON to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Parsed data object. * @static * @protected */ _parseResults: function(schema, json_in, data_out) { var getPath = SchemaJSON.getPath, getValue = SchemaJSON.getLocationValue, path = getPath(schema.resultListLocator), results = path ? (getValue(path, json_in) || // Fall back to treat resultListLocator as a simple key json_in[schema.resultListLocator]) : // Or if no resultListLocator is supplied, use the input json_in; if (isArray(results)) { // if no result fields are passed in, then just take // the results array whole-hog Sometimes you're getting // an array of strings, or want the whole object, so // resultFields don't make sense. if (isArray(schema.resultFields)) { data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out); } else { data_out.results = results; } } else if (schema.resultListLocator) { data_out.results = []; data_out.error = new Error("JSON results retrieval failure"); Y.log("JSON data could not be parsed: " + Y.dump(json_in), "error", "dataschema-json"); } return data_out; }, /** * Get field data values out of list of full results * * @method _getFieldValues * @param fields {Array} Fields to find. * @param array_in {Array} Results to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Parsed data object. * @static * @protected */ _getFieldValues: function(fields, array_in, data_out) { var results = [], len = fields.length, i, j, field, key, locator, path, parser, val, simplePaths = [], complexPaths = [], fieldParsers = [], result, record; // First collect hashes of simple paths, complex paths, and parsers for (i=0; i<len; i++) { field = fields[i]; // A field can be a simple string or a hash key = field.key || field; // Find the key locator = field.locator || key; // Find the locator // Validate and store locators for later path = SchemaJSON.getPath(locator); if (path) { if (path.length === 1) { simplePaths.push({ key : key, path: path[0] }); } else { complexPaths.push({ key : key, path : path, locator: locator }); } } else { Y.log("Invalid key syntax: " + key, "warn", "dataschema-json"); } // Validate and store parsers for later //TODO: use Y.DataSchema.parse? parser = (isFunction(field.parser)) ? field.parser : Y.Parsers[field.parser + '']; if (parser) { fieldParsers.push({ key : key, parser: parser }); } } // Traverse list of array_in, creating records of simple fields, // complex fields, and applying parsers as necessary for (i=array_in.length-1; i>=0; --i) { record = {}; result = array_in[i]; if(result) { // Cycle through complexLocators for (j=complexPaths.length - 1; j>=0; --j) { path = complexPaths[j]; val = SchemaJSON.getLocationValue(path.path, result); if (val === undefined) { val = SchemaJSON.getLocationValue([path.locator], result); // Fail over keys like "foo.bar" from nested parsing // to single token parsing if a value is found in // results["foo.bar"] if (val !== undefined) { simplePaths.push({ key: path.key, path: path.locator }); // Don't try to process the path as complex // for further results complexPaths.splice(i,1); continue; } } record[path.key] = Base.parse.call(this, (SchemaJSON.getLocationValue(path.path, result)), path); } // Cycle through simpleLocators for (j = simplePaths.length - 1; j >= 0; --j) { path = simplePaths[j]; // Bug 1777850: The result might be an array instead of object record[path.key] = Base.parse.call(this, ((result[path.path] === undefined) ? result[j] : result[path.path]), path); } // Cycle through fieldParsers for (j=fieldParsers.length-1; j>=0; --j) { key = fieldParsers[j].key; record[key] = fieldParsers[j].parser.call(this, record[key]); // Safety net if (record[key] === undefined) { record[key] = null; } } results[i] = record; } } data_out.results = results; return data_out; }, /** * Parses results data according to schema * * @method _parseMeta * @param metaFields {Object} Metafields definitions. * @param json_in {Object} JSON to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Schema-parsed meta data. * @static * @protected */ _parseMeta: function(metaFields, json_in, data_out) { if (isObject(metaFields)) { var key, path; for(key in metaFields) { if (metaFields.hasOwnProperty(key)) { path = SchemaJSON.getPath(metaFields[key]); if (path && json_in) { data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in); } } } } else { data_out.error = new Error("JSON meta data retrieval failure"); } return data_out; } }; // TODO: Y.Object + mix() might be better here Y.DataSchema.JSON = Y.mix(SchemaJSON, Base); }, '3.9.0pr1', {"requires": ["dataschema-base", "json"]});
rochestb/Adventurly
node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/dataschema-json/dataschema-json-debug.js
JavaScript
gpl-3.0
16,312
/* (c) Copyright 2011-2014 Felipe Magno de Almeida * * 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 ghtv.awt; import java.awt.Container; import java.awt.Component; public class LwuitComponent extends Container { private com.sun.dtv.lwuit.Component lwuit_component; public LwuitComponent(com.sun.dtv.lwuit.Component c) { assert c != null; lwuit_component = c; } public void paint(java.awt.Graphics g) { java.awt.Graphics2D g2d = (java.awt.Graphics2D)g; lwuit_component.paint(new com.sun.dtv.lwuit.Graphics(g2d)); } // public void longKeyPress(int keyCode) // { // form.longKeyPress(keyCode); // } // public void keyPressed(int keyCode) // { // form.keyPressed(keyCode); // } // public void keyReleased(int keyCode) // { // form.keyReleased(keyCode); // } // public void keyRepeated(int keyCode) // { // form.keyRepeated(keyCode); // } // public void pointerPressed(int x, int y) // { // form.pointerPressed(x, y); // } // public void pointerDragged(int x, int y) // { // form.pointerDragged(x, y); // } }
expertisesolutions/ghtv-ncl-player
java/ghtv/awt/LwuitComponent.java
Java
gpl-3.0
1,801
<?php /** * Runtime Extension Hhvm * * include patch for modified compiled or cached templates * HHVM does not check if file was modified when including same file multiple times * * @package Smarty * @subpackage PluginsInternal * @author Uwe Tews */ class Smarty_Internal_Runtime_Hhvm { /** * * @param \Smarty_Internal_Template $_template * @param string $file * file name * * @return mixed */ static function includeHhvm(Smarty_Internal_Template $_template, $file) { $_smarty_tpl = $_template; $tmp_file = $file . preg_replace ( '![^\w]+!', '_', uniqid ( rand (), true ) ) . '.php'; file_put_contents ( $tmp_file, file_get_contents ( $file ) ); $result = @include $tmp_file; @unlink ( $tmp_file ); return $result; } }
J0hnHawk/FS17_NF_Marsch_WebStats
include/smarty/sysplugins/smarty_internal_runtime_hhvm.php
PHP
gpl-3.0
819
import React, { Component, PropTypes } from 'react'; import { View, Image, Text, StyleSheet } from 'react-native'; import LinearGradient from 'react-native-linear-gradient'; const glassPrimary = '#d5d2da'; const glassSecondary = '#bb2130'; class ProfilePicture extends Component { render() { const profileImage = this.props.image; return ( <View style={Styles.container}> <Image source={profileImage} resizeMode='contain' style={Styles.profilePic}> </Image> <LinearGradient colors={[glassPrimary, glassSecondary, glassPrimary]} start={{x: 0.0, y: 0.1}} end={{x: 0.5, y: 1.0}} style={Styles.frame}> </LinearGradient> </View> ) } } const Styles = StyleSheet.create({ container: { height: 120, width: 70, shadowColor: '#000', shadowOffset: { width: 2, height: 2 }, shadowOpacity: 0.7, shadowRadius: 2, elevation: 3, backgroundColor: 'transparent' }, profilePic: { height: 120, width: 70, shadowRadius: 2, shadowOpacity: 0.7, shadowColor: '#000000', borderColor: '#320f1c', borderWidth: 1, }, frame: { position: 'absolute', top: 0, height: 120, width: 70, opacity: 0.25, } }); export default ProfilePicture;
TekkenChicken/t7-chicken-native
src/components/CharacterProfile/ProfilePicture.js
JavaScript
gpl-3.0
1,316
//Copyright (c) 2008-2009 Emil Dotchevski and Reverge Studios, Inc. //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef UUID_D6250026A17F11DEA29012BF55D89593 #define UUID_D6250026A17F11DEA29012BF55D89593 #include <boost/la/config.hpp> #include <boost/la/deduce_matrix.hpp> #include <boost/assert.hpp> #include <boost/static_assert.hpp> namespace boost { namespace la { namespace la_detail { template <class T,int Dim> class identity_matrix_ { identity_matrix_( identity_matrix_ const & ); identity_matrix_ & operator=( identity_matrix_ const & ); ~identity_matrix_(); public: template <class R> BOOST_LA_INLINE_TRIVIAL operator R() const { R r; assign(r,*this); return r; } }; } template <class Matrix> struct matrix_traits; template <class T,int Dim> struct matrix_traits< la_detail::identity_matrix_<T,Dim> > { typedef la_detail::identity_matrix_<T,Dim> this_matrix; typedef T scalar_type; static int const rows=Dim; static int const cols=Dim; template <int Row,int Col> static BOOST_LA_INLINE_CRITICAL scalar_type r( this_matrix const & x ) { BOOST_ASSERT(&x==0); BOOST_STATIC_ASSERT(Row>=0); BOOST_STATIC_ASSERT(Row<Dim); BOOST_STATIC_ASSERT(Col>=0); BOOST_STATIC_ASSERT(Col<Dim); return scalar_type(Row==Col); } static BOOST_LA_INLINE_CRITICAL scalar_type ir( int row, int col, this_matrix const & x ) { BOOST_ASSERT(&x==0); BOOST_ASSERT(row>=0); BOOST_ASSERT(row<Dim); BOOST_ASSERT(col>=0); BOOST_ASSERT(col<Dim); return scalar_type(row==col); } }; template <class T,int Dim,int R,int C,class S> struct deduce_matrix<la_detail::identity_matrix_<T,Dim>,R,C,S> { typedef mat<S,R,C> type; }; template <class T,int Dim> BOOST_LA_INLINE_TRIVIAL la_detail::identity_matrix_<T,Dim> const & identity_matrix() { return *(la_detail::identity_matrix_<T,Dim> const *)0; } } } #endif
kelvindk/Video-Stabilization
la/boost/la/identity_matrix.hpp
C++
gpl-3.0
2,136
function helloWorld() { return 'Hello World'; }
hacktoberfest17/programming
hello_world/js/Hello-world.js
JavaScript
gpl-3.0
50
/*============================================================================= Copyright (c) 2009 Hartmut Kaiser Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_NVIEW_SEP_23_2009_0948PM) #define BOOST_FUSION_NVIEW_SEP_23_2009_0948PM #include <boost/mpl/size.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/vector_c.hpp> #include <boost/utility/result_of.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/add_reference.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/fusion/support/is_view.hpp> #include <boost/fusion/support/category_of.hpp> #include <boost/fusion/support/sequence_base.hpp> #include <boost/fusion/container/vector.hpp> #include <boost/fusion/view/transform_view.hpp> #include <boost/config.hpp> namespace boost { namespace fusion { namespace detail { struct addref { template<typename Sig> struct result; template<typename U> struct result<addref(U)> : add_reference<U> {}; #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES template <typename T> typename add_reference<T>::type operator()(T& x) const { return x; } #else template <typename T> typename result<addref(T)>::type operator()(T&& x) const { return x; } #endif }; struct addconstref { template<typename Sig> struct result; template<typename U> struct result<addconstref(U)> : add_reference<typename add_const<U>::type> {}; template <typename T> typename add_reference<typename add_const<T>::type>::type operator()(T& x) const { return x; } template <typename T> typename add_reference<typename add_const<T>::type>::type operator()(T const& x) const { return x; } }; } struct nview_tag; struct random_access_traversal_tag; struct fusion_sequence_tag; template<typename Sequence, typename Indicies> struct nview : sequence_base<nview<Sequence, Indicies> > { typedef nview_tag fusion_tag; typedef fusion_sequence_tag tag; // this gets picked up by MPL typedef random_access_traversal_tag category; typedef mpl::true_ is_view; typedef Indicies index_type; typedef typename mpl::size<Indicies>::type size; typedef typename mpl::if_< is_const<Sequence>, detail::addconstref, detail::addref >::type transform_type; typedef transform_view<Sequence, transform_type> transform_view_type; typedef typename result_of::as_vector<transform_view_type>::type sequence_type; explicit nview(Sequence& val) : seq(sequence_type(transform_view_type(val, transform_type()))) {} sequence_type seq; }; }} // define the nview() generator functions #include <boost/fusion/view/nview/detail/nview_impl.hpp> #endif
N00byEdge/ProjectDurr
lib/boost/boost/fusion/view/nview/nview.hpp
C++
gpl-3.0
3,538
/* * MindmapsDB - A Distributed Semantic Database * Copyright (C) 2016 Mindmaps Research Ltd * * MindmapsDB 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. * * MindmapsDB 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 MindmapsDB. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package io.mindmaps.graph.internal; import io.mindmaps.concept.Resource; import io.mindmaps.concept.ResourceType; import io.mindmaps.exception.InvalidConceptValueException; import io.mindmaps.util.ErrorMessage; import io.mindmaps.util.Schema; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A Resource Type which can hold different values. * @param <D> The data tyoe of this resource type. */ class ResourceTypeImpl<D> extends TypeImpl<ResourceType<D>, Resource<D>> implements ResourceType<D> { ResourceTypeImpl(Vertex v, AbstractMindmapsGraph mindmapsGraph) { super(v, mindmapsGraph); } ResourceTypeImpl(Vertex v, AbstractMindmapsGraph mindmapsGraph, DataType<D> type) { super(v, mindmapsGraph); setDataType(type); } /** * * @param type The data type of the resource */ private void setDataType(DataType<D> type) { setProperty(Schema.ConceptProperty.DATA_TYPE, type.getName()); } /** * @param regex The regular expression which instances of this resource must conform to. * @return The Resource Type itself. */ @Override public ResourceType<D> setRegex(String regex) { if(!getDataType().equals(DataType.STRING)){ throw new UnsupportedOperationException(ErrorMessage.REGEX_NOT_STRING.getMessage(toString())); } if(regex != null) { Pattern pattern = Pattern.compile(regex); Matcher matcher; for (Resource<D> resource : instances()) { String value = (String) resource.getValue(); matcher = pattern.matcher(value); if(!matcher.matches()){ throw new InvalidConceptValueException(ErrorMessage.REGEX_INSTANCE_FAILURE.getMessage(regex, resource.toString())); } } } return setProperty(Schema.ConceptProperty.REGEX, regex); } /** * @return The data type which instances of this resource must conform to. */ //This unsafe cast is suppressed because at this stage we do not know what the type is when reading from the rootGraph. @SuppressWarnings("unchecked") @Override public DataType<D> getDataType() { Object object = getProperty(Schema.ConceptProperty.DATA_TYPE); return (DataType<D>) DataType.SUPPORTED_TYPES.get(String.valueOf(object)); } /** * @return The regular expression which instances of this resource must conform to. */ @Override public String getRegex() { Object object = getProperty(Schema.ConceptProperty.REGEX); if(object == null) return null; return (String) object; } }
denislobanov/grakn
mindmaps-graph/src/main/java/io/mindmaps/graph/internal/ResourceTypeImpl.java
Java
gpl-3.0
3,522
""" # Notes: - This simulation seeks to emulate the CUBA benchmark simulations of (Brette et al. 2007) using the Brian2 simulator for speed benchmark comparison to DynaSim. However, this simulation does NOT include synapses, for better comparison to Figure 5 of (Goodman and Brette, 2008). - The time taken to simulate will be indicated in the stdout log file '~/batchdirs/brian_benchmark_CUBA_nosyn_250/pbsout/brian_benchmark_CUBA_nosyn_250.out' - Note that this code has been slightly modified from the original (Brette et al. 2007) benchmarking code, available here on ModelDB: https://senselab.med.yale.edu/modeldb/showModel.cshtml?model=83319 in order to work with version 2 of the Brian simulator (aka Brian2), and also modified to change the model being benchmarked, etc. # References: - Brette R, Rudolph M, Carnevale T, Hines M, Beeman D, Bower JM, et al. Simulation of networks of spiking neurons: A review of tools and strategies. Journal of Computational Neuroscience 2007;23:349–98. doi:10.1007/s10827-007-0038-6. - Goodman D, Brette R. Brian: a simulator for spiking neural networks in Python. Frontiers in Neuroinformatics 2008;2. doi:10.3389/neuro.11.005.2008. """ from brian2 import * # Parameters cells = 250 defaultclock.dt = 0.01*ms taum=20*ms Vt = -50*mV Vr = -60*mV El = -49*mV # The model eqs = Equations(''' dv/dt = ((v-El))/taum : volt ''') P = NeuronGroup(cells, model=eqs,threshold="v>Vt",reset="v=Vr",refractory=5*ms, method='euler') proportion=int(0.8*cells) Pe = P[:proportion] Pi = P[proportion:] # Initialization P.v = Vr # Record a few traces trace = StateMonitor(P, 'v', record=[1, 10, 100]) totaldata = StateMonitor(P, 'v', record=True) run(0.5 * second, report='text') # plot(trace.t/ms, trace[1].v/mV) # plot(trace.t/ms, trace[10].v/mV) # plot(trace.t/ms, trace[100].v/mV) # xlabel('t (ms)') # ylabel('v (mV)') # show() # print("Saving TC cell voltages!") # numpy.savetxt("foo_totaldata.csv", totaldata.v/mV, delimiter=",")
asoplata/dynasim-benchmark-brette-2007
output/Brian2/brian2_benchmark_CUBA_nosyn_250/brian2_benchmark_CUBA_nosyn_250.py
Python
gpl-3.0
2,003
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.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/ **********************************************************************/ package keel.Algorithms.Instance_Generation.BasicMethods; import keel.Algorithms.Instance_Generation.Basic.PrototypeSet; import keel.Algorithms.Instance_Generation.Basic.PrototypeGenerator; import keel.Algorithms.Instance_Generation.Basic.Prototype; import keel.Algorithms.Instance_Generation.Basic.PrototypeGenerationAlgorithm; import keel.Algorithms.Instance_Generation.*; import java.util.*; import keel.Algorithms.Instance_Generation.utilities.*; import keel.Algorithms.Instance_Generation.utilities.KNN.*; import org.core.*; /** * Implements the reduction of the prototype set, making a centroid for each class. * That is, it adds average prototypes of each class to the reduced set. * @author diegoj */ public class AVG extends PrototypeGenerator { /** * Constructs the AVG * @param _trainingDataSet Original training prototypes set. */ public AVG(PrototypeSet _trainingDataSet) { super(_trainingDataSet); algorithmName="AVG"; } /** * Constructs the AVG * @param _trainingDataSet Original training prototypes set. * @param param Parameters of the algorithm (random seed). */ public AVG(PrototypeSet _trainingDataSet, Parameters param) { super(_trainingDataSet, param); algorithmName="AVG"; } /** * Reduces the set by adding centroid prototype of each class to reduced set. * @return Reduced set of centroids of classes of the original training set. */ @Override public PrototypeSet reduceSet() { PrototypeSet reduced = new PrototypeSet(); ArrayList<Double> classes = trainingDataSet.nonVoidClasses(); //For each class in the training data set, calculate the centroid of //its class-partition and adds it to the reduced set. for(double c : classes) { PrototypeSet Tc = trainingDataSet.getFromClass(c); //Debug.errorln("Number of ps of class " + c + ": " + Tc.size()); Prototype centroid_c =Tc.avg(); centroid_c.setLabel(c); reduced.add(centroid_c); } return reduced; } /** * General main for all the prototoype generators * Arguments: * 0: Filename with the training data set to be condensed. * 1: Filename wich will contain the test data set * @param args Arguments of the main function. */ public static void main(String[] args) { Parameters.setUse("AVG", ""); Parameters.assertBasicArgs(args); PrototypeSet training = PrototypeGenerationAlgorithm.readPrototypeSet(args[0]); PrototypeSet test = PrototypeGenerationAlgorithm.readPrototypeSet(args[1]); AVG generator = new AVG(training); PrototypeSet resultingSet = generator.execute(); int accuracy1NN = KNN.classficationAccuracy(resultingSet, test); generator.showResultsOfAccuracy(Parameters.getFileName(), accuracy1NN, test); } }//end-of-class
TheMurderer/keel
src/keel/Algorithms/Instance_Generation/BasicMethods/AVG.java
Java
gpl-3.0
4,311
# Copyright 2008-2014 Amazon.com, Inc. or its affiliates. All Rights # Reserved. Licensed under the Amazon Software License (the # "License"). You may not use this file except in compliance with the # License. A copy of the License is located at # http://aws.amazon.com/asl or in the "license" file accompanying this # file. This file is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See # the License for the specific language governing permissions and # limitations under the License. # # A class to contain headers and sign them with signature version 4 # This code is a shameless copy of our SDK's signature version 4 code base # require 'cgi' require 'uri' require 'time' require 'base64' require 'tempfile' require 'digest/md5' require 'openssl' require 'digest' require 'digest/sha2' module EC2 module Common class HeadersV4 # Create an HttpHeaderV4, # values = { # :host -> http host # :hexdigest_body -> hexdigest of the http request's body # :region -> region of the endpoint # :service -> the service that should recieve this request # :http_method -> http method # :path -> URI # :querystring -> Everything after ? in URI # :access_key_id -> access key # :secret_access_key -> secret access kry # [optional] :fixed_datetime -> Fix the datetime using DateTime object, do not use Time.now # } # For more info see: # http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html def initialize values, headers={} @headers = headers @host = values[:host] @hexdigest_body = values[:hexdigest_body] @region = values[:region] @service = values[:service] @http_method = values[:http_method] @path = values[:path] @querystring = values[:querystring] @access_key_id = values[:access_key_id] @secret_access_key = values[:secret_access_key] @fixed_datetime = values[:fixed_datetime] end def add_authorization! datetime = get_datetime @headers['host'] = @host @headers['x-amz-date'] = datetime @headers['x-amz-content-sha256'] ||= @hexdigest_body || EC2::Common::HeadersV4::hexdigest('') @headers['authorization'] = authorization(datetime) @headers end def authorization datetime parts = [] parts << "AWS4-HMAC-SHA256 Credential=#{credential(datetime)}" parts << "SignedHeaders=#{signed_headers}" parts << "Signature=#{signature(datetime)}" parts.join(', ') end def signature datetime k_secret = @secret_access_key k_date = hmac("AWS4" + k_secret, datetime[0,8]) k_region = hmac(k_date, @region) k_service = hmac(k_region, @service) k_credentials = hmac(k_service, 'aws4_request') hexhmac(k_credentials, string_to_sign(datetime)) end def string_to_sign datetime parts = [] parts << 'AWS4-HMAC-SHA256' parts << datetime parts << credential_string(datetime) parts << EC2::Common::HeadersV4::hexdigest(canonical_request) parts.join("\n") end def credential datetime "#{@access_key_id}/#{credential_string(datetime)}" end def credential_string datetime parts = [] parts << datetime[0,8] parts << @region parts << @service parts << 'aws4_request' parts.join("/") end def canonical_request parts = [] parts << @http_method parts << CGI::unescape(@path) parts << canonical_querystring parts << canonical_headers + "\n" parts << signed_headers parts << @headers['x-amz-content-sha256'] parts.join("\n") end def signed_headers to_sign = @headers.keys.map{|k| k.to_s.downcase} to_sign.delete('authorization') to_sign.sort.join(";") end def canonical_querystring CGI::parse(@querystring).sort_by{|k,v| CGI::escape(k)}.map do |v| value = v[1][0] || "" "#{CGI::escape(v[0])}=#{CGI::escape(value)}" end.join('&') end def canonical_headers headers = [] @headers.each_pair do |k,v| k_lower = k.downcase headers << [k_lower,v] unless k_lower == 'authorization' end headers = headers.sort_by{|k,v| k} headers.map{|k,v| "#{k}:#{canonical_header_values(v)}"}.join("\n") end def canonical_header_values values values = [values] unless values.is_a?(Array) values.map{|v|v.to_s}.join(',').gsub(/\s+/, ' ').strip end def hmac key, value OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha256'), key, value) end def hexhmac key, value OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha256'), key, value) end def get_datetime return @fixed_datetime.strftime("%Y%m%dT%H%M%SZ") if @fixed_datetime != nil Time.now.utc.strftime("%Y%m%dT%H%M%SZ") end # Returns a SHA256 hexdigest of value. # Should be used to hexdigest body of http request. def self.hexdigest value, chunk_size = 1024 * 1024 digest = Digest::SHA256.new if value.respond_to?(:read) chunk = nil digest.update(chunk) while chunk = value.read(chunk_size) value.rewind else digest.update(value) end digest.hexdigest end end end end
atramos/ec2-spotter
classic/ec2-ami-tools-1.5.7/lib/ec2/common/headersv4.rb
Ruby
gpl-3.0
5,629
<?php require_once GTFWConfiguration::GetValue('application','docroot').'module/data_pegawai/business/data_pegawai.class.php'; class Cuti extends Database { protected $mSqlFile= 'module/data_cuti/business/cuti.sql.php'; function __construct($connectionNumber=0) { parent::__construct($connectionNumber); // } function GetQueryKeren($sql,$params) { foreach ($params as $k => $v) { if (is_array($v)) { $params[$k] = '~~' . join("~~,~~", $v) . '~~'; $params[$k] = str_replace('~~', '\'', addslashes($params[$k])); } else { $params[$k] = addslashes($params[$k]); } } $param_serialized = '~~' . join("~~,~~", $params) . '~~'; $param_serialized = str_replace('~~', '\'', addslashes($param_serialized)); eval('$sql_parsed = sprintf("' . $sql . '", ' . $param_serialized . ');'); //echo $sql_parsed; return $sql_parsed; } //==GET== function GetCount($nip_nama='') { if($nip_nama != ""){ $str = " WHERE (pegKodeResmi LIKE '%".$nip_nama."%' OR pegNama LIKE '%".$nip_nama."%')"; }else{ $str = ""; } $result = $this->GetQueryKeren($this->mSqlQueries['get_count1'], array($str)); $res2 = $this->Open(stripslashes($result), array()); $res3 = sizeof($res2); if (!$res3) { //return 0; } else { //return $res3; } $Obj = new DataPegawai; $totalData = $Obj->GetCountPegawaiByUserId($nip_nama, 'all'); return $totalData; } function GetData ($offset, $limit, $nip_nama='') { if($nip_nama != ""){ $str = " WHERE (pegKodeResmi LIKE '%".$nip_nama."%' OR pegNama LIKE '%".$nip_nama."%')"; }else{ $str = ""; } $result = $this->GetQueryKeren($this->mSqlQueries['get_data1'], array($str, $offset, $limit)); //return $this->Open(stripslashes($result), array()); $Obj = new DataPegawai; $result = $Obj->GetDataPegawaiByUserId($offset, $limit, $nip_nama, 'all'); return $result; } function GetCountCuti($idPeg, $tampil,$year,$nomor) { if($tampil != "all"){ $str = " AND cutiStatus = '".$tampil."'"; }else{ $str = ""; } $str .= " AND cutiNo LIKE '%".$nomor."%'"; $str .= " AND YEAR(cutiMulai)=".$year; $result = $this->GetQueryKeren($this->mSqlQueries['get_count2'], array($idPeg, $str)); $res2 = $this->Open(stripslashes($result), array()); $res3 = sizeof($res2); if (!$res3) { return 0; } else { return $res3; } } function GetDataCuti($offset, $limit, $idPeg, $tampil,$year,$nomor) { if($tampil != "all"){ $str = " AND cutiStatus = '".$tampil."'"; }else{ $str = ""; } $str .= " AND cutiNo LIKE '%".$nomor."%'"; $str .= " AND YEAR(cutiMulai)=".$year; $result = $this->GetQueryKeren($this->mSqlQueries['get_data2'], array($idPeg, $str, $offset, $limit)); //print_r(stripslashes($result)); $result=$this->Open(stripslashes($result), array()); for ($i=0; $i<sizeof($result); $i++){ $result[$i]['durasi']=$this->GetDurasi($result[$i]['mulai'],$result[$i]['selesai']); } return $result; } function GetDataById($id) { $result = $this->Open($this->mSqlQueries['get_data_by_id'], array($id)); if($result) return $result[0]; else return $result; } function GetDataCutiDet($id) { $result = $this->Open($this->mSqlQueries['get_data_cuti_det'], array("%Y-%m-%d",$id)); $result[0]['durasi']=$this->GetDurasi($result[0]['tglmul'],$result[0]['tglsel']); return $result; } function GetComboTipe(){ $result = $this->Open($this->mSqlQueries['get_combo_tipe'], array()); return $result; } function CekNmrCuti($nmr){ $result = $this->Open($this->mSqlQueries['cek_nmr_cuti'], array($nmr)); return $result; } function GetTahunNo(){ $result = $this->Open($this->mSqlQueries['get_tahun_no'], array()); return $result; } function GetNoBaru($tahun){ $result = $this->Open($this->mSqlQueries['get_no_baru'], array($tahun)); return $result; } function GetLastId(){ $result = $this->Open($this->mSqlQueries['get_last_id'], array()); return $result; } function GetNumber($tipe){ $result = $this->Open($this->mSqlQueries['get_sql_generate_number'], array($tipe)); $result = $this->open($result['0']['formatNumberFormula'],array()); return $result['0']['number']; } //==DO== function Add($data) { $return = $this->Execute($this->mSqlQueries['do_add'], $data); //print_r($this->getLastError());exit; return $return; } function Update($data) { $return = $this->Execute($this->mSqlQueries['do_update'], $data); //print_r($this->getLastError());exit; return $return; } function Delete($id) { $result = $this->Execute($this->mSqlQueries['do_delete'], array($id)); //print_r($this->getLastError());exit; return $result; } function GetPeriodeCutiByPegId($pegId){ $result = $this->Open($this->mSqlQueries['get_periode_cuti_by_peg_id'], array($pegId)); return $result; } function UpdatePeriodeCutiDiambil($durasi,$durasi,$pegId,$perId) { $return = $this->Execute($this->mSqlQueries['do_update_periode_cuti_diambil'], array($durasi,$durasi,$pegId,$perId)); return $return; } function UpdatePeriodeCutiDiambilTambah($durasi,$durasi,$pegId,$perId) { $return = $this->Execute($this->mSqlQueries['do_update_periode_cuti_diambil_tambah_by_id'], array($durasi,$durasi,$pegId,$perId)); //echo vsprintf($this->mSqlQueries['do_update_periode_cuti_diambil_tambah_by_id'], array($durasi,$durasi,$pegId,$perId)).'<br/><br/>'; return $return; } function UpdatePeriodeCutiDiambilKurang($durasi,$durasi,$pegId,$perId) { $return = $this->Execute($this->mSqlQueries['do_update_periode_cuti_diambil_kurang_by_id'], array($durasi,$durasi,$pegId,$perId)); //echo vsprintf($this->mSqlQueries['do_update_periode_cuti_diambil_kurang_by_id'], array($durasi,$durasi,$pegId,$perId)).'<br/><br/>'; return $return; } function GetComboTahunCuti($id){ $result = $this->Open($this->mSqlQueries['get_combo_tahun_cuti'], array($id)); return $result; } function GetHariLibur() { $result = $this->Open($this->mSqlQueries['get_hari_libur'], array()); $hari_libur=""; for ($i=0; $i<sizeof($result); $i++){ $hari_libur .=";".$result[$i]['tanggal']; } return $hari_libur; } function GetDurasi($awal,$akhir) { $result = $this->Open($this->mSqlQueries['get_hari_libur'], array()); $durasi=0; $query_banding="SELECT IF(DATE('".$awal."')<=DATE('".$akhir."'),1,0) AS hari"; $banding = $this->Open($query_banding, array()); $banding=$banding[0]['hari']; while ($banding==1){ $query_cek_nama_hari="SELECT UPPER(DAYNAME(DATE('".$awal."'))) as hari"; $hari = $this->Open($query_cek_nama_hari, array()); $hari=$hari[0]['hari']; $libur=false; for ($i=0; $i<sizeof($result); $i++){ if (($result[$i]['tanggal']==$awal)) $libur=true; } if (($libur==false)&&($hari!='SUNDAY')&&($hari!='SATURDAY')) $durasi++; $i++; $query_next="SELECT ADDDATE(DATE('".$awal."'),1) AS hari"; $next = $this->Open($query_next, array()); $awal=$next[0]['hari']; $query_banding="SELECT IF(DATE('".$awal."')<=DATE('".$akhir."'),1,0) AS hari"; $banding = $this->Open($query_banding, array()); $banding=$banding[0]['hari']; if ($i>10) break; } return $durasi; } } ?>
4n6g4/gtsdm
malra/fo/module/data_cuti/business/cuti.class.php
PHP
gpl-3.0
7,599
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.worldpainter.layers; import java.util.Random; import org.pepsoft.worldpainter.layers.trees.Bush; import org.pepsoft.worldpainter.layers.trees.JungleTree; import org.pepsoft.worldpainter.layers.trees.OakTree; import org.pepsoft.worldpainter.layers.trees.TreeType; /** * * @author pepijn */ public class Jungle extends TreeLayer { private Jungle() { super("Jungle", "a jungle", 43); } @Override public TreeType pickTree(Random random) { int rnd = random.nextInt(20); if (rnd == 0) { return OAK_TREE; } else if (rnd < 10) { return JUNGLE_TREE; } else { return BUSH; } } public int getDefaultTreeChance() { return 640; } @Override public int getDefaultLayerStrengthCap() { return 9; } public static final Jungle INSTANCE = new Jungle(); private static final JungleTree JUNGLE_TREE = new JungleTree(); private static final OakTree OAK_TREE = new OakTree(); private static final Bush BUSH = new Bush(); private static final long serialVersionUID = 1L; }
frogocomics/WorldPainter
WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/Jungle.java
Java
gpl-3.0
1,265
#include "sketch/setsketch.h" #include "zlib.h" void usage(const char *s) { std::fprintf(stderr, "css2ss: Converts a Continuous SetSketch (CSetSketch) to a packed SetSketch.\nUsage: %s <opts>\n-a: set a [required].\n-b: set a [required]\n-B: Pack into bytes\n-N: Pack into nibbles\n-H: Pack into halves\n", s); std::exit(1); } int main(int argc, char **argv) { int c; double a = -1., b = -1.; int type = 'B'; while((c = getopt(argc, argv, "HBNh?a:b:")) >= 0) { switch(c) { case 'h': usage(*argv); return 1; case 'a': a = std::atof(optarg); break; case 'b': b = std::atof(optarg); break; case 'B': type = 'B'; break; case 'H': type = 'H'; break; case 'N': type = 'N'; break; } } if(a < 0 || b < 0) { std::fprintf(stderr, "a, b are mandatory.\n"); usage(*argv); } gzFile fp = gzdopen(STDIN_FILENO, "rb"); sketch::CSetSketch<double> cs(fp); gzclose(fp); if(type == 'B' || type == 'N') { size_t q = (type == 'N' ? size_t(14): size_t(254)); cs.to_setsketch<uint8_t>(a, b, q).write(stdout); } else if(type == 'H') { cs.to_setsketch<uint16_t>(a, b).write(stdout); } }
dnbaker/emp
bin/css2ss.cpp
C++
gpl-3.0
1,251
/** * Marlin 3D Printer Firmware * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * 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/>. * */ /* based on u8g_com_LPC1768_st7920_hw_spi.c Universal 8bit Graphics Library Copyright (c) 2011, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef TARGET_LPC1768 // #include <inttypes.h> // #include "src/core/macros.h" // #include "Configuration.h" #include <U8glib.h> #define SPI_FULL_SPEED 0 #define SPI_HALF_SPEED 1 #define SPI_QUARTER_SPEED 2 #define SPI_EIGHTH_SPEED 3 #define SPI_SIXTEENTH_SPEED 4 #define SPI_SPEED_5 5 #define SPI_SPEED_6 6 void spiBegin(); void spiInit(uint8_t spiRate); void spiSend(uint8_t b); void spiSend(const uint8_t* buf, size_t n); static uint8_t rs_last_state = 255; static void u8g_com_LPC1768_st7920_write_byte_hw_spi(uint8_t rs, uint8_t val) { uint8_t i; if ( rs != rs_last_state) { // time to send a command/data byte rs_last_state = rs; if ( rs == 0 ) /* command */ spiSend(0x0f8); else /* data */ spiSend(0x0fa); for( i = 0; i < 4; i++ ) // give the controller some time to process the data u8g_10MicroDelay(); // 2 is bad, 3 is OK, 4 is safe } spiSend(val & 0x0f0); spiSend(val << 4); } uint8_t u8g_com_HAL_LPC1768_ST7920_hw_spi_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { switch(msg) { case U8G_COM_MSG_INIT: u8g_SetPILevel(u8g, U8G_PI_CS, 0); u8g_SetPIOutput(u8g, U8G_PI_CS); u8g_Delay(5); spiBegin(); spiInit(SPI_EIGHTH_SPEED); // ST7920 max speed is about 1.1 MHz u8g->pin_list[U8G_PI_A0_STATE] = 0; /* inital RS state: command mode */ break; case U8G_COM_MSG_STOP: break; case U8G_COM_MSG_RESET: u8g_SetPILevel(u8g, U8G_PI_RESET, arg_val); break; case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */ u8g->pin_list[U8G_PI_A0_STATE] = arg_val; break; case U8G_COM_MSG_CHIP_SELECT: u8g_SetPILevel(u8g, U8G_PI_CS, arg_val); //note: the st7920 has an active high chip select break; case U8G_COM_MSG_WRITE_BYTE: u8g_com_LPC1768_st7920_write_byte_hw_spi(u8g->pin_list[U8G_PI_A0_STATE], arg_val); break; case U8G_COM_MSG_WRITE_SEQ: { uint8_t *ptr = (uint8_t*) arg_ptr; while( arg_val > 0 ) { u8g_com_LPC1768_st7920_write_byte_hw_spi(u8g->pin_list[U8G_PI_A0_STATE], *ptr++); arg_val--; } } break; case U8G_COM_MSG_WRITE_SEQ_P: { uint8_t *ptr = (uint8_t*) arg_ptr; while( arg_val > 0 ) { u8g_com_LPC1768_st7920_write_byte_hw_spi(u8g->pin_list[U8G_PI_A0_STATE], *ptr++); arg_val--; } } break; } return 1; } #endif // TARGET_LPC1768
MoonshineSG/Marlin
Marlin/src/HAL/HAL_LPC1768/u8g_com_HAL_LPC1768_st7920_hw_spi.cpp
C++
gpl-3.0
5,033
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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.neo4j.kernel.impl.core; import java.util.Arrays; import java.util.Map; import java.util.logging.Logger; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.TransactionManager; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.kernel.Config; import org.neo4j.kernel.impl.cache.AdaptiveCacheManager; import org.neo4j.kernel.impl.core.NodeManager.CacheType; import org.neo4j.kernel.impl.nioneo.store.PropertyIndexData; import org.neo4j.kernel.impl.nioneo.store.RelationshipTypeData; import org.neo4j.kernel.impl.persistence.EntityIdGenerator; import org.neo4j.kernel.impl.persistence.PersistenceManager; import org.neo4j.kernel.impl.transaction.LockManager; public class GraphDbModule { private static final CacheType DEFAULT_CACHE_TYPE = CacheType.soft; private static Logger log = Logger.getLogger( GraphDbModule.class.getName() ); private boolean startIsOk = true; private static final int INDEX_COUNT = 2500; private final GraphDatabaseService graphDbService; private final TransactionManager transactionManager; private final AdaptiveCacheManager cacheManager; private final LockManager lockManager; private final EntityIdGenerator idGenerator; private NodeManager nodeManager; private boolean readOnly = false; public GraphDbModule( GraphDatabaseService graphDb, AdaptiveCacheManager cacheManager, LockManager lockManager, TransactionManager transactionManager, EntityIdGenerator idGenerator, boolean readOnly ) { this.graphDbService = graphDb; this.cacheManager = cacheManager; this.lockManager = lockManager; this.transactionManager = transactionManager; this.idGenerator = idGenerator; this.readOnly = readOnly; } public void init() { } public void start( LockReleaser lockReleaser, PersistenceManager persistenceManager, RelationshipTypeCreator relTypeCreator, Map<Object,Object> params ) { if ( !startIsOk ) { return; } String cacheTypeName = (String) params.get( Config.CACHE_TYPE ); CacheType cacheType = null; try { cacheType = cacheTypeName != null ? CacheType.valueOf( cacheTypeName ) : DEFAULT_CACHE_TYPE; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( "Invalid cache type, please use one of: " + Arrays.asList( CacheType.values() ) + " or keep empty for default (" + DEFAULT_CACHE_TYPE + ")", e.getCause() ); } if ( !readOnly ) { nodeManager = new NodeManager( graphDbService, cacheManager, lockManager, lockReleaser, transactionManager, persistenceManager, idGenerator, relTypeCreator, cacheType ); } else { nodeManager = new ReadOnlyNodeManager( graphDbService, cacheManager, lockManager, lockReleaser, transactionManager, persistenceManager, idGenerator, cacheType ); } // load and verify from PS RelationshipTypeData relTypes[] = null; PropertyIndexData propertyIndexes[] = null; // beginTx(); relTypes = persistenceManager.loadAllRelationshipTypes(); propertyIndexes = persistenceManager.loadPropertyIndexes( INDEX_COUNT ); // commitTx(); nodeManager.addRawRelationshipTypes( relTypes ); nodeManager.addPropertyIndexes( propertyIndexes ); if ( propertyIndexes.length < INDEX_COUNT ) { nodeManager.setHasAllpropertyIndexes( true ); } nodeManager.start( params ); startIsOk = false; } private void beginTx() { try { transactionManager.begin(); } catch ( NotSupportedException e ) { throw new TransactionFailureException( "Unable to begin transaction.", e ); } catch ( SystemException e ) { throw new TransactionFailureException( "Unable to begin transaction.", e ); } } private void commitTx() { try { transactionManager.commit(); } catch ( SecurityException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( IllegalStateException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( RollbackException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( HeuristicMixedException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( HeuristicRollbackException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( SystemException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } } public void setReferenceNodeId( Long nodeId ) { nodeManager.setReferenceNodeId( nodeId.longValue() ); try { nodeManager.getReferenceNode(); } catch ( NotFoundException e ) { log.warning( "Reference node[" + nodeId + "] not valid." ); } } public Long getCurrentReferenceNodeId() { try { return nodeManager.getReferenceNode().getId(); } catch ( NotFoundException e ) { return -1L; } } public void createNewReferenceNode() { Node node = nodeManager.createNode(); nodeManager.setReferenceNodeId( node.getId() ); } public void reload( Map<Object,Object> params ) { throw new UnsupportedOperationException(); } public void stop() { nodeManager.clearPropertyIndexes(); nodeManager.clearCache(); nodeManager.stop(); } public void destroy() { } public NodeManager getNodeManager() { return this.nodeManager; } public Iterable<RelationshipType> getRelationshipTypes() { return nodeManager.getRelationshipTypes(); } }
kirilenkoo/neo4j-mobile-android
neo4j-android/kernel-src/org/neo4j/kernel/impl/core/GraphDbModule.java
Java
gpl-3.0
7,634
<?php class ModelPaymentPPPro extends Model { public function getMethod($country_id, $zone_id) { $this->load->language('payment/pp_pro'); if ($this->config->get('pp_pro_status')) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('pp_pro_geo_zone_id') . "' AND country_id = '" . (int)$country_id . "' AND (zone_id = '" . (int)$zone_id . "' OR zone_id = '0')"); if (!$this->config->get('pp_pro_geo_zone_id')) { $status = TRUE; } elseif ($query->num_rows) { $status = TRUE; } else { $status = FALSE; } } else { $status = FALSE; } $method_data = array(); if ($status) { $method_data = array( 'id' => 'pp_pro', 'title' => $this->language->get('text_title'), 'sort_order' => $this->config->get('pp_pro_sort_order') ); } return $method_data; } } ?>
chetan/opencart
upload/catalog/model/payment/pp_pro.php
PHP
gpl-3.0
989
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor 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. # # OpenShot Video Editor 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 OpenShot Video Editor. If not, see <http://www.gnu.org/licenses/>. # Import Blender's python API. This only works when the script is being # run from the context of Blender. Blender contains it's own version of Python # with this library pre-installed. import bpy # Load a font def load_font(font_path): """ Load a new TTF font into Blender, and return the font object """ # get the original list of fonts (before we add a new one) original_fonts = bpy.data.fonts.keys() # load new font bpy.ops.font.open(filepath=font_path) # get the new list of fonts (after we added a new one) for font_name in bpy.data.fonts.keys(): if font_name not in original_fonts: return bpy.data.fonts[font_name] # no new font was added return None # Debug Info: # ./blender -b test.blend -P demo.py # -b = background mode # -P = run a Python script within the context of the project file # Init all of the variables needed by this script. Because Blender executes # this script, OpenShot will inject a dictionary of the required parameters # before this script is executed. params = { 'title' : 'Oh Yeah! OpenShot!', 'extrude' : 0.1, 'bevel_depth' : 0.02, 'spacemode' : 'CENTER', 'text_size' : 1.5, 'width' : 1.0, 'fontname' : 'Bfont', 'color' : [0.8,0.8,0.8], 'alpha' : 1.0, 'alpha_mode' : 'TRANSPARENT', 'output_path' : '/tmp/', 'fps' : 24, 'quality' : 90, 'file_format' : 'PNG', 'color_mode' : 'RGBA', 'horizon_color' : [0.57, 0.57, 0.57], 'resolution_x' : 1920, 'resolution_y' : 1080, 'resolution_percentage' : 100, 'start_frame' : 20, 'end_frame' : 25, 'animation' : True, } #INJECT_PARAMS_HERE # The remainder of this script will modify the current Blender .blend project # file, and adjust the settings. The .blend file is specified in the XML file # that defines this template in OpenShot. #---------------------------------------------------------------------------- # Modify Text / Curve settings #print (bpy.data.curves.keys()) text_object = bpy.data.curves["Title"] text_object.extrude = params["extrude"] text_object.bevel_depth = params["bevel_depth"] text_object.body = params["title"] text_object.align = params["spacemode"] text_object.size = params["text_size"] text_object.space_character = params["width"] # Get font object font = None if params["fontname"] != "Bfont": # Add font so it's available to Blender font = load_font(params["fontname"]) else: # Get default font font = bpy.data.fonts["Bfont"] text_object.font = font text_object = bpy.data.curves["Subtitle"] text_object.extrude = params["extrude"] text_object.bevel_depth = params["bevel_depth"] text_object.body = params["sub_title"] text_object.align = params["spacemode"] text_object.size = params["text_size"] text_object.space_character = params["width"] # set the font text_object.font = font # Change the material settings (color, alpha, etc...) material_object = bpy.data.materials["Text"] material_object.diffuse_color = params["diffuse_color"] material_object.specular_color = params["specular_color"] material_object.specular_intensity = params["specular_intensity"] material_object.alpha = params["alpha"] # Set the render options. It is important that these are set # to the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = params["output_path"] bpy.context.scene.render.fps = params["fps"] #bpy.context.scene.render.quality = params["quality"] try: bpy.context.scene.render.file_format = params["file_format"] bpy.context.scene.render.color_mode = params["color_mode"] except: bpy.context.scene.render.image_settings.file_format = params["file_format"] bpy.context.scene.render.image_settings.color_mode = params["color_mode"] try: bpy.context.scene.render.alpha_mode = params["alpha_mode"] except: pass bpy.data.worlds[0].horizon_color = params["horizon_color"] bpy.context.scene.render.resolution_x = params["resolution_x"] bpy.context.scene.render.resolution_y = params["resolution_y"] bpy.context.scene.render.resolution_percentage = params["resolution_percentage"] bpy.context.scene.frame_start = params["start_frame"] bpy.context.scene.frame_end = params["end_frame"] # Animation Speed (use Blender's time remapping to slow or speed up animation) animation_speed = int(params["animation_speed"]) # time remapping multiplier new_length = int(params["end_frame"]) * animation_speed # new length (in frames) bpy.context.scene.frame_end = new_length bpy.context.scene.render.frame_map_old = 1 bpy.context.scene.render.frame_map_new = animation_speed if params["start_frame"] == params["end_frame"]: bpy.context.scene.frame_start = params["end_frame"] bpy.context.scene.frame_end = params["end_frame"] # Render the current animation to the params["output_path"] folder bpy.ops.render.render(animation=params["animation"])
XXLRay/libreshot
libreshot/blender/scripts/blinds.py
Python
gpl-3.0
5,718
/***************************************************************************** * 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. *****************************************************************************/ #if defined(__MINGW32__) && !defined(WINVER) && !defined(_WIN32_WINNT) // 0x0600 == vista # define WINVER 0x0600 # define _WIN32_WINNT 0x0600 #endif // __MINGW32__ #ifdef _WIN32 // Windows.h needs to be included first // clang-format off # include <windows.h> # include <shellapi.h> // clang-format on // Then the rest # include "../OpenRCT2.h" # include "../Version.h" # include "../config/Config.h" # include "../core/String.hpp" # include "../localisation/Date.h" # include "../localisation/Language.h" # include "../rct2/RCT2.h" # include "../util/Util.h" # include "Platform2.h" # include "platform.h" # include <algorithm> # include <array> # include <iterator> # include <lmcons.h> # include <memory> # include <psapi.h> # include <shlobj.h> # include <sys/stat.h> // Native resource IDs # include "../../../resources/resource.h" // Enable visual styles # pragma comment( \ linker, \ "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") // The name of the mutex used to prevent multiple instances of the game from running # define SINGLE_INSTANCE_MUTEX_NAME "RollerCoaster Tycoon 2_GSKMUTEX" # define OPENRCT2_DLL_MODULE_NAME "openrct2.dll" # if _WIN32_WINNT < 0x600 # define swprintf_s(a, b, c, d, ...) swprintf(a, b, c, ##__VA_ARGS__) # endif bool platform_directory_exists(const utf8* path) { auto wPath = String::ToWideChar(path); DWORD dwAttrib = GetFileAttributesW(wPath.c_str()); return dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY); } bool platform_original_game_data_exists(const utf8* path) { utf8 checkPath[MAX_PATH]; safe_strcpy(checkPath, path, MAX_PATH); safe_strcat_path(checkPath, "Data", MAX_PATH); safe_strcat_path(checkPath, "g1.dat", MAX_PATH); return Platform::FileExists(checkPath); } bool platform_ensure_directory_exists(const utf8* path) { if (platform_directory_exists(path)) return 1; auto wPath = String::ToWideChar(path); auto success = CreateDirectoryW(wPath.c_str(), nullptr); return success != FALSE; } bool platform_directory_delete(const utf8* path) { // Needs to be double-null terminated as pFrom is a null terminated array of strings auto wPath = String::ToWideChar(path) + L"\0"; SHFILEOPSTRUCTW fileop; fileop.hwnd = nullptr; // no status display fileop.wFunc = FO_DELETE; // delete operation fileop.pFrom = wPath.c_str(); // source file name as double null terminated string fileop.pTo = nullptr; // no destination needed fileop.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; // do not prompt the user fileop.fAnyOperationsAborted = FALSE; fileop.lpszProgressTitle = nullptr; fileop.hNameMappings = nullptr; int32_t ret = SHFileOperationW(&fileop); return (ret == 0); } bool platform_lock_single_instance() { HANDLE mutex, status; // Check if operating system mutex exists mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, SINGLE_INSTANCE_MUTEX_NAME); if (mutex == nullptr) { // Create new mutex status = CreateMutex(nullptr, FALSE, SINGLE_INSTANCE_MUTEX_NAME); if (status == nullptr) log_error("unable to create mutex"); return true; } // Already running CloseHandle(mutex); return false; } int32_t platform_get_drives() { return GetLogicalDrives(); } bool platform_file_copy(const utf8* srcPath, const utf8* dstPath, bool overwrite) { auto wSrcPath = String::ToWideChar(srcPath); auto wDstPath = String::ToWideChar(dstPath); auto success = CopyFileW(wSrcPath.c_str(), wDstPath.c_str(), overwrite ? FALSE : TRUE); return success != FALSE; } bool platform_file_move(const utf8* srcPath, const utf8* dstPath) { auto wSrcPath = String::ToWideChar(srcPath); auto wDstPath = String::ToWideChar(dstPath); auto success = MoveFileW(wSrcPath.c_str(), wDstPath.c_str()); return success != FALSE; } bool platform_file_delete(const utf8* path) { auto wPath = String::ToWideChar(path); auto success = DeleteFileW(wPath.c_str()); return success != FALSE; } bool platform_get_steam_path(utf8* outPath, size_t outSize) { wchar_t* wSteamPath; HKEY hKey; DWORD type, size; LRESULT result; if (RegOpenKeyW(HKEY_CURRENT_USER, L"Software\\Valve\\Steam", &hKey) != ERROR_SUCCESS) return false; // Get the size of the path first if (RegQueryValueExW(hKey, L"SteamPath", nullptr, &type, nullptr, &size) != ERROR_SUCCESS) { RegCloseKey(hKey); return false; } wSteamPath = reinterpret_cast<wchar_t*>(malloc(size)); result = RegQueryValueExW(hKey, L"SteamPath", nullptr, &type, reinterpret_cast<LPBYTE>(wSteamPath), &size); if (result == ERROR_SUCCESS) { auto utf8SteamPath = String::ToUtf8(wSteamPath); safe_strcpy(outPath, utf8SteamPath.c_str(), outSize); safe_strcat_path(outPath, "steamapps\\common", outSize); } free(wSteamPath); RegCloseKey(hKey); return result == ERROR_SUCCESS; } std::string platform_get_rct1_steam_dir() { return "Rollercoaster Tycoon Deluxe"; } std::string platform_get_rct2_steam_dir() { return "Rollercoaster Tycoon 2"; } std::string platform_sanitise_filename(const std::string& path) { static constexpr std::array prohibited = { '<', '>', '*', '\\', ':', '|', '?', '"', '/' }; auto sanitised = path; std::replace_if( sanitised.begin(), sanitised.end(), [](const std::string::value_type& ch) -> bool { return std::find(prohibited.begin(), prohibited.end(), ch) != prohibited.end(); }, '_'); sanitised = String::Trim(sanitised); return sanitised; } uint16_t platform_get_locale_language() { CHAR langCode[4]; if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME, reinterpret_cast<LPSTR>(&langCode), sizeof(langCode)) == 0) { return LANGUAGE_UNDEFINED; } if (strcmp(langCode, "ENG") == 0) { return LANGUAGE_ENGLISH_UK; } if (strcmp(langCode, "ENU") == 0) { return LANGUAGE_ENGLISH_US; } if (strcmp(langCode, "DEU") == 0) { return LANGUAGE_GERMAN; } if (strcmp(langCode, "NLD") == 0) { return LANGUAGE_DUTCH; } if (strcmp(langCode, "FRA") == 0) { return LANGUAGE_FRENCH; } if (strcmp(langCode, "HUN") == 0) { return LANGUAGE_HUNGARIAN; } if (strcmp(langCode, "PLK") == 0) { return LANGUAGE_POLISH; } if (strcmp(langCode, "ESP") == 0) { return LANGUAGE_SPANISH; } if (strcmp(langCode, "SVE") == 0) { return LANGUAGE_SWEDISH; } if (strcmp(langCode, "ITA") == 0) { return LANGUAGE_ITALIAN; } if (strcmp(langCode, "POR") == 0) { return LANGUAGE_PORTUGUESE_BR; } if (strcmp(langCode, "FIN") == 0) { return LANGUAGE_FINNISH; } if (strcmp(langCode, "NOR") == 0) { return LANGUAGE_NORWEGIAN; } if (strcmp(langCode, "DAN") == 0) { return LANGUAGE_DANISH; } return LANGUAGE_UNDEFINED; } time_t platform_file_get_modified_time(const utf8* path) { WIN32_FILE_ATTRIBUTE_DATA data{}; auto wPath = String::ToWideChar(path); auto result = GetFileAttributesExW(wPath.c_str(), GetFileExInfoStandard, &data); if (result != FALSE) { FILETIME localFileTime{}; result = FileTimeToLocalFileTime(&data.ftLastWriteTime, &localFileTime); if (result != FALSE) { ULARGE_INTEGER ull{}; ull.LowPart = localFileTime.dwLowDateTime; ull.HighPart = localFileTime.dwHighDateTime; return ull.QuadPart / 10000000ULL - 11644473600ULL; } } return 0; } CurrencyType platform_get_locale_currency() { CHAR currCode[4]; if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SINTLSYMBOL, reinterpret_cast<LPSTR>(&currCode), sizeof(currCode)) == 0) { return platform_get_currency_value(nullptr); } return platform_get_currency_value(currCode); } MeasurementFormat platform_get_locale_measurement_format() { UINT measurement_system; if (GetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_IMEASURE | LOCALE_RETURN_NUMBER, reinterpret_cast<LPSTR>(&measurement_system), sizeof(measurement_system)) == 0) { return MeasurementFormat::Metric; } switch (measurement_system) { case 1: return MeasurementFormat::Imperial; case 0: default: return MeasurementFormat::Metric; } } TemperatureUnit platform_get_locale_temperature_format() { UINT fahrenheit; // GetLocaleInfo will set fahrenheit to 1 if the locale on this computer // uses the United States measurement system or 0 otherwise. if (GetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_IMEASURE | LOCALE_RETURN_NUMBER, reinterpret_cast<LPSTR>(&fahrenheit), sizeof(fahrenheit)) == 0) { // Assume celsius by default if function call fails return TemperatureUnit::Celsius; } if (fahrenheit) return TemperatureUnit::Fahrenheit; return TemperatureUnit::Celsius; } uint8_t platform_get_locale_date_format() { # if _WIN32_WINNT >= 0x0600 // Retrieve short date format, eg "MM/dd/yyyy" wchar_t dateFormat[20]; if (GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SSHORTDATE, dateFormat, static_cast<int>(std::size(dateFormat))) == 0) { return DATE_FORMAT_DAY_MONTH_YEAR; } // The only valid characters for format types are: dgyM // We try to find 3 strings of format types, ignore any characters in between. // We also ignore 'g', as it represents 'era' and we don't have that concept // in our date formats. // https://msdn.microsoft.com/en-us/library/windows/desktop/dd317787(v=vs.85).aspx // wchar_t first[sizeof(dateFormat)]; wchar_t second[sizeof(dateFormat)]; if (swscanf_s( dateFormat, L"%l[dyM]%*l[^dyM]%l[dyM]%*l[^dyM]%*l[dyM]", first, static_cast<uint32_t>(std::size(first)), second, static_cast<uint32_t>(std::size(second))) != 2) { return DATE_FORMAT_DAY_MONTH_YEAR; } if (wcsncmp(L"d", first, 1) == 0) { return DATE_FORMAT_DAY_MONTH_YEAR; } if (wcsncmp(L"M", first, 1) == 0) { return DATE_FORMAT_MONTH_DAY_YEAR; } if (wcsncmp(L"y", first, 1) == 0) { if (wcsncmp(L"d", second, 1) == 0) { return DATE_FORMAT_YEAR_DAY_MONTH; } // Closest possible option return DATE_FORMAT_YEAR_MONTH_DAY; } # endif // Default fallback return DATE_FORMAT_DAY_MONTH_YEAR; } # ifndef NO_TTF bool platform_get_font_path(TTFFontDescriptor* font, utf8* buffer, size_t size) { # if !defined(__MINGW32__) \ && ((NTDDI_VERSION >= NTDDI_VISTA) && !defined(_USING_V110_SDK71_) && !defined(_ATL_XP_TARGETING)) wchar_t* fontFolder; if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Fonts, 0, nullptr, &fontFolder))) { // Convert wchar to utf8, then copy the font folder path to the buffer. auto outPathTemp = String::ToUtf8(fontFolder); safe_strcpy(buffer, outPathTemp.c_str(), size); CoTaskMemFree(fontFolder); // Append the requested font's file name. safe_strcat_path(buffer, font->filename, size); return true; } return false; # else log_warning("Compatibility hack: falling back to C:\\Windows\\Fonts"); safe_strcpy(buffer, "C:\\Windows\\Fonts\\", size); safe_strcat_path(buffer, font->filename, size); return true; # endif } # endif // NO_TTF std::string platform_get_absolute_path(const utf8* relativePath, const utf8* basePath) { std::string result; if (relativePath != nullptr) { std::string pathToResolve; if (basePath == nullptr) { pathToResolve = std::string(relativePath); } else { pathToResolve = std::string(basePath) + std::string("\\") + relativePath; } auto pathToResolveW = String::ToWideChar(pathToResolve); wchar_t fullPathW[MAX_PATH]{}; auto fullPathLen = GetFullPathNameW( pathToResolveW.c_str(), static_cast<DWORD>(std::size(fullPathW)), fullPathW, nullptr); if (fullPathLen != 0) { result = String::ToUtf8(fullPathW); } } return result; } datetime64 platform_get_datetime_now_utc() { // Get file time FILETIME fileTime; GetSystemTimeAsFileTime(&fileTime); uint64_t fileTime64 = (static_cast<uint64_t>(fileTime.dwHighDateTime) << 32ULL) | (static_cast<uint64_t>(fileTime.dwLowDateTime)); // File time starts from: 1601-01-01T00:00:00Z // Convert to start from: 0001-01-01T00:00:00Z datetime64 utcNow = fileTime64 - 504911232000000000ULL; return utcNow; } std::string platform_get_username() { std::string result; wchar_t usernameW[UNLEN + 1]{}; DWORD usernameLength = UNLEN + 1; if (GetUserNameW(usernameW, &usernameLength)) { result = String::ToUtf8(usernameW); } return result; } bool platform_process_is_elevated() { BOOL isElevated = FALSE; HANDLE hToken = nullptr; if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { TOKEN_ELEVATION Elevation; DWORD tokenSize = sizeof(TOKEN_ELEVATION); if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &tokenSize)) { isElevated = Elevation.TokenIsElevated; } } if (hToken) { CloseHandle(hToken); } return isElevated; } /////////////////////////////////////////////////////////////////////////////// // URI protocol association setup /////////////////////////////////////////////////////////////////////////////// # define SOFTWARE_CLASSES L"Software\\Classes" # define MUI_CACHE L"Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache" bool platform_setup_uri_protocol() { # if _WIN32_WINNT >= 0x0600 log_verbose("Setting up URI protocol..."); // [HKEY_CURRENT_USER\Software\Classes] HKEY hRootKey; if (RegOpenKeyW(HKEY_CURRENT_USER, SOFTWARE_CLASSES, &hRootKey) == ERROR_SUCCESS) { // [hRootKey\openrct2] HKEY hClassKey; if (RegCreateKeyA(hRootKey, "openrct2", &hClassKey) == ERROR_SUCCESS) { if (RegSetValueA(hClassKey, nullptr, REG_SZ, "URL:openrct2", 0) == ERROR_SUCCESS) { if (RegSetKeyValueA(hClassKey, nullptr, "URL Protocol", REG_SZ, "", 0) == ERROR_SUCCESS) { // [hRootKey\openrct2\shell\open\command] wchar_t exePath[MAX_PATH]; GetModuleFileNameW(nullptr, exePath, MAX_PATH); wchar_t buffer[512]; swprintf_s(buffer, std::size(buffer), L"\"%s\" handle-uri \"%%1\"", exePath); if (RegSetValueW(hClassKey, L"shell\\open\\command", REG_SZ, buffer, 0) == ERROR_SUCCESS) { // Not compulsory, but gives the application a nicer name // [HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache] HKEY hMuiCacheKey; if (RegCreateKeyW(hRootKey, MUI_CACHE, &hMuiCacheKey) == ERROR_SUCCESS) { swprintf_s(buffer, std::size(buffer), L"%s.FriendlyAppName", exePath); // mingw-w64 used to define RegSetKeyValueW's signature incorrectly // You need at least mingw-w64 5.0 including this commit: // https://sourceforge.net/p/mingw-w64/mingw-w64/ci/da9341980a4b70be3563ac09b5927539e7da21f7/ RegSetKeyValueW(hMuiCacheKey, nullptr, buffer, REG_SZ, L"OpenRCT2", sizeof(L"OpenRCT2")); } log_verbose("URI protocol setup successful"); return true; } } } } } # endif log_verbose("URI protocol setup failed"); return false; } /////////////////////////////////////////////////////////////////////////////// #endif
Gymnasiast/OpenRCT2
src/openrct2/platform/Windows.cpp
C++
gpl-3.0
17,541
import { Fail, Ok, Result } from "./Result"; export function inlineEscaped(str : string) : Result<string, string> { let result = "" for (let i = 0; i < str.length; ++i) { const ch = str[i]; if (ch == "\\") { if (i + 1 === str.length) { return new Fail("Extra backslash"); } result += str[i + 1]; ++i; } else { result += ch; } } return new Ok(result); } export function escapedSplit (string : string) : Result<string[], string> { const result : string[] = [] for (const part of string.split(/(?<!\\)\*/)) { const inlined = inlineEscaped(part); if (inlined.isOk) { result.push(inlined.ok); } else { return new Fail(inlined.fail); } } return new Ok(result); } export function stripComments(line : string) : Result<string, string> { const parts = line.split(" "); if (parts[0].startsWith("#")) { return new Ok(""); } else if (parts.length > 1 && !parts[1].startsWith("#")) { return new Fail("Comments should start with #"); } else { return new Ok(parts[0]); } } export function glob(parts : string[], haystack : string) { const first = parts[0]; const last = parts[parts.length - 1]; if (!haystack.startsWith(first)) { return false; } let index = first.length; for (let i = 1; i < parts.length; ++i) { const part = parts[i]; index = haystack.indexOf(part, index); if (index === -1) { return false; } index += part.length; } return index === haystack.length || last === ""; } export function parseGlob(line: string) : Result<(str: string) => boolean, string> { return stripComments(line) .bind(escapedSplit) .bind(parts => { if (parts.length === 0) { return new Fail("Empty pattern."); } else if (parts.reduce((sum, str) => sum + str.length, 0) <= 3) { return new Fail("Pattern is too short: " + parts); } else { return new Ok(haystack => glob(parts, haystack)); } }); } export function* enumerate<T>(enumerator: Iterable<T>) : Iterable<[number, T]> { let i = 0; for (const element of enumerator) { yield [i, element]; ++i; } } export function parseGlobs(lines : string[]) { const parsers : ((str: string) => boolean)[] = []; const errors : string[] = []; for (const [lineIndex, line] of enumerate(lines)) { const trimmed = line.trim(); if (trimmed !== "" && !trimmed.startsWith("#")) { parseGlob(trimmed).match( parser => parsers.push(parser), error => errors.push(`Line ${lineIndex + 1}: ${error}`)); } } return { parsers, errors } } export function groupBy<T, V>(items : Iterable<T>, func : (value: T) => V) { const groups = new Map<V, T[]>(); for (const item of items) { const id = func(item); let group = groups.get(id); if (!group) { group = []; groups.set(id, group); } group.push(item); } return groups; } const prefixes = [ "https://www.", "http://www.", "https://", "http://", ] export function removeProtocol(url : string) { const prefix = prefixes.find(prefix => url.startsWith(prefix)); if (prefix !== undefined) { return url.substr(prefix.length); } return url; } export function removeDomain(url : string) { const protocolIndex = url.indexOf("//"); if (protocolIndex < 0) { return url; } const domainIndex = url.indexOf("/", protocolIndex + 2); return url.substring(domainIndex + 1); } // css shortcuts export function px(input : number) { return Math.round(input) + "px"; } export function url(input : string) { return " url('" + input + "') "; } // converts to string, checks if supplied string is a valid URL // 1. String isURL(Mixed text) export function isURL(text : string) { return text.indexOf("://") > 0 && text.indexOf(" ") < 0; } // converts to string, If supplied string is an URL, returns trimmed version of it, else returns supplied string // 1. String trimURL(Mixed text) export function trimURL(text : string) { text += ''; if (!isURL(text)) return text; // trim query strings ?q=...xxx var queryStart = text.indexOf("?"); var queryEnd = text.indexOf("=", queryStart); if (queryStart > 0 && queryEnd > 0) text = text.substr(0, queryEnd + 1) + "..."; // trim slashes var split = text.split("/"); if (split.length > 5) { split.splice(4, split.length - 5, "..."); text = split.join("/"); } return text; } // convert supplied time to human-readable time format relative to current date // relativeTime(Number timeInMilliseconds) export function relativeTime(value : number) { var diff = ( Date.now() - value ) / 1000; if (diff < 60) { return "<1m"; } else if (diff < 3600) { return Math.round(diff / 60) + "m"; } else if (diff < 3600 * 24) { return Math.round(diff / 3600) + "h"; } else if (diff < 3600 * 24 * 365) { return Math.round(diff / 3600 / 24) + "d"; } else { return Math.round(diff / 3600 / 24 / 365) + "y"; } } interface Template { nodeName : string className? : string events? : { click? : ((e: MouseEvent) => void) mousedown? : ((e: MouseEvent) => void) mouseup? : ((e: MouseEvent) => void) }, childNodes? : Node[] type? : string disabled? : boolean width? : number height? : number } export function $(params : Template | string) : HTMLElement | Node { if (typeof(params) == "string") return document.createTextNode(params); const element = document.createElement(params.nodeName); if (params.events) { if (params.events.click) { element.addEventListener("click", params.events.click); } if (params.events.mousedown) { element.addEventListener("mousedown", params.events.mousedown); } if (params.events.mouseup) { element.addEventListener("mouseup", params.events.mouseup); } } if (params.childNodes) { params.childNodes.forEach(element.appendChild.bind(element)); } if (params.className) { element.className = params.className } if (params.type) { (element as HTMLInputElement).type = params.type } if (params.disabled !== undefined) { (element as HTMLInputElement).disabled = params.disabled } if (params.width) { const canvas = element as HTMLCanvasElement canvas.width = params.width canvas.height = params.height } return element; } const MouseButton = Object.freeze({ Left : 0, Middle : 1, }) export function isInBackground(e : MouseEvent | KeyboardEvent) { return (e as MouseEvent).button === MouseButton.Middle || ((e as MouseEvent).button === MouseButton.Left || (e as KeyboardEvent).key === "Enter") && e.metaKey || e.ctrlKey || e.shiftKey; } export default { $, px, url, isURL, trimURL, relativeTime, }
LAJW/wrona-history
source/Utils.ts
TypeScript
gpl-3.0
6,467
<?php // Opencart v1.4.9.3 Lithuanian transliation. UTF-8 // Opencart v1.3.2 Lithuanian by Saulius Varskevicius, varske@takas.lt // Opencart v1.4.0 Lithuanian by Rimvydas Zubkus, rimasz@kava.lt // Opencart v1.4.8b Lithuanian by Andrejus Zlotnikovas, andrejuszl@gmail.com // Opencart v1.4.9.1 Lithuanian by Rimvydas Zubkus, rimasz@kava.lt // Opencart v1.4.9.3 Lithuanian by Andrejus Zlotnikovas, andrejuszl@gmail.com // Opencart v1.5.0 Lithuanian by Marius Radvilavicius radvis@gmail.com // Heading $_['heading_title'] = 'Naujienlaiškio prenumerata'; // Text $_['text_account'] = 'Paskyra'; $_['text_newsletter'] = 'Naujienlaiškis'; $_['text_success'] = 'Pavyko: Jūsų naujienlaiškio prenumerata sėkmingai atnaujinta!'; // Entry $_['entry_newsletter'] = 'Užsakyti:'; ?>
censam/open_cart
multilanguage/OC-Europa-1-5-1-3-9.part01/upload/catalog/language/lithuanian/account/newsletter.php
PHP
gpl-3.0
791
/* * yeast.cpp is part of Brewtarget, and is Copyright the following * authors 2009-2014 * - marker5a * - Philip Greggory Lee <rocketman768@gmail.com> * - plut0nium * - Samuel Östling <MrOstling@gmail.com> * * Brewtarget 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. * * Brewtarget 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 <QDomNode> #include <QDomElement> #include <QDomText> #include <QObject> #include "yeast.h" #include "brewtarget.h" QStringList Yeast::types = QStringList() << "Ale" << "Lager" << "Wheat" << "Wine" << "Champagne"; QStringList Yeast::forms = QStringList() << "Liquid" << "Dry" << "Slant" << "Culture"; QStringList Yeast::flocculations = QStringList() << "Low" << "Medium" << "High" << "Very High"; QHash<QString,QString> Yeast::tagToProp = Yeast::tagToPropHash(); QHash<QString,QString> Yeast::tagToPropHash() { QHash<QString,QString> propHash; propHash["NAME"] = "name"; //propHash["TYPE"] = "type"; //propHash["FORM"] = "form"; propHash["AMOUNT"] = "amount"; propHash["INVENTORY"] = "inventory"; propHash["AMOUNT_IS_WEIGHT"] = "amountIsWeight"; propHash["LABORATORY"] = "laboratory"; propHash["PRODUCT_ID"] = "productID"; propHash["MIN_TEMPERATURE"] = "minTemperature_c"; propHash["MAX_TEMPERATURE"] = "maxTemperature_c"; //propHash["FLOCCULATION"] = "flocculation"; propHash["ATTENUATION"] = "attenuation_pct"; propHash["NOTES"] = "notes"; propHash["BEST_FOR"] = "bestFor"; propHash["TIMES_CULTURED"] = "timesCultured"; propHash["MAX_REUSE"] = "maxReuse"; propHash["ADD_TO_SECONDARY"] = "addToSecondary"; return propHash; } bool operator<(Yeast &y1, Yeast &y2) { return y1.name() < y2.name(); } bool operator==(Yeast &y1, Yeast &y2) { return y1.name() == y2.name(); } //============================CONSTRUCTORS====================================== Yeast::Yeast() : BeerXMLElement() { } Yeast::Yeast(Yeast const& other) : BeerXMLElement(other) { } //============================="GET" METHODS==================================== QString Yeast::laboratory() const { return get("laboratory").toString();; } QString Yeast::productID() const { return get("product_id").toString(); } QString Yeast::notes() const { return get("notes").toString(); } QString Yeast::bestFor() const { return get("best_for").toString(); } const QString Yeast::typeString() const { return types.at(type()); } const QString Yeast::formString() const { return forms.at(form()); } const QString Yeast::flocculationString() const { return flocculations.at(flocculation()); } double Yeast::amount() const { return get("amount").toDouble(); } double Yeast::minTemperature_c() const { return get("min_temperature").toDouble(); } double Yeast::maxTemperature_c() const { return get("max_temperature").toDouble(); } double Yeast::attenuation_pct() const { return get("attenuation").toDouble(); } int Yeast::inventory() const { return getInventory("quanta").toInt(); } int Yeast::timesCultured() const { return get("times_cultured").toInt(); } int Yeast::maxReuse() const { return get("max_reuse").toInt(); } bool Yeast::addToSecondary() const { return get("add_to_secondary").toBool(); } bool Yeast::amountIsWeight() const { return get("amount_is_weight").toBool(); } Yeast::Form Yeast::form() const { return static_cast<Yeast::Form>( forms.indexOf(get("form").toString())); } Yeast::Flocculation Yeast::flocculation() const { return static_cast<Yeast::Flocculation>( flocculations.indexOf(get("flocculation").toString())); } Yeast::Type Yeast::type() const { return static_cast<Yeast::Type>( types.indexOf(get("ytype").toString())); } const QString Yeast::typeStringTr() const { static QStringList typesTr = QStringList() << QObject::tr("Ale") << QObject::tr("Lager") << QObject::tr("Wheat") << QObject::tr("Wine") << QObject::tr("Champagne"); return typesTr.at(type()); } const QString Yeast::formStringTr() const { static QStringList formsTr = QStringList() << QObject::tr("Liquid") << QObject::tr("Dry") << QObject::tr("Slant") << QObject::tr("Culture"); return formsTr.at(form()); } const QString Yeast::flocculationStringTr() const { static QStringList flocculationsTr = QStringList() << QObject::tr("Low") << QObject::tr("Medium") << QObject::tr("High") << QObject::tr("Very High"); return flocculationsTr.at(flocculation()); } //============================="SET" METHODS==================================== void Yeast::setType( Yeast::Type t ) { set("type", "ytype", types.at(t)); } void Yeast::setForm( Yeast::Form f ) { set("form", "form", forms.at(f)); } void Yeast::setAmount( double var ) { if( var < 0.0 ) Brewtarget::logW( QString("Yeast: amount < 0: %1").arg(var) ); else set("amount", "amount", var); } void Yeast::setInventoryQuanta( int var ) { if( var < 0.0 ) Brewtarget::logW( QString("Yeast: inventory < 0: %1").arg(var) ); else setInventory("inventory", "quanta", var); } void Yeast::setAmountIsWeight( bool var ) { set("amountIsWeight", "amount_is_weight", var); } void Yeast::setLaboratory( const QString& var ) { set("laboratory", "laboratory", var); } void Yeast::setProductID( const QString& var ) { set("productID", "product_id", var); } void Yeast::setMinTemperature_c( double var ) { if( var < -273.15 ) return; else set("minTemperature_c", "min_temperature", var); } void Yeast::setMaxTemperature_c( double var ) { if( var < -273.15 ) return; else set("maxTemperature_c", "max_temperature", var); } void Yeast::setFlocculation( Yeast::Flocculation f ) { set("flocculation", "flocculation", flocculations.at(f)); } void Yeast::setAttenuation_pct( double var ) { if( var < 0.0 || var > 100.0 ) return; else set("attenuation", "attenuation", var); } void Yeast::setNotes( const QString& var ) { set("notes", "notes", var); } void Yeast::setBestFor( const QString& var ) { set("bestFor", "best_for", var); } void Yeast::setTimesCultured( int var ) { if( var < 0 ) return; else set("timesCultured", "times_cultured", var); } void Yeast::setMaxReuse( int var ) { if( var < 0 ) return; else set("maxReuse", "max_reuse", var); } void Yeast::setAddToSecondary( bool var ) { set("addToSecondary", "add_to_secondary", var); } //========================OTHER METHODS========================================= bool Yeast::isValidType(const QString& str) const { static const QString types[] = {"Ale", "Lager", "Wheat", "Wine", "Champagne"}; unsigned int i, size = 5; for( i = 0; i < size; ++i ) if( str == types[i] ) return true; return false; } bool Yeast::isValidForm(const QString& str) const { static const QString forms[] = {"Liquid", "Dry", "Slant", "Culture"}; unsigned int i, size=4; for( i = 0; i < size; ++i ) if( str == forms[i] ) return true; return false; } bool Yeast::isValidFlocculation(const QString& str) const { static const QString floc[] = {"Low", "Medium", "High", "Very High"}; unsigned int i, size=4; for( i = 0; i < size; ++i ) if( str == floc[i] ) return true; return false; }
theophae/brewtarget
src/yeast.cpp
C++
gpl-3.0
8,150
""" Python script "setup.py" by Matthew Garcia, PhD student Dept. of Forest and Wildlife Ecology University of Wisconsin - Madison matt.e.garcia@gmail.com Copyright (C) 2015-2016 by Matthew Garcia Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms Send questions, bug reports, any related requests to matt.e.garcia@gmail.com See also 'README.md', 'DISCLAIMER.txt', 'CITATION.txt', 'ACKNOWLEDGEMENTS.txt' Treat others as you would be treated. Pay it forward. Valar dohaeris. PURPOSE: Verifies sample data, scripts, modules, documents, auxiliary files. Verifies availability of python dependencies used by various scripts. Uncompresses certain large example data files Builds directory structure for script output products. DEPENDENCIES: all software package source dependencies are polled here USAGE: '$ python setup.py' """ import os import sys import glob def message(char_string): """ prints a string to the terminal and flushes the buffer """ print char_string sys.stdout.flush() return txt_files = ['ACKNOWLEDGEMENTS.txt', 'CITATION.txt', 'DISCLAIMER.txt', 'LICENSE_GnuGPLv3.txt'] md_files = ['README.md'] main_dirs = ['data', 'docs', 'htcondor', 'source', 'tools'] # scripts = ['process_NCEI_00.py', 'process_NCEI_01.py', 'process_NCEI_02a.py', 'process_NCEI_02b.py', 'process_NCEI_03_chill_d.py', 'process_NCEI_03_chill_dd.py', 'process_NCEI_03_grow_dd.py', 'process_NCEI_03_grow_dd_base0.py', 'process_NCEI_03_prcp_03d.py', 'process_NCEI_03_prcp_07d.py', 'process_NCEI_03_prcp_120d.py', 'process_NCEI_03_prcp_15d.py', 'process_NCEI_03_prcp_180d.py', 'process_NCEI_03_prcp_30d.py', 'process_NCEI_03_prcp_365d.py', 'process_NCEI_03_prcp_60d.py', 'process_NCEI_03_prcp_90d.py', 'process_NCEI_03_prcp_90d_nd0.py', 'process_NCEI_03_prcp_90d_nd10.py', 'process_NCEI_03_prcp_90d_nd25.py', 'process_NCEI_03_preprocess.py', 'process_NCEI_03_tavg_03d.py', 'process_NCEI_03_tavg_07d.py', 'process_NCEI_03_tavg_15d.py', 'process_NCEI_03_tavg_30d.py', 'process_NCEI_03_tavg_60d.py', 'process_NCEI_03_tavg_90d.py', 'process_NCEI_03_tavg_frz.py', 'process_NCEI_03_tmax_03d.py', 'process_NCEI_03_tmax_07d.py', 'process_NCEI_03_tmax_15d.py', 'process_NCEI_03_tmax_30d.py', 'process_NCEI_03_tmax_60d.py', 'process_NCEI_03_tmax_90d.py', 'process_NCEI_03_tmax_frz.py', 'process_NCEI_03_tmin_03d.py', 'process_NCEI_03_tmin_07d.py', 'process_NCEI_03_tmin_15d.py', 'process_NCEI_03_tmin_30d.py', 'process_NCEI_03_tmin_60d.py', 'process_NCEI_03_tmin_90d.py', 'process_NCEI_03_tmin_frz.py', 'process_NCEI_03_vpd_03d.py', 'process_NCEI_03_vpd_07d.py', 'process_NCEI_03_vpd_15d.py', 'process_NCEI_03_vpd_30d.py', 'process_NCEI_03_vpd_60d.py', 'process_NCEI_03_vpd_90d.py', 'process_NCEI_04a.py', 'process_NCEI_04b.py', 'process_NCEI_05.py', 'process_NCEI_06.py', 'process_NCEI_07.py', 'process_NCEI_08.py', 'process_NCEI_09.py', 'process_NCEI_10.py', 'process_NCEI_11.py', 'process_NCEI_12.py', 'process_NCEI_13.py', 'process_NCEI_14.py', 'process_NCEI_15.py'] # modules = ['Date_Convert.py', 'Interpolation.py', 'Plots.py', 'process_NCEI_03_aux.py', 'Read_Header_Files.py', 'Stats.py', 'Teleconnections.py', 'UTM_Geo_Convert.py'] # htcondor = ['process_NCEI_00.sh', 'process_NCEI_00.sub', 'process_NCEI_01.sh', 'process_NCEI_01.sub', 'process_NCEI_02a.sh', 'process_NCEI_02a.sub', 'process_NCEI_02b.sh', 'process_NCEI_02b.sub', 'process_NCEI_02b_dag.sub', 'process_NCEI_03_chill_d.sh', 'process_NCEI_03_chill_dd.sh', 'process_NCEI_03_dag_gen.py', 'process_NCEI_03_generic.sub', 'process_NCEI_03_grow_dd.sh', 'process_NCEI_03_grow_dd_base0.sh', 'process_NCEI_03_prcp_03d.sh', 'process_NCEI_03_prcp_07d.sh', 'process_NCEI_03_prcp_120d.sh', 'process_NCEI_03_prcp_15d.sh', 'process_NCEI_03_prcp_180d.sh', 'process_NCEI_03_prcp_30d.sh', 'process_NCEI_03_prcp_365d.sh', 'process_NCEI_03_prcp_60d.sh', 'process_NCEI_03_prcp_90d.sh', 'process_NCEI_03_prcp_90d_nd0.sh', 'process_NCEI_03_prcp_90d_nd10.sh', 'process_NCEI_03_prcp_90d_nd25.sh', 'process_NCEI_03_preprocess.sh', 'process_NCEI_03_tavg_03d.sh', 'process_NCEI_03_tavg_07d.sh', 'process_NCEI_03_tavg_15d.sh', 'process_NCEI_03_tavg_30d.sh', 'process_NCEI_03_tavg_60d.sh', 'process_NCEI_03_tavg_90d.sh', 'process_NCEI_03_tavg_frz.sh', 'process_NCEI_03_tmax_03d.sh', 'process_NCEI_03_tmax_07d.sh', 'process_NCEI_03_tmax_15d.sh', 'process_NCEI_03_tmax_30d.sh', 'process_NCEI_03_tmax_60d.sh', 'process_NCEI_03_tmax_90d.sh', 'process_NCEI_03_tmax_frz.sh', 'process_NCEI_03_tmin_03d.sh', 'process_NCEI_03_tmin_07d.sh', 'process_NCEI_03_tmin_15d.sh', 'process_NCEI_03_tmin_30d.sh', 'process_NCEI_03_tmin_60d.sh', 'process_NCEI_03_tmin_90d.sh', 'process_NCEI_03_tmin_frz.sh', 'process_NCEI_03_vpd_03d.sh', 'process_NCEI_03_vpd_07d.sh', 'process_NCEI_03_vpd_15d.sh', 'process_NCEI_03_vpd_30d.sh', 'process_NCEI_03_vpd_60d.sh', 'process_NCEI_03_vpd_90d.sh', 'process_NCEI_04a.sh', 'process_NCEI_04a.sub', 'process_NCEI_04b.sh', 'process_NCEI_04b.sub', 'process_NCEI_05.sh', 'process_NCEI_05.sub', 'process_NCEI_06.sh', 'process_NCEI_06.sub', 'process_NCEI_07.sh', 'process_NCEI_07.sub', 'process_NCEI_08.sh', 'process_NCEI_08.sub', 'process_NCEI_09.sh', 'process_NCEI_09.sub'] # dependencies = ['os', 'sys', 'datetime', 'glob', 'numpy', 'pandas', 'h5py', 'matplotlib', 'matplotlib.pyplot', 'gdal', 'osgeo.osr', 'scipy.interpolate', 'scipy.ndimage', 'scipy.stats', 'mpl_toolkits', 'mpl_toolkits.basemap', 'pickle'] # gz_data_files = ['EPA_L4_Ecoregions_WLS_UTM15N.bil.gz', 'NCEI_WLS_19830101-20151031.csv.gz', 'NLCD_2011_WLS_UTM15N.bil.gz'] # data_files = ['EPA_L4_Ecoregions_WLS_polygonIDs.txt', 'EPA_L4_Ecoregions_WLS_UTM15N.bil', 'EPA_L4_Ecoregions_WLS_UTM15N.hdr', 'NCEI_WLS_19830101-20151031.csv', 'NCEP_CPC_AO_indices.csv', 'NCEP_CPC_ENSO_indices.csv', 'NCEP_CPC_NAO_indices.csv', 'NCEP_CPC_PNA_indices.csv', 'NLCD_2011_WLS_UTM15N.bil', 'NLCD_2011_WLS_UTM15N.hdr', 'NOAA_ESRL_AMO_indices.csv', 'NOAA_ESRL_PDO_indices.csv', 'NSIDC_MIFL_Superior_Ice.csv', 'Query_locations_dates_sample.csv'] # doc_files = ['How_to_get_NCEI_GHCND_data.txt', 'NCEI_GHCND_documentation.pdf'] # tools = ['query_NCEI_grids.py', 'orientation_maps.py'] # add_dirs = ['analyses', 'grids', 'images'] # analyses_dirs = ['annual_maps', 'cluster_maps', 'ecoregion_maps', 'figures', 'summary_maps'] # os.system('rm .DS_Store') os.system('rm */.DS_Store') os.system('rm ._*') os.system('rm */._*') # message('checking for auxiliary files that should accompany this software') txts_present = glob.glob('*.txt') mds_present = glob.glob('*.md') absent = 0 for txt in txt_files: if txt in txts_present: message('- found auxiliary file \'%s\' as expected' % txt) else: message('- auxiliary file \'%s\' is absent' % txt) absent += 1 for md in md_files: if md in mds_present: message('- found auxiliary file \'%s\' as expected' % md) else: message('- auxiliary file \'%s\' is absent' % md) absent += 1 if absent > 0: message('- you don\'t need them to run things, but you do need them to \ understand things') message('- you should probably download this package again from scratch') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for top-level directories that should already exist') dirs_present = [d.replace('/', '') for d in glob.glob('*/')] absent = 0 for dirname in main_dirs: if dirname in dirs_present: message('- found main directory \'%s\' as expected' % dirname) else: message('- main directory \'%s\' is absent' % dirname) absent += 1 if absent > 0: message('- you should download this package again from scratch') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for main scripts and modules that comprise this software') src_present = glob.glob('source/*') absent = 0 for srcfile in scripts: srcfile = 'source/%s' % srcfile if srcfile in src_present: message('- found script \'%s\' as expected' % srcfile) else: message('- script \'%s\' is absent' % srcfile) absent += 1 for srcfile in modules: srcfile = 'source/%s' % srcfile if srcfile in src_present: message('- found module \'%s\' as expected' % srcfile) else: message('- module \'%s\' is absent' % srcfile) absent += 1 if absent > 0: message('- you should download this package again from scratch') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for script-based tools that accompany this software') src_present = glob.glob('tools/*') absent = 0 for srcfile in tools: srcfile = 'tools/%s' % srcfile if srcfile in src_present: message('- found script \'%s\' as expected' % srcfile) else: message('- script \'%s\' is absent' % srcfile) absent += 1 if absent > 0: message('- if you need these tools, you should download this package \ again from scratch') message(' ') # message('checking for HTCondor example files that accompany this software') src_present = glob.glob('htcondor/*') absent = 0 for srcfile in htcondor: srcfile = 'htcondor/%s' % srcfile if srcfile in src_present: message('- found htcondor file \'%s\' as expected' % srcfile) else: message('- htcondor file \'%s\' is absent' % srcfile) absent += 1 if absent > 0: message('- if you need these files, you should download this package \ again from scratch') message(' ') # message('checking for essential python package dependencies for this software') err = 0 # try: import os message('- python dependency \'os\' is available') except ImportError: message('- essential python dependency \'os\' is not available') err += 1 # try: import sys message('- python dependency \'sys\' is available') except ImportError: message('- essential python dependency \'sys\' is not available') err += 1 # try: import datetime message('- python dependency \'datetime\' is available') except ImportError: message('- essential python dependency \'datetime\' is not available') err += 1 # try: import glob message('- python dependency \'glob\' is available') except ImportError: message('- essential python dependency \'glob\' is not available') err += 1 # try: import pickle message('- python dependency \'pickle\' is available') except ImportError: message('- essential python dependency \'pickle\' is not available') err += 1 # try: import numpy message('- python dependency \'numpy\' is available') except ImportError: message('- essential python dependency \'numpy\' is not available') err += 1 # try: import pandas message('- python dependency \'pandas\' is available') except ImportError: message('- essential python dependency \'pandas\' is not available') err += 1 # try: import h5py message('- python dependency \'h5py\' is available') except ImportError: message('- essential python dependency \'h5py\' is not available') err += 1 # try: import gdal message('- python dependency \'gdal\' is available') except ImportError: message('- essential python dependency \'gdal\' is not available') err += 1 # try: import osgeo.osr message('- python dependency \'osgeo.osr\' is available') except ImportError: message('- essential python dependency \'osgeo.osr\' is not available') err += 1 # try: import scipy.interpolate message('- python dependency \'scipy.interpolate\' is available') except ImportError: message('- essential python dependency \'scipy.interpolate\' is not \ available') err += 1 # try: import scipy.ndimage message('- python dependency \'scipy.ndimage\' is available') except ImportError: message('- essential python dependency \'scipy.ndimage\' is not available') err += 1 # try: import scipy.stats message('- python dependency \'scipy.stats\' is available') except ImportError: message('- essential python dependency \'scipy.stats\' is not available') err += 1 # try: import matplotlib message('- python dependency \'matplotlib\' is available') except ImportError: message('- essential python dependency \'matplotlib\' is not available') err += 1 # try: import matplotlib.pyplot message('- python dependency \'matplotlib.pyplot\' is available') except ImportError: message('- essential python dependency \'matplotlib.pyplot\' is not \ available') err += 1 # try: import mpl_toolkits message('- python dependency \'mpl_toolkits\' is available') except ImportError: message('- essential python dependency \'mpl_toolkits\' is not available') err += 1 # try: import mpl_toolkits.basemap message('- python dependency \'mpl_toolkits.basemap\' is available') except ImportError: message('- essential python dependency \'mpl_toolkits.basemap\' is not \ available') err += 1 # if err > 0: message('- you need to install one or more additional python packages for \ this software to work') message('- all of these packages are available via Anaconda (\'conda\') \ and/or PyPI (\'pip\') repositories') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for example data files that should accompany this software') gz_data_present = glob.glob('data/*.gz') absent = 0 for gz_dfile in gz_data_files: gz_dfile_path = 'data/%s' % gz_dfile if gz_dfile_path in gz_data_present: message('- found compressed data file \'%s\' as expected' % gz_dfile) message('-- uncompressing \'%s\'' % gz_dfile) os.system('cd data') os.system('gunzip %s' % gz_dfile) os.system('cd ..') else: message('- compressed example data file \'%s\' is absent' % gz_dfile) absent += 1 if absent > 0: message('- you don\'t need these if you have your own data in the right \ formats') message('- if you need the examples, you can find them at on GitHub at') message(' https://github.com/megarcia/WxCD') # data_present = glob.glob('data/*') absent = 0 for dfile in data_files: dfile_path = 'data/%s' % dfile if dfile_path in data_present: message('- found data file \'%s\' as expected' % dfile) else: message('- example data file \'%s\' is absent' % dfile) absent += 1 if absent > 0: message('- you don\'t need these if you have your own data in the right \ formats') message('- if you need the examples, you can find them at on GitHub at') message(' https://github.com/megarcia/WxCD') message(' ') # message('checking for data documentation files that should accompany this \ software') docs_present = glob.glob('docs/*') absent = 0 for dfile in doc_files: dfile = 'docs/%s' % dfile if dfile in docs_present: message('- found documentation file \'%s\' as expected' % dfile) else: message('- data documentation file \'%s\' is absent' % dfile) absent += 1 if absent > 0: message('- you don\'t need these if you have your own documentation') message('- if you need the examples, you can find them at on GitHub at') message(' https://github.com/megarcia/GT16_JGRA') message(' ') # message('creating top-level and sub-directories that will be used for process \ output') for dirname in add_dirs: os.system('mkdir %s' % dirname) message('- made top-level directory \'%s\' ' % dirname) for dirname in analyses_dirs: os.system('mkdir analyses/%s' % dirname) message('- made sub-directory \'analyses/%s\' ' % dirname) message(' ') # message('copying source scripts and modules to top-level directory') os.system('cp source/*.py .') message('archiving original scripts and modules to \'source_orig\' directory') os.system('mv source source_orig') # message('copying tools to top-level directory') os.system('cp tools/*.py .') message('archiving original tools scripts to \'tools_orig\' directory') os.system('mv tools tools_orig') message(' ') # message('all set!') message(' ') # message('if you plan to use the HTCondor example files, you\'ll need to \ move or copy them to') message(' your top-level directory') message(' ') # message('make sure to read the \'README.md\' file before you get started on \ the scripts') message(' ') # message('if you need help getting your own dataset of GHCND weather \ observations, there is') message(' a how-to document in the \'docs\' directory') message(' ') # message('please send questions, bug reports, any other requests to \ matt.e.garcia@gmail.com') message(' (and include a helpfully descriptive subject line, if you could)') message('or submit them through the Issues tab at the GitHub repository for \ this package') message(' ') # sys.exit(0)
megarcia/WxCD
setup.py
Python
gpl-3.0
18,007
/* Copyright 2010, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var GdataExtension = {}; GdataExtension.isAuthorized = function() { return $.cookie('authsub_token') !== null; }; GdataExtension.showAuthorizationDialog = function(onAuthorized, onNotAuthorized) { if (window.name) { var windowName = window.name; } else { var windowName = "openrefine" + new Date().getTime(); window.name = windowName; } var callbackName = "cb" + new Date().getTime(); var callback = function(evt) { delete window[callbackName]; if (GdataExtension.isAuthorized()) { onAuthorized(); } else if (onNotAuthorized) { onNotAuthorized(); } window.setTimeout(function() { win.close(); }, 100); }; window[callbackName] = callback; var url = ModuleWirings['gdata'] + "authorize?winname=" + escape(windowName) + "&callback=" + escape(callbackName); var win = window.open(url, "openrefinegdataauth", "resizable=1,width=800,height=600"); };
WGBH/AMS
OpenRefine/extensions/gdata/module/scripts/gdata-extension.js
JavaScript
gpl-3.0
2,422
module.exports = { 'code': 1100, 'type': 'UserExtTokenAlreadyRegistered', 'message': 'The provided external authentification is already used', 'http': 400 };
Tuxkowo/api.life.tl
wrappers/LifeErrors/UserExtTokenAlreadyRegistered.js
JavaScript
gpl-3.0
178
package getters import ( "errors" "fmt" "regexp" "strings" ) //longzhu 龙珠直播 type longzhu struct{} //Site 实现接口 func (i *longzhu) Site() string { return "龙珠直播" } //SiteURL 实现接口 func (i *longzhu) SiteURL() string { return "http://www.longzhu.com" } //SiteIcon 实现接口 func (i *longzhu) SiteIcon() string { return i.SiteURL() + "/favicon.ico" } //FileExt 实现接口 func (i *longzhu) FileExt() string { return "flv" } //NeedFFMpeg 实现接口 func (i *longzhu) NeedFFMpeg() bool { return false } //GetRoomInfo 实现接口 func (i *longzhu) GetRoomInfo(url string) (id string, live bool, err error) { defer func() { if recover() != nil { err = errors.New("fail get data") } }() url = strings.ToLower(url) reg, _ := regexp.Compile("longzhu\\.com/(\\w+)") id = reg.FindStringSubmatch(url)[1] if id != "" { url := "http://roomapicdn.plu.cn/room/RoomAppStatusV2?domain=" + id var tmp string tmp, err = httpGet(url) if err == nil { if strings.Contains(tmp, "IsBroadcasting") { live = strings.Contains(tmp, "\"IsBroadcasting\":true") } else { id = "" } } } if id == "" { err = errors.New("fail get data") } return } //GetLiveInfo 实现接口 func (i *longzhu) GetLiveInfo(id string) (live LiveInfo, err error) { defer func() { if recover() != nil { err = errors.New("fail get data") } }() live = LiveInfo{} url := "http://roomapicdn.plu.cn/room/RoomAppStatusV2?domain=" + id tmp, err := httpGet(url) json := *(pruseJSON(tmp).JToken("BaseRoomInfo")) nick := json["Name"].(string) title := json["BoardCastTitle"].(string) details := json["Desc"].(string) _id := json["Id"] live.RoomID = fmt.Sprintf("%.f", _id) url = "http://livestream.plu.cn/live/getlivePlayurl?roomId=" + live.RoomID tmp, err = httpGet(url) json = *(pruseJSON(tmp).JTokens("playLines")[0].JTokens("urls")[0]) video := json["securityUrl"].(string) live.LiveNick = nick live.RoomTitle = title live.RoomDetails = details live.LivingIMG = "" live.VideoURL = video if video == "" { err = errors.New("fail get data") } return }
Baozisoftware/Luzhibo-go
api/getters/longzhu.go
GO
gpl-3.0
2,208
/** * Generic interface to compare objects */ public interface Comparable<T> { public int compareTo(T o); }
agicquel/dut
M2103/TP9/src/Comparable.java
Java
gpl-3.0
108
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package xqt.model.functions.aggregates; import xqt.model.functions.AggregateFunction; /** * * @author Javad Chamanara <chamanara@gmail.com> */ public class Count implements AggregateFunction{ long counter = 0; @Override public Long move(Object data) { // Long is a subclass of Object, hence, compatible... if(data != null) counter++; return counter; } }
javadch/quis
xqt.model/src/main/java/xqt/model/functions/aggregates/Count.java
Java
gpl-3.0
589
# =================================================================== # # Copyright (c) 2014, Legrandin <helderijs@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # =================================================================== from Cryptodome.Util.py3compat import bord from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer, SmartPointer, create_string_buffer, get_raw_buffer, c_size_t, c_uint8_ptr) _raw_md2_lib = load_pycryptodome_raw_lib( "Cryptodome.Hash._MD2", """ int md2_init(void **shaState); int md2_destroy(void *shaState); int md2_update(void *hs, const uint8_t *buf, size_t len); int md2_digest(const void *shaState, uint8_t digest[20]); int md2_copy(const void *src, void *dst); """) class MD2Hash(object): """An MD2 hash object. Do not instantiate directly. Use the :func:`new` function. :ivar oid: ASN.1 Object ID :vartype oid: string :ivar block_size: the size in bytes of the internal message block, input to the compression function :vartype block_size: integer :ivar digest_size: the size in bytes of the resulting hash :vartype digest_size: integer """ # The size of the resulting hash in bytes. digest_size = 16 # The internal block size of the hash algorithm in bytes. block_size = 64 # ASN.1 Object ID oid = "1.2.840.113549.2.2" def __init__(self, data=None): state = VoidPointer() result = _raw_md2_lib.md2_init(state.address_of()) if result: raise ValueError("Error %d while instantiating MD2" % result) self._state = SmartPointer(state.get(), _raw_md2_lib.md2_destroy) if data: self.update(data) def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Args: data (byte string/byte array/memoryview): The next chunk of the message being hashed. """ result = _raw_md2_lib.md2_update(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while instantiating MD2" % result) def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Binary form. :rtype: byte string """ bfr = create_string_buffer(self.digest_size) result = _raw_md2_lib.md2_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while instantiating MD2" % result) return get_raw_buffer(bfr) def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. :return: The hash digest, computed over the data processed so far. Hexadecimal encoded. :rtype: string """ return "".join(["%02x" % bord(x) for x in self.digest()]) def copy(self): """Return a copy ("clone") of the hash object. The copy will have the same internal state as the original hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. :return: A hash object of the same type """ clone = MD2Hash() result = _raw_md2_lib.md2_copy(self._state.get(), clone._state.get()) if result: raise ValueError("Error %d while copying MD2" % result) return clone def new(self, data=None): return MD2Hash(data) def new(data=None): """Create a new hash object. :parameter data: Optional. The very first chunk of the message to hash. It is equivalent to an early call to :meth:`MD2Hash.update`. :type data: byte string/byte array/memoryview :Return: A :class:`MD2Hash` hash object """ return MD2Hash().new(data) # The size of the resulting hash in bytes. digest_size = MD2Hash.digest_size # The internal block size of the hash algorithm in bytes. block_size = MD2Hash.block_size
hclivess/Stallion
nuitka/Cryptodome/Hash/MD2.py
Python
gpl-3.0
6,130
/* * Copyright (C) 2018-2019 The ESPResSo project * * This file is part of ESPResSo. * * ESPResSo 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. * * ESPResSo 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/>. */ /* Unit tests for the Utils::tensor_product class. */ #define BOOST_TEST_MODULE Utils::tensor_product #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "utils/math/tensor_product.hpp" using Utils::tensor_product; #include <type_traits> BOOST_AUTO_TEST_CASE(square) { Utils::Vector<int, 4> x{1, 2, 3, 4}; Utils::Vector<int, 4> y{5, 6, 7, 8}; using expected_type = Utils::Vector<Utils::Vector<int, 4>, 4>; using actual_type = decltype(tensor_product(x, y)); /* Check return type */ static_assert(std::is_same<expected_type, actual_type>::value, ""); auto prod = tensor_product(x, y); /* Check values */ for (std::size_t i = 0; i < x.size(); i++) for (std::size_t j = 0; j < y.size(); j++) { BOOST_CHECK(prod[i][j] == x[i] * y[j]); } } BOOST_AUTO_TEST_CASE(non_square) { Utils::Vector3i x{1, 2, 3}; Utils::Vector<int, 4> y{5, 6, 7, 8}; using expected_type = Utils::Vector<Utils::Vector<int, 4>, 3>; using actual_type = decltype(tensor_product(x, y)); /* Check return type */ static_assert(std::is_same<expected_type, actual_type>::value, ""); auto prod = tensor_product(x, y); /* Check values */ for (std::size_t i = 0; i < x.size(); i++) for (std::size_t j = 0; j < y.size(); j++) { BOOST_CHECK(prod[i][j] == x[i] * y[j]); } } BOOST_AUTO_TEST_CASE(left_scalar) { double x = 3.; Utils::Vector2d y{1., 2.}; using expected_type = Utils::Vector2d; using actual_type = decltype(tensor_product(x, y)); /* Check return type */ static_assert(std::is_same<expected_type, actual_type>::value, ""); auto prod = tensor_product(x, y); BOOST_CHECK((x * y) == prod); }
KaiSzuttor/espresso
src/utils/tests/tensor_product_test.cpp
C++
gpl-3.0
2,407
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.4.1) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x01\xf1\ \x00\ \x00\x09\x00\x78\x9c\xdd\x96\x51\x6f\x9b\x30\x10\xc7\xdf\xfb\x29\ \x3c\x1e\x9a\x4d\x15\xd0\x49\x7b\x98\x52\x48\x34\x92\x4c\xea\xd4\ \xaa\x54\x69\x55\xf5\xd1\x98\x0b\x71\x01\xdb\x35\x26\x09\xdf\x7e\ \x86\xb0\x96\xa4\x2c\xa4\x1d\x4f\xe3\xc5\xd8\x77\xbe\xdf\x9d\x8d\ \xff\xc6\x19\x6f\xd2\x04\xad\x40\x66\x94\x33\xd7\xf8\x6a\x9d\x1b\ \x08\x18\xe1\x21\x65\x91\x6b\xe4\x6a\x61\x7e\x37\xc6\xa3\x13\xe7\ \xd3\xf4\x66\x72\xf7\xe8\xcf\xd0\x26\x80\x44\xf7\xcb\x66\x77\xda\ \xe8\x04\xe9\xc7\x59\xf0\x24\x04\x89\xaa\x26\x74\x0d\xc6\x6b\x43\ \x65\x54\x54\x25\x30\xf2\x38\x8f\x53\x2c\xe3\x0c\x79\x58\x3a\xf6\ \x76\xf0\xd5\x29\xa8\xcd\x68\x29\x61\xe1\x1a\x4b\xa5\xc4\xd0\xb6\ \x41\x52\x62\xd2\x10\x2c\x51\xa8\x25\x67\xa6\x90\xfc\x09\x88\xca\ \x2c\x2e\x23\xbb\xc1\x68\x70\x66\x7a\x0a\x7a\x80\x00\xcd\xa9\x82\ \xb7\x1c\xfb\x0f\xa8\x93\xbd\x5e\xaf\x2d\x49\x75\xb5\x01\x66\x31\ \xe1\xa9\xc8\x95\x5e\x1e\x4b\xbf\xfd\x85\xec\x17\xb7\xea\x9d\xe4\ \x43\xeb\xd6\x88\xdc\x88\x9b\xbd\x09\xdc\x51\xc2\xb3\xb2\x28\xb7\ \xf7\x53\x6e\x0f\xde\x1e\xbb\x25\xf1\xa3\x98\x21\xac\x20\xe1\x42\ \x7f\x2e\x87\xe9\xd3\x17\xbf\x3e\xf8\x21\x27\x35\xff\x30\x94\x93\ \x3c\x05\xa6\xb0\xd2\xdf\x72\x1f\xdc\x20\xe1\xd1\x31\x60\x4f\xfb\ \xf5\xc1\x5b\x70\x99\xa7\xc7\x00\x7f\x96\x8e\x7d\x10\x45\x82\x19\ \xa8\x4e\xa4\x5f\xb9\xa1\x5b\xd5\x07\xf3\x59\x11\xbd\x49\x12\xda\ \x0e\xfc\x6e\x99\x93\xca\xaf\x1f\xa6\x89\x85\x68\xd5\x98\x1d\xa4\ \xf9\xa3\xf6\x3a\x1a\xea\xd8\xdb\x03\xff\x7e\x05\xf0\x2b\xfd\xfb\ \xb8\x0a\x6c\xf5\xb3\xa3\xa4\x1a\x72\x85\x59\x94\xe3\x08\x4a\x5a\ \xd6\x93\x2a\x88\x42\xd0\x66\x12\x65\xbf\x33\x11\x1f\x93\xb8\xcc\ \xe3\x92\x85\xb0\x19\x22\xbf\xf0\x2f\x3f\xb8\xd4\x7b\xbd\xbd\x45\ \x2f\x20\x3b\x74\x5f\x5d\x03\xcb\xff\xdb\x0b\xeb\xdb\xbf\xa1\x9f\ \xf0\x0a\x67\x44\x52\xa1\x86\x09\x27\x95\x98\x5a\x95\x65\x90\x62\ \x9a\x28\x3e\x1c\xcf\xef\xbd\x5f\xb3\xc9\x9d\x3b\x40\x67\x28\xac\ \x45\xd7\xaa\x48\x7a\x60\x70\x8a\x53\x71\xe1\xdd\x4c\x1f\x2b\x3b\ \x64\x04\x0b\xf8\xbc\x13\xe9\xcb\x45\x7b\xf2\x73\x60\x21\xba\xa2\ \x2c\xee\xcc\xfb\x75\xf3\x1d\x7b\xfb\x23\xf3\x1b\xc5\xa5\x8d\x58\ \ " qt_resource_name = b"\ \x00\x15\ \x0c\xd3\x2e\x3c\ \x00\x44\ \x00\x65\x00\x66\x00\x61\x00\x75\x00\x6c\x00\x74\x00\x42\x00\x6f\x00\x6f\x00\x6b\x00\x6d\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x2e\ \x00\x78\x00\x62\x00\x65\x00\x6c\ " qt_resource_struct = b"\ \x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ \x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ " def qInitResources(): QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) def qCleanupResources(): QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) qInitResources()
testmana2/test
Helpviewer/Bookmarks/DefaultBookmarks_rc.py
Python
gpl-3.0
2,920
namespace Grove.UserInterface.Steps { using System.Collections.Generic; using System.Linq; using Events; using Grove.Infrastructure; using Step = Grove.Step; public class ViewModel : ViewModelBase, IReceive<TurnStartedEvent> { private readonly List<UserInterface.Step.ViewModel> _steps = new List<UserInterface.Step.ViewModel>(); public IEnumerable<UserInterface.Step.ViewModel> Steps { get { return _steps; } } public virtual int TurnNumber { get; protected set; } public void Receive(TurnStartedEvent message) { TurnNumber = message.TurnCount; } public override void Initialize() { _steps.AddRange(CreateStepViewModels()); TurnNumber = Game.Turn.TurnCount; SetCurrentStep(); } private void SetCurrentStep() { var currentStep = _steps.SingleOrDefault(x => x.IsStep(Game.Turn.Step)); if (currentStep != null) // pre untap steps are not shown (e.g Mulligan step) currentStep.IsCurent = true; } private IEnumerable<UserInterface.Step.ViewModel> CreateStepViewModels() { yield return ViewModels.Step.Create("Untap", Step.Untap); yield return ViewModels.Step.Create("Upkeep", Step.Upkeep); yield return ViewModels.Step.Create("Draw", Step.Draw); yield return ViewModels.Step.Create("1st main", Step.FirstMain); yield return ViewModels.Step.Create("Beg. of combat", Step.BeginningOfCombat); yield return ViewModels.Step.Create("Dec. attackers", Step.DeclareAttackers); yield return ViewModels.Step.Create("Dec. blockers", Step.DeclareBlockers); yield return ViewModels.Step.Create("Combat damage", Step.CombatDamage, Step.FirstStrikeCombatDamage); yield return ViewModels.Step.Create("End of combat", Step.EndOfCombat); yield return ViewModels.Step.Create("2nd main", Step.SecondMain); yield return ViewModels.Step.Create("End of turn", Step.EndOfTurn); yield return ViewModels.Step.Create("Clean up", Step.CleanUp); } } }
tectronics/magicgrove
source/Grove/UserInterface/Steps/ViewModel.cs
C#
gpl-3.0
2,024
/* Copyright © 2014-2019 by The qTox Project Contributors This file is part of qTox, a Qt-based graphical interface for Tox. qTox is libre 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. qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>. */ #include "offlinemsgengine.h" #include "src/core/core.h" #include "src/model/friend.h" #include "src/nexus.h" #include "src/persistence/profile.h" #include "src/persistence/settings.h" #include "src/model/status.h" #include <QMutexLocker> #include <QTimer> #include <QCoreApplication> #include <chrono> OfflineMsgEngine::OfflineMsgEngine(Friend* frnd, ICoreFriendMessageSender* messageSender) : mutex(QMutex::Recursive) , f(frnd) , messageSender(messageSender) {} /** * @brief Notification that the message is now delivered. * * @param[in] receipt Toxcore message ID which the receipt is for. */ void OfflineMsgEngine::onReceiptReceived(ReceiptNum receipt) { QMutexLocker ml(&mutex); if (receivedReceipts.contains(receipt)) { qWarning() << "Receievd duplicate receipt" << receipt.get() << "from friend" << f->getId(); return; } receivedReceipts.append(receipt); checkForCompleteMessages(receipt); } /** * @brief Add a message which has been saved to history, but not sent yet to the peer. * * OfflineMsgEngine will send this message once the friend becomes online again, then track its * receipt, updating history and chatlog once received. * * @param[in] messageID database RowId of the message, used to eventually mark messages as received in history * @param[in] msg chat message line in the chatlog, used to eventually set the message's receieved timestamp */ void OfflineMsgEngine::addUnsentMessage(Message const& message, CompletionFn completionCallback) { QMutexLocker ml(&mutex); unsentMessages.append(OfflineMessage{message, std::chrono::steady_clock::now(), completionCallback}); } /** * @brief Add a message which has been saved to history, and which has been sent to the peer. * * OfflineMsgEngine will track this message's receipt. If the friend goes offline then comes back before the receipt * is received, OfflineMsgEngine will also resend the message, updating history and chatlog once received. * * @param[in] receipt the toxcore message ID, corresponding to expected receipt ID * @param[in] messageID database RowId of the message, used to eventually mark messages as received in history * @param[in] msg chat message line in the chatlog, used to eventually set the message's receieved timestamp */ void OfflineMsgEngine::addSentMessage(ReceiptNum receipt, Message const& message, CompletionFn completionCallback) { QMutexLocker ml(&mutex); assert(!sentMessages.contains(receipt)); sentMessages.insert(receipt, {message, std::chrono::steady_clock::now(), completionCallback}); checkForCompleteMessages(receipt); } /** * @brief Deliver all messages, used when a friend comes online. */ void OfflineMsgEngine::deliverOfflineMsgs() { QMutexLocker ml(&mutex); if (!Status::isOnline(f->getStatus())) { return; } if (sentMessages.empty() && unsentMessages.empty()) { return; } QVector<OfflineMessage> messages = sentMessages.values().toVector() + unsentMessages; // order messages by authorship time to resend in same order as they were written std::sort(messages.begin(), messages.end(), [](const OfflineMessage& lhs, const OfflineMessage& rhs) { return lhs.authorshipTime < rhs.authorshipTime; }); removeAllMessages(); for (const auto& message : messages) { QString messageText = message.message.content; ReceiptNum receipt; bool messageSent{false}; if (message.message.isAction) { messageSent = messageSender->sendAction(f->getId(), messageText, receipt); } else { messageSent = messageSender->sendMessage(f->getId(), messageText, receipt); } if (messageSent) { addSentMessage(receipt, message.message, message.completionFn); } else { qCritical() << "deliverOfflineMsgs failed to send message"; addUnsentMessage(message.message, message.completionFn); } } } /** * @brief Removes all messages which are being tracked. */ void OfflineMsgEngine::removeAllMessages() { QMutexLocker ml(&mutex); receivedReceipts.clear(); sentMessages.clear(); unsentMessages.clear(); } void OfflineMsgEngine::completeMessage(QMap<ReceiptNum, OfflineMessage>::iterator msgIt) { msgIt->completionFn(); receivedReceipts.removeOne(msgIt.key()); sentMessages.erase(msgIt); } void OfflineMsgEngine::checkForCompleteMessages(ReceiptNum receipt) { auto msgIt = sentMessages.find(receipt); const bool receiptReceived = receivedReceipts.contains(receipt); if (!receiptReceived || msgIt == sentMessages.end()) { return; } completeMessage(msgIt); }
sudden6/qTox
src/persistence/offlinemsgengine.cpp
C++
gpl-3.0
5,508
../../../../../../../share/pyshared/orca/scripts/apps/nautilus/script.py
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/orca/scripts/apps/nautilus/script.py
Python
gpl-3.0
72
<?php /** * ... * * Copyright (c) 2007-2012 Christian Würker (ceusmedia.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/>. * * @category cmClasses * @package ADT * @author Christian Würker <christian.wuerker@ceusmedia.de> * @copyright 2007-2012 Christian Würker * @license http://www.gnu.org/licenses/gpl-3.0.txt GPL 3 * @link http://code.google.com/p/cmclasses/ * @see http://www.w3.org/Addressing/URL/url-spec.html * @version $Id$ */ /** * ... * @category cmClasses * @package ADT * @author Christian Würker <christian.wuerker@ceusmedia.de> * @copyright 2007-2012 Christian Würker * @license http://www.gnu.org/licenses/gpl-3.0.txt GPL 3 * @link http://code.google.com/p/cmclasses/ * @see http://www.w3.org/Addressing/URL/url-spec.html * @version $Id$ */ class ADT_URL { public $scheme; public $address; public $separator = "&"; public static $staticUrlScheme = ""; public static $staticUrlAddress = "./"; public function __construct( $scheme, $address = NULL ) { $scheme = preg_replace( "/^url:/i", "", $scheme ); if( $address === NULL && preg_match( "/^\S+:\S+$/", $scheme ) ) { $parts = explode( ":", $scheme ); $scheme = array_shift( $parts ); $address = preg_replace( "@^/*@", "", implode( ":", $parts ) ); } $this->setScheme( $scheme ); $this->setAddress( $address ); } static public function fromUrl( $url, $defaultScheme = "http", $defaultPort = NULL ){ $parts = parse_url( $url ); $scheme = isset( $parts['scheme'] ) ? $parts['scheme'] : $defaultScheme; if( !isset( $parts['host'] ) ) throw new InvalidArgumentException( 'URL is missing host' ); $port = !is_null( $defaultPort ) ? ":".$defaultPort : ""; $port = isset( $parts['port'] ) ? ':'.$parts['port'] : $port; $auth = isset( $parts['user'] ) ? ( isset( $parts['pass'] ) ? $parts['user'].':'.$parts['pass'].'@' : $parts['user'].'@' ) : ""; $path = isset( $parts['path'] ) ? $parts['path'] : ""; $query = isset( $parts['query'] ) ? '?'.$parts['query'] : ""; $fragment = isset( $parts['fragment'] ) ? '#'.$parts['fragment'] : ""; return new ADT_URL( $scheme, $parts['host'].$path.$query.$fragment ); } public function getScheme() { return $this->scheme; } public function getAddress() { return $this->address; } public function getUrl( $withPrefix = FALSE ) { $url = (string) $this; if( $withPrefix ) $url = "url:".$url; return $url; } /** * Builds URL Query String based on current URL Parameters extended by a Map of new Parameters ($mapSet) and reduced by a List of Parameters ($listRemove). * Note: You can also remove a Parameter by setting a new Parameter with value NULL. * * @access public * @param array $mapSet Map of Parameters to append to URL * @param array $reset List of Parameters to remove from URL * @param string $fragment Fragment ID * @return string New URL. */ public function infer( $mapSet = array(), $listRemove = array(), $fragment = NULL ) { $parameters = $this->inferQueryString( $mapSet, $listRemove, $fragment ); $parameters = $parameters ? "?".$parameters : ""; $parameters .= $fragment ? "#".$fragment : ""; return $this->getUrl().$parameters; } /** * Builds URL Query String based on current URL Parameters extended by a Map of new Parameters ($mapSet) and reduced by a List of Parameters ($listRemove). * Note: You can also remove a Parameter by setting a new Parameter with value NULL. * * @access public * @param array $mapSet Map of Parameters to append to URL * @param array $reset List of Parameters to remove from URL * @param string $fragment Fragment ID * @return string New URL. */ public function inferStatic( $mapSet = array(), $listRemove = array(), $fragment = NULL ) { $parameters = self::inferQueryString( $mapSet, $listRemove, $fragment ); $parameters = $parameters ? "?".$parameters : ""; $parameters .= $fragment ? "#".$fragment : ""; $url = new ADT_URL( self::$staticUrlScheme, self::$staticUrlAddress ); return $url->getUrl().$parameters; } /** * Builds URL based on current URL extended by a Map of new Parameters ($mapSet) and reduced by a List of Parameters ($listRemove). * Note: You can also remove a Parameter by setting a new Parameter with value NULL. * * @access public * @param array $mapSet Map of Parameters to append to URL * @param array $reset List of Parameters to remove from URL * @return string New URL. */ public static function inferQueryString( $mapSet = array(), $listRemove = array() ) { $mapRequest = $_GET; foreach( $mapSet as $key => $value ) // overwriting vars $mapRequest[$key] = $value; foreach( $listRemove as $key ) // unsetting vars unset( $mapRequest[$key] ); return http_build_query( $mapRequest, "test_", $this->separator ); // making link parameter string } public function setScheme( $scheme ) { if( !preg_match( '/^([a-z0-9][a-z0-9-]{1,31})?$/i', $scheme ) ) throw new InvalidArgumentException( 'Scheme "'.$scheme.'" is invalid.' ); $this->scheme = $scheme; } public function setAddress( $address ) { $alpha = 'a-z0-9'; $others = '()+,-.:=@;$_!*\\'; $reserved = '%\/?#'; $trans = '(['.$alpha.$others.$reserved.'])'; $hex = '(%[0-9a-f]{2})'; if( !preg_match( '/^('.$trans.'|'.$hex.')+$/i', $address ) ) throw new InvalidArgumentException( 'Address "'.$address.'" is invalid.' ); $this->address = $address; } public function __toString() { $prefix = $this->scheme ? ( $this->scheme.":" ) : ""; return $prefix.$this->address; } } ?>
kriss0r/cmclasses
src/ADT/URL.php
PHP
gpl-3.0
6,252
#line 3 "<stdout>" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define yy_create_buffer tagYY_create_buffer #define yy_delete_buffer tagYY_delete_buffer #define yy_flex_debug tagYY_flex_debug #define yy_init_buffer tagYY_init_buffer #define yy_flush_buffer tagYY_flush_buffer #define yy_load_buffer_state tagYY_load_buffer_state #define yy_switch_to_buffer tagYY_switch_to_buffer #define yyin tagYYin #define yyleng tagYYleng #define yylex tagYYlex #define yylineno tagYYlineno #define yyout tagYYout #define yyrestart tagYYrestart #define yytext tagYYtext #define yywrap tagYYwrap #define yyalloc tagYYalloc #define yyrealloc tagYYrealloc #define yyfree tagYYfree #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE tagYYrestart(tagYYin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif extern yy_size_t tagYYleng; extern FILE *tagYYin, *tagYYout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up tagYYtext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up tagYYtext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via tagYYrestart()), so that the user can continue scanning by * just pointing tagYYin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when tagYYtext is formed. */ static char yy_hold_char; static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */ yy_size_t tagYYleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow tagYYwrap()'s to do buffer switches * instead of setting up a fresh tagYYin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void tagYYrestart (FILE *input_file ); void tagYY_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE tagYY_create_buffer (FILE *file,int size ); void tagYY_delete_buffer (YY_BUFFER_STATE b ); void tagYY_flush_buffer (YY_BUFFER_STATE b ); void tagYYpush_buffer_state (YY_BUFFER_STATE new_buffer ); void tagYYpop_buffer_state (void ); static void tagYYensure_buffer_stack (void ); static void tagYY_load_buffer_state (void ); static void tagYY_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER tagYY_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE tagYY_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE tagYY_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE tagYY_scan_bytes (yyconst char *bytes,yy_size_t len ); void *tagYYalloc (yy_size_t ); void *tagYYrealloc (void *,yy_size_t ); void tagYYfree (void * ); #define yy_new_buffer tagYY_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ tagYYensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ tagYY_create_buffer(tagYYin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ tagYYensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ tagYY_create_buffer(tagYYin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ typedef unsigned char YY_CHAR; FILE *tagYYin = (FILE *) 0, *tagYYout = (FILE *) 0; typedef int yy_state_type; extern int tagYYlineno; int tagYYlineno = 1; extern char *tagYYtext; #define yytext_ptr tagYYtext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up tagYYtext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ tagYYleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 125 #define YY_END_OF_BUFFER 126 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[707] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 123, 124, 123, 79, 81, 79, 81, 123, 101, 100, 99, 99, 99, 96, 102, 123, 104, 112, 112, 106, 106, 111, 123, 123, 92, 123, 93, 123, 90, 90, 90, 123, 120, 119, 120, 119, 85, 121, 122, 84, 83, 123, 81, 13, 13, 16, 14, 16, 26, 26, 24, 18, 18, 24, 24, 24, 37, 37, 37, 27, 35, 36, 37, 63, 63, 68, 68, 56, 56, 61, 61, 70, 70, 75, 75, 39, 39, 44, 44, 47, 47, 53, 53, 48, 0, 0, 0, 0, 0, 81, 0, 0, 0, 81, 0, 100, 99, 99, 99, 96, 102, 0, 0, 112, 112, 0, 0, 0, 0, 0, 93, 0, 0, 90, 90, 90, 90, 0, 0, 0, 0, 0, 0, 85, 122, 84, 83, 0, 81, 0, 14, 0, 0, 0, 18, 0, 0, 23, 0, 0, 0, 27, 0, 0, 0, 0, 0, 36, 0, 0, 63, 0, 0, 0, 0, 0, 56, 0, 0, 0, 0, 0, 70, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 47, 0, 0, 0, 0, 0, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 81, 0, 99, 99, 103, 0, 112, 0, 0, 0, 109, 0, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 1, 0, 0, 81, 0, 0, 99, 99, 0, 112, 108, 107, 0, 0, 0, 0, 90, 113, 0, 116, 115, 0, 0, 0, 0, 0, 25, 25, 20, 19, 0, 0, 30, 29, 0, 0, 0, 0, 0, 65, 64, 0, 0, 0, 58, 57, 0, 0, 0, 72, 71, 0, 0, 0, 41, 40, 0, 0, 0, 50, 49, 0, 0, 0, 0, 77, 0, 0, 0, 0, 81, 0, 0, 99, 0, 0, 112, 0, 91, 0, 0, 90, 114, 0, 0, 0, 0, 0, 25, 0, 28, 0, 0, 33, 0, 66, 0, 0, 59, 0, 76, 73, 0, 45, 42, 0, 54, 51, 0, 0, 0, 0, 0, 0, 0, 0, 81, 0, 0, 0, 0, 0, 112, 110, 0, 88, 90, 118, 117, 82, 0, 15, 25, 22, 32, 31, 0, 67, 0, 60, 74, 43, 52, 0, 0, 0, 0, 0, 0, 0, 81, 0, 0, 0, 0, 0, 112, 0, 0, 90, 0, 25, 0, 62, 0, 0, 0, 0, 0, 0, 81, 0, 0, 0, 0, 105, 0, 87, 90, 0, 25, 69, 0, 0, 78, 0, 0, 0, 7, 0, 95, 0, 0, 0, 0, 89, 0, 0, 89, 89, 89, 90, 90, 89, 12, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89, 0, 0, 0, 0, 0, 89, 0, 90, 90, 89, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 86, 0, 0, 0, 0, 0, 0, 90, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89, 89, 0, 90, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 89, 0, 89, 0, 89, 89, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 98, 0, 0, 89, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 94, 38, 0, 0, 0, 0, 0, 0, 0, 55, 0, 0, 0, 10, 0, 0, 0, 0, 46, 0, 0, 11, 0, 0, 0, 4, 3, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 6, 7, 1, 8, 9, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 18, 20, 18, 18, 18, 18, 18, 18, 21, 22, 23, 24, 25, 1, 26, 27, 27, 28, 27, 27, 29, 27, 27, 30, 27, 27, 27, 27, 27, 27, 27, 27, 31, 27, 27, 27, 27, 27, 27, 27, 27, 32, 1, 33, 8, 34, 1, 35, 36, 37, 38, 39, 40, 41, 42, 43, 27, 27, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 27, 54, 55, 56, 27, 1, 57, 1, 58, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[59] = { 0, 1, 1, 2, 3, 4, 5, 1, 4, 6, 1, 1, 4, 7, 8, 7, 9, 10, 11, 11, 11, 12, 1, 13, 10, 14, 3, 15, 15, 15, 15, 15, 4, 4, 11, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 4, 16 } ; static yyconst flex_int16_t yy_base[746] = { 0, 2054, 2053, 0, 36, 57, 58, 81, 0, 139, 0, 197, 255, 60, 61, 313, 0, 371, 0, 429, 0, 485, 0, 209, 210, 543, 0, 59, 66, 601, 0, 212, 213, 215, 222, 659, 0, 715, 0, 771, 0, 829, 0, 214, 223, 887, 913, 939, 0, 995, 1051, 1109, 0, 67, 68, 238, 265, 267, 280, 287, 288, 289, 296, 2055, 2058, 2058, 0, 484, 0, 486, 2008, 2018, 2058, 0, 0, 2008, 2008, 0, 0, 191, 2058, 0, 2002, 2058, 34, 2058, 2010, 2009, 2058, 2012, 0, 224, 192, 253, 0, 2029, 2058, 2058, 684, 2058, 0, 2058, 0, 0, 0, 2028, 1167, 2058, 2009, 2058, 0, 2018, 2058, 2021, 2058, 0, 199, 2030, 2001, 2000, 2058, 502, 685, 2058, 2058, 0, 2021, 0, 0, 2033, 492, 0, 0, 2032, 974, 0, 0, 2031, 976, 0, 0, 2030, 991, 0, 0, 2029, 995, 2058, 2010, 2016, 1978, 2025, 1978, 0, 232, 1984, 1988, 1983, 2020, 0, 0, 1988, 1978, 0, 0, 1996, 1968, 0, 1980, 1966, 1965, 1972, 1961, 2010, 0, 1975, 1989, 452, 466, 0, 468, 1976, 1965, 1957, 1956, 1971, 1953, 0, 0, 0, 0, 1957, 0, 2000, 0, 1980, 1981, 1980, 0, 1948, 1947, 2058, 1954, 1943, 737, 2058, 1951, 1943, 1942, 1957, 1939, 0, 1966, 480, 0, 1955, 1944, 1936, 1935, 1933, 0, 1935, 1939, 1931, 1930, 1928, 0, 1965, 1934, 1926, 1925, 1923, 0, 1960, 1929, 1921, 1920, 1918, 0, 1955, 1924, 1916, 1915, 1913, 2058, 1950, 1929, 1917, 1923, 281, 1957, 1935, 1934, 1935, 1918, 211, 1905, 1916, 2058, 1904, 1903, 1930, 1929, 1911, 2058, 0, 1902, 1931, 674, 1922, 1898, 1923, 1922, 1892, 1895, 1891, 1894, 1922, 1891, 1915, 1914, 1896, 2058, 1886, 1911, 1910, 1880, 1883, 2058, 284, 1879, 1880, 1905, 1904, 1878, 1885, 1875, 1900, 1899, 1873, 1904, 1870, 1895, 1894, 1868, 1899, 1865, 1890, 1889, 1863, 1894, 1860, 1885, 1884, 1858, 1900, 1867, 1867, 1876, 1865, 2058, 1862, 1875, 2058, 1874, 469, 1846, 1851, 1844, 1842, 1888, 1844, 1855, 2058, 2058, 1837, 1863, 1832, 1851, 860, 2058, 1863, 2058, 2058, 1836, 1831, 1843, 1846, 1845, 0, 1831, 2058, 2058, 1826, 1855, 2058, 2058, 1828, 1823, 1849, 1832, 1850, 2058, 2058, 1819, 1830, 1847, 2058, 2058, 1816, 1842, 1844, 2058, 2058, 1813, 1839, 1841, 2058, 2058, 1810, 1836, 1838, 2058, 2058, 1807, 1820, 1813, 1811, 2058, 1811, 1810, 1811, 497, 1809, 1816, 1811, 1845, 1817, 1801, 1794, 1806, 2058, 1788, 1818, 874, 2058, 1820, 1819, 1815, 1794, 1813, 1798, 1797, 2058, 1813, 1812, 2058, 1782, 2058, 1810, 1807, 2058, 1808, 2058, 2058, 1807, 2058, 2058, 1806, 2058, 2058, 1805, 1779, 1786, 1785, 1780, 1787, 1802, 902, 1768, 1768, 1778, 1786, 1777, 1774, 1767, 2058, 1761, 1789, 482, 2058, 2058, 2058, 1772, 2058, 1760, 2058, 2058, 2058, 1785, 2058, 1802, 2058, 2058, 2058, 2058, 1752, 1781, 1781, 1763, 1752, 1777, 502, 1750, 1749, 1775, 1759, 1757, 1771, 1745, 1759, 1758, 966, 1768, 1756, 1784, 2058, 1733, 1765, 1781, 1740, 1734, 704, 1780, 1759, 1776, 1741, 1741, 0, 1738, 2058, 1224, 1772, 1725, 2058, 1724, 1733, 2058, 1750, 1749, 879, 2058, 1766, 2058, 1732, 1720, 1745, 1281, 1034, 1002, 1231, 1254, 2058, 1759, 1018, 1023, 1291, 2058, 1719, 1729, 1741, 1722, 893, 1028, 1719, 1705, 1715, 1743, 1307, 1708, 1706, 1684, 1667, 1665, 691, 1675, 1027, 984, 0, 1651, 1659, 1681, 1645, 1629, 1622, 261, 1609, 1613, 1599, 2058, 1586, 1575, 1580, 1605, 1604, 1572, 1040, 0, 1602, 700, 1574, 1571, 1591, 699, 1605, 1564, 1572, 1568, 1584, 997, 1064, 1583, 1043, 1598, 1553, 1542, 1530, 1575, 1553, 1011, 1571, 1535, 1531, 1514, 1068, 1524, 1069, 1518, 1221, 1548, 1047, 1059, 1514, 1521, 1514, 1526, 1513, 1204, 1505, 1507, 2058, 1505, 1507, 1226, 1311, 1310, 1349, 1316, 1313, 1319, 1316, 1305, 1305, 1331, 1349, 882, 1302, 2058, 1306, 1328, 1327, 1312, 1304, 1300, 1298, 1292, 1317, 2058, 1306, 1291, 1208, 1297, 1287, 1283, 1294, 1296, 1306, 1305, 2058, 1324, 1291, 1224, 1285, 1272, 1271, 1278, 1308, 1304, 1263, 1263, 979, 1283, 1279, 1257, 1249, 1260, 1240, 1249, 1241, 976, 1273, 1271, 1224, 1251, 1235, 1230, 1221, 1235, 1229, 2058, 2058, 1200, 1234, 1144, 1118, 1068, 1100, 1076, 2058, 1030, 1036, 1048, 2058, 1049, 1011, 983, 925, 2058, 850, 730, 2058, 302, 250, 209, 2058, 2058, 2058, 1364, 1380, 1396, 1412, 1428, 1444, 1460, 1476, 1492, 1508, 1524, 195, 524, 1534, 881, 1543, 1088, 1238, 1243, 1552, 1562, 1246, 64, 1568, 1584, 1597, 1603, 1615, 1257, 1631, 1647, 1663, 1679, 1695, 1711, 1727, 1741, 1746, 1752 } ; static yyconst flex_int16_t yy_def[746] = { 0, 707, 707, 706, 3, 707, 707, 706, 7, 706, 9, 708, 708, 707, 707, 706, 15, 706, 17, 706, 19, 707, 21, 707, 707, 706, 25, 707, 707, 706, 29, 707, 707, 709, 709, 706, 35, 707, 37, 706, 39, 706, 41, 710, 710, 711, 711, 706, 47, 712, 712, 706, 51, 713, 713, 714, 714, 715, 715, 716, 716, 717, 717, 706, 706, 706, 718, 706, 719, 706, 719, 706, 706, 720, 721, 721, 721, 722, 723, 706, 706, 724, 724, 706, 706, 706, 706, 706, 706, 706, 725, 706, 726, 726, 727, 706, 706, 706, 706, 706, 728, 706, 729, 730, 731, 706, 706, 706, 706, 706, 732, 706, 706, 733, 706, 734, 734, 706, 706, 706, 706, 706, 706, 706, 706, 735, 736, 737, 737, 706, 706, 738, 738, 706, 706, 739, 739, 706, 706, 740, 740, 706, 706, 741, 741, 706, 706, 706, 718, 706, 706, 706, 706, 719, 706, 706, 706, 719, 706, 720, 721, 721, 721, 722, 723, 706, 706, 724, 724, 706, 706, 706, 706, 706, 725, 706, 706, 726, 726, 727, 726, 706, 706, 706, 706, 706, 706, 728, 729, 730, 731, 706, 106, 706, 732, 706, 733, 706, 734, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 735, 736, 736, 737, 706, 706, 706, 706, 706, 738, 706, 706, 706, 706, 706, 739, 706, 706, 706, 706, 706, 740, 706, 706, 706, 706, 706, 741, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 742, 719, 706, 721, 721, 706, 706, 724, 706, 706, 706, 706, 743, 706, 706, 726, 706, 706, 706, 706, 706, 706, 706, 706, 706, 744, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 736, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 742, 742, 719, 706, 706, 721, 721, 706, 724, 706, 706, 706, 743, 706, 706, 726, 706, 706, 706, 706, 706, 706, 706, 706, 706, 744, 744, 706, 706, 706, 706, 706, 706, 706, 706, 736, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 742, 719, 706, 706, 721, 706, 706, 724, 706, 706, 706, 706, 726, 706, 706, 706, 706, 706, 706, 744, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 742, 719, 706, 706, 706, 706, 706, 724, 706, 706, 706, 726, 706, 706, 706, 706, 706, 744, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 742, 719, 706, 706, 706, 706, 706, 724, 706, 706, 726, 706, 744, 706, 706, 706, 706, 706, 706, 706, 742, 719, 706, 706, 706, 706, 724, 706, 706, 726, 706, 744, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 726, 706, 521, 726, 726, 727, 706, 744, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 726, 706, 726, 726, 727, 744, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 726, 744, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 726, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 726, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 745, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 742, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 0, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706 } ; static yyconst flex_int16_t yy_nxt[2117] = { 0, 64, 64, 65, 64, 64, 64, 64, 64, 66, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 67, 64, 64, 64, 68, 68, 68, 68, 68, 64, 64, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 64, 64, 69, 65, 65, 65, 65, 65, 91, 70, 72, 72, 65, 128, 128, 91, 129, 129, 169, 130, 130, 170, 188, 71, 71, 64, 64, 65, 64, 64, 64, 72, 64, 64, 64, 64, 64, 73, 64, 73, 73, 64, 73, 73, 73, 64, 64, 64, 64, 64, 64, 73, 73, 73, 73, 73, 64, 64, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 64, 64, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 74, 74, 74, 64, 64, 64, 64, 64, 64, 74, 75, 76, 74, 74, 64, 64, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 64, 64, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 148, 64, 88, 88, 64, 65, 65, 65, 97, 64, 64, 64, 64, 64, 98, 97, 65, 165, 175, 64, 64, 98, 89, 89, 705, 95, 95, 108, 99, 178, 199, 132, 166, 200, 133, 99, 108, 134, 327, 176, 179, 249, 250, 328, 64, 64, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 132, 64, 136, 133, 64, 137, 134, 704, 138, 64, 64, 64, 64, 64, 251, 136, 325, 319, 137, 64, 64, 138, 140, 140, 144, 141, 141, 145, 142, 142, 146, 144, 178, 180, 145, 147, 359, 146, 320, 573, 703, 288, 147, 179, 64, 64, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 78, 78, 78, 64, 64, 64, 64, 64, 64, 78, 78, 78, 78, 78, 64, 64, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 64, 64, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 79, 64, 64, 64, 80, 80, 80, 80, 80, 64, 64, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 64, 80, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 81, 81, 81, 64, 64, 64, 64, 64, 64, 81, 81, 81, 81, 81, 64, 64, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, 82, 81, 81, 81, 81, 81, 81, 81, 81, 81, 64, 64, 65, 149, 83, 149, 325, 83, 84, 83, 83, 83, 83, 178, 83, 150, 83, 150, 204, 288, 204, 268, 85, 83, 179, 392, 205, 178, 180, 178, 438, 83, 83, 151, 325, 151, 289, 86, 179, 325, 179, 216, 154, 482, 155, 87, 152, 217, 152, 153, 218, 492, 156, 153, 179, 219, 83, 83, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 90, 90, 90, 64, 64, 64, 64, 64, 64, 90, 90, 90, 90, 90, 64, 64, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 64, 64, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 92, 64, 92, 92, 64, 92, 92, 92, 92, 64, 64, 64, 64, 64, 92, 92, 92, 92, 92, 64, 64, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 93, 92, 92, 92, 92, 92, 92, 92, 92, 92, 64, 94, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 100, 100, 100, 64, 64, 64, 64, 64, 64, 100, 100, 100, 100, 100, 64, 64, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 64, 64, 65, 182, 206, 178, 325, 589, 339, 183, 207, 325, 184, 208, 185, 209, 179, 186, 210, 584, 702, 585, 178, 204, 101, 204, 102, 102, 102, 102, 102, 205, 510, 179, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 64, 64, 65, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 103, 103, 103, 103, 64, 64, 64, 64, 64, 103, 103, 103, 103, 103, 64, 64, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 64, 103, 104, 104, 65, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104, 105, 104, 104, 104, 106, 106, 106, 106, 106, 104, 104, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 104, 104, 109, 109, 65, 109, 160, 111, 109, 404, 160, 109, 109, 553, 701, 109, 325, 109, 109, 325, 472, 178, 109, 109, 109, 109, 109, 109, 109, 109, 65, 109, 179, 111, 109, 178, 533, 109, 109, 325, 449, 109, 640, 109, 109, 700, 179, 554, 109, 109, 109, 109, 109, 109, 112, 112, 65, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 113, 113, 113, 112, 112, 112, 112, 112, 112, 113, 113, 113, 113, 113, 112, 112, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, 112, 112, 65, 325, 115, 678, 325, 115, 116, 117, 595, 115, 115, 222, 115, 228, 115, 178, 180, 223, 501, 229, 224, 115, 230, 596, 699, 225, 179, 231, 234, 115, 115, 669, 240, 178, 235, 118, 325, 236, 241, 541, 544, 242, 237, 119, 179, 542, 243, 522, 543, 522, 607, 522, 698, 325, 115, 115, 65, 697, 115, 546, 522, 115, 116, 117, 547, 115, 115, 178, 115, 522, 115, 555, 178, 566, 696, 597, 178, 115, 179, 612, 595, 582, 695, 179, 694, 115, 115, 179, 544, 178, 598, 118, 178, 522, 613, 596, 178, 600, 617, 119, 179, 164, 693, 179, 618, 164, 619, 179, 692, 691, 115, 115, 120, 121, 65, 121, 120, 120, 120, 120, 122, 123, 124, 120, 120, 120, 120, 120, 120, 125, 125, 125, 120, 120, 126, 120, 120, 120, 125, 125, 125, 125, 125, 120, 120, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 120, 120, 190, 190, 690, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 192, 192, 192, 190, 190, 689, 190, 190, 190, 192, 192, 192, 192, 192, 190, 190, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 190, 190, 517, 325, 517, 518, 597, 325, 518, 519, 520, 612, 518, 521, 522, 523, 688, 518, 522, 625, 522, 598, 522, 325, 518, 167, 613, 687, 325, 167, 174, 522, 520, 187, 174, 686, 651, 187, 524, 660, 522, 522, 685, 544, 211, 544, 525, 178, 211, 684, 683, 682, 681, 680, 522, 679, 677, 518, 526, 517, 676, 517, 518, 522, 522, 518, 519, 520, 675, 518, 518, 522, 538, 674, 518, 673, 672, 178, 522, 671, 548, 518, 548, 670, 668, 667, 666, 522, 179, 520, 665, 522, 545, 664, 522, 539, 522, 663, 522, 662, 522, 661, 659, 540, 658, 657, 656, 522, 655, 654, 653, 613, 652, 650, 518, 518, 522, 649, 648, 647, 646, 645, 644, 643, 522, 598, 596, 642, 641, 639, 638, 636, 635, 634, 633, 632, 631, 616, 630, 629, 522, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 96, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 114, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 131, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 135, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 159, 628, 159, 522, 159, 627, 626, 624, 159, 163, 623, 163, 622, 163, 163, 621, 620, 163, 177, 616, 177, 615, 177, 177, 614, 611, 177, 177, 179, 610, 179, 609, 179, 179, 608, 606, 179, 179, 189, 189, 605, 604, 189, 189, 190, 603, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 602, 190, 190, 190, 194, 601, 194, 194, 599, 594, 593, 194, 592, 591, 590, 194, 194, 196, 196, 588, 587, 196, 198, 586, 198, 198, 583, 581, 198, 580, 579, 578, 522, 577, 198, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 576, 212, 212, 214, 214, 214, 214, 575, 574, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 220, 220, 220, 220, 572, 571, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 226, 226, 226, 226, 570, 569, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 232, 232, 232, 232, 568, 567, 232, 232, 232, 232, 232, 232, 232, 232, 232, 232, 238, 238, 238, 238, 565, 564, 238, 563, 238, 238, 238, 238, 238, 238, 238, 238, 324, 562, 324, 324, 324, 324, 324, 324, 324, 324, 324, 324, 324, 324, 324, 324, 336, 561, 336, 560, 336, 559, 336, 336, 336, 336, 558, 557, 336, 349, 556, 552, 551, 349, 349, 637, 550, 637, 549, 637, 545, 537, 536, 535, 534, 532, 531, 530, 529, 528, 527, 516, 515, 514, 513, 512, 511, 509, 508, 507, 506, 505, 504, 503, 502, 500, 499, 498, 258, 497, 496, 495, 494, 493, 320, 491, 490, 489, 488, 487, 486, 485, 484, 483, 481, 480, 479, 478, 477, 476, 475, 474, 473, 471, 470, 469, 468, 467, 466, 465, 464, 463, 462, 461, 460, 459, 458, 457, 456, 455, 454, 453, 452, 451, 450, 448, 447, 446, 445, 444, 443, 442, 441, 440, 439, 437, 436, 435, 434, 433, 432, 431, 430, 429, 428, 427, 426, 425, 424, 423, 422, 421, 420, 419, 418, 417, 416, 415, 414, 413, 412, 411, 410, 409, 408, 407, 406, 405, 403, 402, 401, 400, 399, 398, 397, 396, 395, 394, 393, 325, 391, 390, 389, 388, 387, 386, 385, 384, 383, 382, 381, 380, 379, 378, 377, 376, 375, 374, 373, 372, 371, 370, 369, 368, 367, 366, 365, 364, 363, 362, 361, 360, 358, 357, 356, 355, 354, 353, 352, 351, 350, 348, 347, 346, 345, 344, 343, 342, 341, 340, 338, 337, 335, 334, 333, 332, 331, 330, 329, 326, 325, 323, 322, 321, 318, 317, 316, 315, 314, 313, 312, 311, 310, 309, 308, 307, 306, 305, 304, 303, 302, 301, 300, 299, 298, 297, 296, 295, 294, 293, 292, 291, 290, 288, 287, 286, 285, 284, 283, 282, 281, 280, 279, 278, 197, 277, 276, 275, 274, 273, 272, 271, 270, 269, 267, 266, 265, 264, 263, 262, 261, 260, 259, 258, 257, 256, 255, 254, 253, 252, 248, 247, 246, 245, 244, 239, 233, 227, 221, 215, 213, 203, 202, 201, 197, 195, 193, 191, 181, 173, 172, 171, 168, 162, 161, 158, 157, 706, 65, 65, 63, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706 } ; static yyconst flex_int16_t yy_chk[2117] = { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 27, 13, 14, 27, 4, 13, 14, 28, 53, 54, 28, 53, 54, 84, 53, 54, 84, 729, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 718, 11, 23, 24, 11, 31, 32, 43, 33, 11, 11, 11, 11, 11, 33, 34, 44, 79, 91, 11, 11, 34, 23, 24, 703, 31, 32, 43, 33, 92, 116, 55, 79, 116, 55, 34, 44, 55, 255, 91, 92, 154, 154, 255, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 56, 12, 57, 56, 12, 57, 56, 702, 57, 12, 12, 12, 12, 12, 154, 58, 555, 249, 58, 12, 12, 58, 59, 60, 61, 59, 60, 61, 59, 60, 61, 62, 93, 93, 62, 61, 289, 62, 249, 555, 701, 289, 62, 93, 12, 12, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 21, 67, 21, 69, 325, 21, 21, 21, 21, 21, 21, 177, 21, 67, 21, 69, 121, 213, 121, 180, 21, 21, 177, 325, 121, 178, 178, 180, 392, 21, 21, 67, 392, 69, 213, 21, 178, 472, 180, 130, 69, 449, 69, 21, 67, 130, 69, 719, 130, 472, 69, 719, 449, 130, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 37, 98, 122, 268, 573, 573, 268, 98, 122, 492, 98, 122, 98, 122, 268, 98, 122, 569, 699, 569, 544, 204, 37, 204, 37, 37, 37, 37, 37, 204, 492, 544, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 45, 45, 45, 45, 721, 45, 45, 339, 721, 45, 45, 532, 698, 45, 510, 45, 45, 625, 438, 339, 45, 45, 45, 45, 45, 45, 46, 46, 46, 46, 339, 46, 46, 404, 510, 46, 46, 438, 404, 46, 625, 46, 46, 696, 404, 532, 46, 46, 46, 46, 46, 46, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47, 49, 669, 49, 669, 660, 49, 49, 49, 579, 49, 49, 134, 49, 138, 49, 482, 482, 134, 482, 138, 134, 49, 138, 579, 695, 134, 482, 138, 142, 49, 49, 660, 146, 547, 142, 49, 589, 142, 146, 519, 547, 146, 142, 49, 547, 519, 146, 518, 519, 518, 589, 518, 694, 533, 49, 49, 50, 693, 50, 524, 518, 50, 50, 50, 525, 50, 50, 524, 50, 518, 50, 533, 525, 546, 691, 580, 546, 50, 524, 594, 596, 566, 690, 525, 689, 50, 50, 546, 600, 566, 580, 50, 582, 518, 594, 596, 600, 582, 601, 50, 566, 723, 687, 582, 601, 723, 601, 600, 686, 685, 50, 50, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 106, 106, 684, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 683, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 501, 607, 501, 501, 598, 640, 501, 501, 501, 613, 501, 501, 501, 501, 682, 501, 520, 607, 520, 598, 520, 651, 501, 724, 613, 681, 678, 724, 725, 520, 501, 728, 725, 677, 640, 728, 501, 651, 520, 521, 676, 521, 735, 521, 501, 501, 735, 675, 674, 673, 672, 671, 521, 670, 668, 501, 501, 517, 667, 517, 517, 521, 520, 517, 517, 517, 666, 517, 517, 517, 517, 665, 517, 664, 663, 521, 526, 662, 526, 517, 526, 661, 659, 658, 657, 521, 521, 517, 656, 526, 538, 655, 538, 517, 538, 654, 538, 653, 526, 652, 650, 517, 649, 647, 646, 538, 645, 644, 643, 642, 641, 639, 517, 517, 538, 638, 636, 635, 634, 633, 632, 631, 526, 630, 629, 628, 626, 624, 623, 622, 621, 620, 619, 618, 617, 616, 615, 614, 538, 707, 707, 707, 707, 707, 707, 707, 707, 707, 707, 707, 707, 707, 707, 707, 707, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 708, 709, 709, 709, 709, 709, 709, 709, 709, 709, 709, 709, 709, 709, 709, 709, 709, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 710, 711, 711, 711, 711, 711, 711, 711, 711, 711, 711, 711, 711, 711, 711, 711, 711, 712, 712, 712, 712, 712, 712, 712, 712, 712, 712, 712, 712, 712, 712, 712, 712, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 713, 714, 714, 714, 714, 714, 714, 714, 714, 714, 714, 714, 714, 714, 714, 714, 714, 715, 715, 715, 715, 715, 715, 715, 715, 715, 715, 715, 715, 715, 715, 715, 715, 716, 716, 716, 716, 716, 716, 716, 716, 716, 716, 716, 716, 716, 716, 716, 716, 717, 717, 717, 717, 717, 717, 717, 717, 717, 717, 717, 717, 717, 717, 717, 717, 720, 612, 720, 611, 720, 609, 608, 606, 720, 722, 605, 722, 604, 722, 722, 603, 602, 722, 726, 599, 726, 597, 726, 726, 595, 593, 726, 726, 727, 592, 727, 591, 727, 727, 590, 588, 727, 727, 730, 730, 587, 586, 730, 730, 731, 585, 731, 731, 731, 731, 731, 731, 731, 731, 731, 731, 584, 731, 731, 731, 732, 583, 732, 732, 581, 578, 577, 732, 576, 575, 574, 732, 732, 733, 733, 572, 571, 733, 734, 570, 734, 734, 568, 565, 734, 564, 563, 562, 561, 560, 734, 736, 736, 736, 736, 736, 736, 736, 736, 736, 736, 736, 736, 736, 558, 736, 736, 737, 737, 737, 737, 557, 556, 737, 737, 737, 737, 737, 737, 737, 737, 737, 737, 738, 738, 738, 738, 554, 553, 738, 738, 738, 738, 738, 738, 738, 738, 738, 738, 739, 739, 739, 739, 552, 551, 739, 739, 739, 739, 739, 739, 739, 739, 739, 739, 740, 740, 740, 740, 550, 549, 740, 740, 740, 740, 740, 740, 740, 740, 740, 740, 741, 741, 741, 741, 545, 543, 741, 542, 741, 741, 741, 741, 741, 741, 741, 741, 742, 541, 742, 742, 742, 742, 742, 742, 742, 742, 742, 742, 742, 742, 742, 742, 743, 540, 743, 539, 743, 537, 743, 743, 743, 743, 536, 535, 743, 744, 534, 531, 530, 744, 744, 745, 529, 745, 528, 745, 523, 516, 515, 514, 512, 509, 508, 506, 505, 503, 502, 499, 497, 496, 495, 494, 493, 491, 490, 489, 488, 487, 485, 484, 483, 481, 480, 479, 478, 477, 476, 475, 474, 473, 471, 470, 469, 468, 467, 466, 461, 459, 455, 453, 448, 447, 445, 444, 443, 442, 441, 440, 439, 437, 436, 435, 434, 433, 432, 431, 428, 425, 422, 420, 419, 417, 415, 414, 412, 411, 410, 409, 408, 407, 406, 403, 402, 400, 399, 398, 397, 396, 395, 394, 393, 391, 390, 389, 387, 386, 385, 384, 381, 380, 379, 376, 375, 374, 371, 370, 369, 366, 365, 364, 361, 360, 359, 358, 357, 354, 353, 350, 348, 347, 346, 345, 344, 341, 338, 337, 336, 335, 332, 331, 330, 329, 328, 327, 326, 324, 322, 321, 319, 318, 317, 316, 315, 314, 313, 312, 311, 310, 309, 308, 307, 306, 305, 304, 303, 302, 301, 300, 299, 298, 297, 296, 295, 294, 293, 292, 291, 290, 287, 286, 285, 284, 283, 281, 280, 279, 278, 277, 276, 275, 274, 273, 272, 271, 270, 269, 267, 266, 263, 262, 261, 260, 259, 257, 256, 254, 253, 252, 251, 250, 248, 247, 246, 245, 243, 242, 241, 240, 239, 237, 236, 235, 234, 233, 231, 230, 229, 228, 227, 225, 224, 223, 222, 221, 219, 218, 217, 216, 215, 212, 210, 209, 208, 207, 206, 203, 202, 200, 199, 197, 196, 195, 193, 191, 186, 185, 184, 183, 182, 181, 176, 175, 173, 172, 171, 170, 169, 168, 166, 165, 162, 161, 158, 157, 156, 155, 152, 151, 150, 149, 148, 145, 141, 137, 133, 129, 126, 119, 118, 117, 113, 111, 108, 105, 95, 89, 87, 86, 82, 76, 75, 71, 70, 63, 2, 1, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int tagYY_flex_debug; int tagYY_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *tagYYtext; #line 1 "doxytag.l" /****************************************************************************** * * $Id: doxytag.l,v 1.27 2001/03/19 19:27:40 root Exp $ * * Copyright (C) 1997-2010 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ #line 19 "doxytag.l" /* * includes */ #include <stdio.h> #include <assert.h> #include <ctype.h> #include "qtbc.h" #include <qstrlist.h> #include <qfileinfo.h> #include <qfile.h> #include <qdict.h> #include <qtextstream.h> #include <qdir.h> #include "version.h" //#include "suffixtree.h" //#include "searchindex.h" #include "logos.h" static QCString convertToXML(const char *s) { QCString result; if (s==0) return result; const char *p=s; char c; while ((c=*p++)) { switch (c) { case '<': result+="&lt;"; break; case '>': result+="&gt;"; break; case '&': result+="&amp;"; break; case '\'': result+="&apos;"; break; case '"': result+="&quot;"; break; default: result+=c; break; } } return result; } struct MemberDef { QCString name; QCString anchor; QCString args; }; struct ClassDef { QCString name; QStrList bases; QCString fileName; bool isFile; QList<MemberDef> memberList; }; QList<ClassDef> classList; QDict<ClassDef> classDict(1009); QList<ClassDef> fileList; QDict<ClassDef> fileDict(1009); static bool genTag; static bool genIndex; static QStrList bases; static QCString inputString; static int inputPosition; static QCString yyFileName; static int yyLineNr; static QCString classFile; static QCString memberRef; static QCString memberName; static QCString memberArgs; static QCString className; static QCString baseName; static QCString docBaseLink; static QCString docAnchor; static QCString docRefName; static bool nameBug; //static SearchIndex searchIndex; #define YY_NEVER_INTERACTIVE 1 /* ----------------------------------------------------------------- */ #undef YY_INPUT #define YY_INPUT(buf,result,max_size) result=yyread(buf,max_size); static int yyread(char *buf,int max_size) { int c=0; while( c < max_size && inputString[inputPosition] ) { *buf = inputString[inputPosition++] ; c++; buf++; } return c; } static void addClass(const char *clName) { if (classDict[clName]==0) { //printf("addClass(%s)\n",clName); ClassDef *cd=new ClassDef; cd->name=clName; cd->fileName=yyFileName; cd->isFile=FALSE; classList.append(cd); classDict.insert(clName,cd); } } static void addFile(const char *fName) { if (classDict[fName]==0) { ClassDef *fd=new ClassDef; fd->name=fName; fd->fileName=yyFileName; fd->isFile=TRUE; classList.append(fd); classDict.insert(fName,fd); } } static void addBases(const char *clName) { ClassDef *cd=0; if (clName && (cd=classDict[clName])) cd->bases=bases; } static void addMember(const char *memName,const char *memRef,const char *memArgs) { //printf("addMember(%s,%s,%s)\n",memName,memRef,memArgs); ClassDef *cd=classList.last(); if (cd) { MemberDef *md; md=new MemberDef; md->name=memName; md->anchor=memRef; md->args=memArgs; cd->memberList.append(md); } else { //printf("Warning: found member %s %s but not class was found to insert it!\n", // memName,memArgs); } } static void addReference() { //printf("addReference() key: %s ref:%s\n", // docRefName.data(),(docBaseLink+"#"+docAnchor).data()); //if (genIndex && !docRefName.isEmpty() && !docBaseLink.isEmpty()) //{ // if (docAnchor.isEmpty()) // searchIndex.addReference(docRefName,docBaseLink); // else // searchIndex.addReference(docRefName,docBaseLink+"#"+docAnchor); // searchIndex.addWord(docRefName,docRefName,TRUE); //} } QCString unhtmlify(const char *str) { QCString result; const char *p=str; char c; while ((c=*p)!='\0') { if (c!='&') { result+=c; p++; } else { if (strncmp(p,"&amp;",5)==0) { result+='&'; p+=5; } else if (strncmp(p,"&lt;",4)==0) { result+='<'; p+=4; } else if (strncmp(p,"&gt;",4)==0) { result+='>'; p+=4; } else if (strncmp(p,"&quot;",6)==0) { result+='"'; p+=4; } else /* should not happen */ { result+='&'; p++; } } } return result; } #line 1410 "<stdout>" #define INITIAL 0 #define Start 1 #define SearchClassFile 2 #define ReadClassFile 3 #define CheckClassName 4 #define ReadClassName 5 #define SearchMemberRef 6 #define ReadMemberRef 7 #define SearchMemberName 8 #define ReadMemberName 9 #define ReadOperator 10 #define SearchBaseClasses 11 #define ReadBaseClass 12 #define SearchRefName 13 #define ReadRefName 14 #define SearchArgs 15 #define ReadArgs 16 #define SearchWords 17 #define SkipHTMLTag 18 #define CheckConstructor 19 #define SkipPreformated 20 #define Qt3ReadType 21 #define Qt3ReadAnchor 22 #define Qt3ReadName 23 #define Qt3ReadOperator 24 #define Qt3ReadArgs 25 #define DoxReadAnchor 26 #define DoxReadName 27 #define DoxReadArgs 28 #define DoxClassName 29 #define DoxClassBase 30 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int tagYYlex_destroy (void ); int tagYYget_debug (void ); void tagYYset_debug (int debug_flag ); YY_EXTRA_TYPE tagYYget_extra (void ); void tagYYset_extra (YY_EXTRA_TYPE user_defined ); FILE *tagYYget_in (void ); void tagYYset_in (FILE * in_str ); FILE *tagYYget_out (void ); void tagYYset_out (FILE * out_str ); yy_size_t tagYYget_leng (void ); char *tagYYget_text (void ); int tagYYget_lineno (void ); void tagYYset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int tagYYwrap (void ); #else extern int tagYYwrap (void ); #endif #endif static void yyunput (int c,char *buf_ptr ); #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( tagYYtext, tagYYleng, 1, tagYYout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( tagYYin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( tagYYin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, tagYYin))==0 && ferror(tagYYin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(tagYYin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int tagYYlex (void); #define YY_DECL int tagYYlex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after tagYYtext and tagYYleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ if ( tagYYleng > 0 ) \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \ (tagYYtext[tagYYleng - 1] == '\n'); \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 241 "doxytag.l" #line 1628 "<stdout>" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! tagYYin ) tagYYin = stdin; if ( ! tagYYout ) tagYYout = stdout; if ( ! YY_CURRENT_BUFFER ) { tagYYensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = tagYY_create_buffer(tagYYin,YY_BUF_SIZE ); } tagYY_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of tagYYtext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_current_state += YY_AT_BOL(); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 707 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 2058 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 243 "doxytag.l" { BEGIN( SearchClassFile ); } YY_BREAK case 2: #line 247 "doxytag.l" case 3: #line 248 "doxytag.l" case 4: #line 249 "doxytag.l" case 5: YY_RULE_SETUP #line 249 "doxytag.l" { // Qt variant BEGIN( ReadClassName ); } YY_BREAK case 6: YY_RULE_SETUP #line 252 "doxytag.l" { // Doxygen variant BEGIN( ReadClassName ); } YY_BREAK case 7: YY_RULE_SETUP #line 255 "doxytag.l" { //printf("Inherits found\n"); BEGIN( SearchBaseClasses ); } YY_BREAK case 8: *yy_cp = (yy_hold_char); /* undo effects of setting up tagYYtext */ (yy_c_buf_p) = yy_cp = yy_bp + 15; YY_DO_BEFORE_ACTION; /* set up tagYYtext again */ YY_RULE_SETUP #line 259 "doxytag.l" { // needed due to inconsistency in the Qt docs BEGIN( CheckConstructor ); } YY_BREAK /* --------------------------------------------------- */ /* Qt member extraction rules */ case 9: YY_RULE_SETUP #line 266 "doxytag.l" { BEGIN( Qt3ReadType ); } YY_BREAK case 10: YY_RULE_SETUP #line 269 "doxytag.l" { // Qt-3.3+ html file BEGIN( Qt3ReadAnchor ); } YY_BREAK case 11: YY_RULE_SETUP #line 272 "doxytag.l" { // Qt-4 html file BEGIN( Qt3ReadAnchor ); } YY_BREAK case 12: YY_RULE_SETUP #line 275 "doxytag.l" { BEGIN( Qt3ReadAnchor ); } YY_BREAK case 13: YY_RULE_SETUP #line 278 "doxytag.l" YY_BREAK case 14: YY_RULE_SETUP #line 279 "doxytag.l" { memberRef = tagYYtext; } YY_BREAK case 15: YY_RULE_SETUP #line 282 "doxytag.l" { BEGIN( Qt3ReadName ); } YY_BREAK case 16: YY_RULE_SETUP #line 285 "doxytag.l" { BEGIN( Start ); } YY_BREAK case 17: YY_RULE_SETUP #line 288 "doxytag.l" { memberName="operator"; BEGIN(Qt3ReadOperator); } YY_BREAK case 18: YY_RULE_SETUP #line 292 "doxytag.l" { memberName+=tagYYtext; } YY_BREAK case 19: YY_RULE_SETUP #line 293 "doxytag.l" { memberName+="<"; } YY_BREAK case 20: YY_RULE_SETUP #line 294 "doxytag.l" { memberName+=">"; } YY_BREAK case 21: YY_RULE_SETUP #line 295 "doxytag.l" { memberName+=" new"; } YY_BREAK case 22: YY_RULE_SETUP #line 296 "doxytag.l" { memberName+=" delete"; } YY_BREAK case 23: YY_RULE_SETUP #line 297 "doxytag.l" { memberName+="()"; BEGIN( Qt3ReadArgs ); } YY_BREAK case 24: YY_RULE_SETUP #line 298 "doxytag.l" { unput(*tagYYtext); BEGIN( Qt3ReadArgs ); } YY_BREAK case 25: YY_RULE_SETUP #line 299 "doxytag.l" { memberName=tagYYtext; memberName=memberName.mid(memberName.find("::")+2); BEGIN(Qt3ReadArgs); } YY_BREAK case 26: YY_RULE_SETUP #line 304 "doxytag.l" YY_BREAK case 27: YY_RULE_SETUP #line 305 "doxytag.l" { memberArgs+='('; } YY_BREAK case 28: YY_RULE_SETUP #line 308 "doxytag.l" { memberArgs+='&'; } YY_BREAK case 29: YY_RULE_SETUP #line 309 "doxytag.l" { memberArgs+='<'; } YY_BREAK case 30: YY_RULE_SETUP #line 310 "doxytag.l" { memberArgs+='>'; } YY_BREAK case 31: YY_RULE_SETUP #line 311 "doxytag.l" { memberArgs+='"'; } YY_BREAK case 32: YY_RULE_SETUP #line 312 "doxytag.l" { memberArgs+=' '; } YY_BREAK case 33: YY_RULE_SETUP #line 313 "doxytag.l" { addMember(memberName,memberRef,memberArgs); memberName.resize(0); memberRef.resize(0); memberArgs.resize(0); BEGIN(Start); } YY_BREAK case 34: /* rule 34 can match eol */ YY_RULE_SETUP #line 320 "doxytag.l" YY_BREAK case 35: YY_RULE_SETUP #line 321 "doxytag.l" { memberArgs+=')'; addMember(memberName,memberRef,memberArgs); memberName.resize(0); memberRef.resize(0); memberArgs.resize(0); BEGIN(Start); } YY_BREAK case 36: YY_RULE_SETUP #line 329 "doxytag.l" { memberArgs+=tagYYtext; } YY_BREAK case 37: YY_RULE_SETUP #line 330 "doxytag.l" { memberArgs+=*tagYYtext; } YY_BREAK /* --------------------------------------------------- */ /* Doxygen class extraction rules */ case 38: YY_RULE_SETUP #line 335 "doxytag.l" { className.resize(0); BEGIN(DoxClassName); } YY_BREAK case 39: /* rule 39 can match eol */ YY_RULE_SETUP #line 339 "doxytag.l" { className=tagYYtext; addClass(className); } YY_BREAK case 40: YY_RULE_SETUP #line 343 "doxytag.l" { className+='<'; } YY_BREAK case 41: YY_RULE_SETUP #line 346 "doxytag.l" { className+='>'; } YY_BREAK case 42: YY_RULE_SETUP #line 349 "doxytag.l" { className+='&'; } YY_BREAK case 43: YY_RULE_SETUP #line 352 "doxytag.l" { className+='"'; } YY_BREAK case 44: YY_RULE_SETUP #line 355 "doxytag.l" { className+=*tagYYtext; } YY_BREAK case 45: YY_RULE_SETUP #line 358 "doxytag.l" { BEGIN(Start); } YY_BREAK /* --------------------------------------------------- */ /* Doxygen inheritance extraction rules */ case 46: YY_RULE_SETUP #line 365 "doxytag.l" { bases.clear(); baseName.resize(0); BEGIN(DoxClassBase); } YY_BREAK case 47: /* rule 47 can match eol */ YY_RULE_SETUP #line 370 "doxytag.l" { baseName+=tagYYtext; } YY_BREAK case 48: YY_RULE_SETUP #line 373 "doxytag.l" { bases.append(baseName); baseName.resize(0); } YY_BREAK case 49: YY_RULE_SETUP #line 377 "doxytag.l" { baseName+='<'; } YY_BREAK case 50: YY_RULE_SETUP #line 380 "doxytag.l" { baseName+='>'; } YY_BREAK case 51: YY_RULE_SETUP #line 383 "doxytag.l" { baseName+='&'; } YY_BREAK case 52: YY_RULE_SETUP #line 386 "doxytag.l" { baseName+='"'; } YY_BREAK case 53: YY_RULE_SETUP #line 389 "doxytag.l" { baseName+=*tagYYtext; } YY_BREAK case 54: YY_RULE_SETUP #line 392 "doxytag.l" { bases.append(baseName); baseName.resize(0); addBases(className); BEGIN(Start); } YY_BREAK /* --------------------------------------------------- */ /* Doxygen member extraction rules */ case 55: YY_RULE_SETUP #line 402 "doxytag.l" { memberName.resize(0); BEGIN(DoxReadName); } YY_BREAK case 56: /* rule 56 can match eol */ YY_RULE_SETUP #line 406 "doxytag.l" { memberName+=tagYYtext; } YY_BREAK case 57: YY_RULE_SETUP #line 409 "doxytag.l" { memberName+='<'; } YY_BREAK case 58: YY_RULE_SETUP #line 412 "doxytag.l" { memberName+='>'; } YY_BREAK case 59: YY_RULE_SETUP #line 415 "doxytag.l" { memberName+='&'; } YY_BREAK case 60: YY_RULE_SETUP #line 418 "doxytag.l" { memberName+='"'; } YY_BREAK case 61: YY_RULE_SETUP #line 421 "doxytag.l" { memberName+=*tagYYtext; } YY_BREAK case 62: YY_RULE_SETUP #line 424 "doxytag.l" { memberName=memberName.mid(memberName.find("::")+2); memberRef.resize(0); BEGIN(DoxReadAnchor); } YY_BREAK case 63: /* rule 63 can match eol */ YY_RULE_SETUP #line 429 "doxytag.l" { memberRef+=tagYYtext; } YY_BREAK case 64: YY_RULE_SETUP #line 432 "doxytag.l" { memberRef+='<'; } YY_BREAK case 65: YY_RULE_SETUP #line 435 "doxytag.l" { memberRef+='>'; } YY_BREAK case 66: YY_RULE_SETUP #line 438 "doxytag.l" { memberRef+='&'; } YY_BREAK case 67: YY_RULE_SETUP #line 441 "doxytag.l" { memberRef+='"'; } YY_BREAK case 68: YY_RULE_SETUP #line 444 "doxytag.l" { memberRef+=*tagYYtext; } YY_BREAK case 69: YY_RULE_SETUP #line 447 "doxytag.l" { memberArgs.resize(0); BEGIN(DoxReadArgs); } YY_BREAK case 70: /* rule 70 can match eol */ YY_RULE_SETUP #line 451 "doxytag.l" { memberArgs+=tagYYtext; } YY_BREAK case 71: YY_RULE_SETUP #line 454 "doxytag.l" { memberArgs+='<'; } YY_BREAK case 72: YY_RULE_SETUP #line 457 "doxytag.l" { memberArgs+='>'; } YY_BREAK case 73: YY_RULE_SETUP #line 460 "doxytag.l" { memberArgs+='&'; } YY_BREAK case 74: YY_RULE_SETUP #line 463 "doxytag.l" { memberArgs+='"'; } YY_BREAK case 75: YY_RULE_SETUP #line 466 "doxytag.l" { memberArgs+=*tagYYtext; } YY_BREAK case 76: YY_RULE_SETUP #line 469 "doxytag.l" { addMember(memberName,memberRef,memberArgs); memberName.resize(0); memberRef.resize(0); memberArgs.resize(0); BEGIN(Start); } YY_BREAK /** --------------------------------------------------- */ case 77: YY_RULE_SETUP #line 479 "doxytag.l" { BEGIN( SkipPreformated ); } YY_BREAK case 78: YY_RULE_SETUP #line 482 "doxytag.l" { BEGIN( SearchWords ); } YY_BREAK case 79: YY_RULE_SETUP #line 485 "doxytag.l" { BEGIN( SkipHTMLTag ); } YY_BREAK case 80: YY_RULE_SETUP #line 488 "doxytag.l" YY_BREAK case 81: YY_RULE_SETUP #line 489 "doxytag.l" { //printf("tag: %s#%s ref: %s word: `%s'\n", // docBaseLink.data(),docAnchor.data(), // docRefName.data(),tagYYtext); //if (genIndex && !docRefName.isEmpty() && tagYYleng>2) // searchIndex.addWord(docRefName, // tagYYtext,FALSE // ); } YY_BREAK case 82: YY_RULE_SETUP #line 498 "doxytag.l" { BEGIN( Start ); } YY_BREAK case 83: YY_RULE_SETUP #line 501 "doxytag.l" YY_BREAK case 84: YY_RULE_SETUP #line 502 "doxytag.l" { QCString s=tagYYtext; if (s.find("::")!=-1) { docRefName=tagYYtext; addReference(); nameBug=TRUE; } else { nameBug=FALSE; } BEGIN( Start ); } YY_BREAK case 85: YY_RULE_SETUP #line 516 "doxytag.l" { docAnchor = tagYYtext; if (docAnchor=="details" || docAnchor=="_details") { docRefName=className.copy(); addReference(); BEGIN( Start ); } else { BEGIN( SearchRefName ); } } YY_BREAK case 86: YY_RULE_SETUP #line 530 "doxytag.l" { BEGIN( ReadRefName ); } YY_BREAK case 87: YY_RULE_SETUP #line 533 "doxytag.l" { // HACK: avoid finding links in code fragments BEGIN( Start ); } YY_BREAK case 88: YY_RULE_SETUP #line 536 "doxytag.l" { // HACK: deal with Qt code if (nameBug) BEGIN( Start ); else BEGIN( ReadRefName ); } YY_BREAK case 89: YY_RULE_SETUP #line 543 "doxytag.l" { // hmm, looks impressive :-) docRefName=unhtmlify(tagYYtext); addReference(); BEGIN( Start ); } YY_BREAK case 90: YY_RULE_SETUP #line 548 "doxytag.l" { //printf("ReadRef=%s\n",tagYYtext); docRefName=tagYYtext; addReference(); BEGIN( Start ); } YY_BREAK case 91: YY_RULE_SETUP #line 554 "doxytag.l" { //printf("Search %s\n",tagYYtext); BEGIN( ReadBaseClass ); } YY_BREAK case 92: /* rule 92 can match eol */ YY_RULE_SETUP #line 558 "doxytag.l" { addBases(className); BEGIN( Start ); } YY_BREAK case 93: YY_RULE_SETUP #line 562 "doxytag.l" { bases.append(tagYYtext); BEGIN( SearchBaseClasses ); } YY_BREAK case 94: YY_RULE_SETUP #line 566 "doxytag.l" { BEGIN( ReadClassFile ); } YY_BREAK case 95: YY_RULE_SETUP #line 569 "doxytag.l" { BEGIN( ReadClassFile ); } YY_BREAK case 96: YY_RULE_SETUP #line 572 "doxytag.l" { className=tagYYtext; BEGIN( CheckClassName); } YY_BREAK case 97: YY_RULE_SETUP #line 576 "doxytag.l" { //printf("className=%s\n",className.data()); addClass(className); BEGIN( Start ); } YY_BREAK case 98: YY_RULE_SETUP #line 581 "doxytag.l" { //printf("className=%s\n",className.data()); addFile(className); BEGIN( Start ); } YY_BREAK case 99: YY_RULE_SETUP #line 586 "doxytag.l" { // not a class file className.resize(0); BEGIN( Start ); } YY_BREAK case 100: YY_RULE_SETUP #line 590 "doxytag.l" { classFile=tagYYtext; BEGIN( SearchMemberRef ); } YY_BREAK case 101: YY_RULE_SETUP #line 594 "doxytag.l" { if (YY_START==ReadClassFile) { classFile=yyFileName; } //BEGIN( ReadMemberRef ); BEGIN( Start ); } YY_BREAK case 102: YY_RULE_SETUP #line 602 "doxytag.l" { memberRef=tagYYtext; BEGIN( SearchMemberName ); } YY_BREAK case 103: YY_RULE_SETUP #line 606 "doxytag.l" { // <strong> is for qt-1.44, <b> is for qt-2.00 BEGIN( ReadMemberName ); } YY_BREAK case 104: YY_RULE_SETUP #line 609 "doxytag.l" { unput(*tagYYtext); BEGIN( ReadMemberName ); } YY_BREAK case 105: YY_RULE_SETUP #line 613 "doxytag.l" { memberName="operator"; BEGIN( ReadOperator ); } YY_BREAK case 106: YY_RULE_SETUP #line 617 "doxytag.l" { memberName+=*tagYYtext; } YY_BREAK case 107: YY_RULE_SETUP #line 618 "doxytag.l" { memberName+="<"; } YY_BREAK case 108: YY_RULE_SETUP #line 619 "doxytag.l" { memberName+=">"; } YY_BREAK case 109: YY_RULE_SETUP #line 620 "doxytag.l" { memberName+=" new"; } YY_BREAK case 110: YY_RULE_SETUP #line 621 "doxytag.l" { memberName+=" delete"; } YY_BREAK case 111: YY_RULE_SETUP #line 622 "doxytag.l" { BEGIN( SearchArgs ); } YY_BREAK case 112: YY_RULE_SETUP #line 623 "doxytag.l" { memberName=tagYYtext; BEGIN( SearchArgs ); } YY_BREAK case 113: YY_RULE_SETUP #line 627 "doxytag.l" { //printf("SearchArg className=%s memberName=%s\n",className.data(),memberName.data()); if (!className.isEmpty() && !memberName.isEmpty()) BEGIN( ReadArgs ); else BEGIN( Start ); } YY_BREAK case 114: YY_RULE_SETUP #line 634 "doxytag.l" { memberArgs+='&'; } YY_BREAK case 115: YY_RULE_SETUP #line 635 "doxytag.l" { memberArgs+='<'; } YY_BREAK case 116: YY_RULE_SETUP #line 636 "doxytag.l" { memberArgs+='>'; } YY_BREAK case 117: YY_RULE_SETUP #line 637 "doxytag.l" { memberArgs+='"'; } YY_BREAK case 118: YY_RULE_SETUP #line 638 "doxytag.l" { memberArgs+=' '; } YY_BREAK /* <ReadArgs>[{}] { // handle enums memberArgs.resize(0); addMember(memberName,memberRef,memberArgs); if (*tagYYtext=='}') BEGIN( Start ); else BEGIN( SearchClassFile ); } */ case 119: /* rule 119 can match eol */ YY_RULE_SETUP #line 649 "doxytag.l" { //printf("adding member %s\n",memberName.data()); memberArgs=memberArgs.stripWhiteSpace(); //if (newClass) //{ // newClass=FALSE; // addClass(className); //} addMember(memberName,memberRef,memberArgs); memberName.resize(0); memberRef.resize(0); memberArgs.resize(0); if (*tagYYtext=='<') BEGIN( SkipHTMLTag); else BEGIN( Start ); } YY_BREAK case 120: YY_RULE_SETUP #line 666 "doxytag.l" { memberArgs+=(*tagYYtext)&0x7f; } YY_BREAK case 121: YY_RULE_SETUP #line 667 "doxytag.l" { BEGIN( Start ); } YY_BREAK case 122: YY_RULE_SETUP #line 668 "doxytag.l" YY_BREAK case 123: YY_RULE_SETUP #line 669 "doxytag.l" YY_BREAK case 124: /* rule 124 can match eol */ YY_RULE_SETUP #line 670 "doxytag.l" { yyLineNr++; if (YY_START!=SkipHTMLTag) BEGIN( Start ); } YY_BREAK case 125: YY_RULE_SETUP #line 674 "doxytag.l" ECHO; YY_BREAK #line 2635 "<stdout>" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(Start): case YY_STATE_EOF(SearchClassFile): case YY_STATE_EOF(ReadClassFile): case YY_STATE_EOF(CheckClassName): case YY_STATE_EOF(ReadClassName): case YY_STATE_EOF(SearchMemberRef): case YY_STATE_EOF(ReadMemberRef): case YY_STATE_EOF(SearchMemberName): case YY_STATE_EOF(ReadMemberName): case YY_STATE_EOF(ReadOperator): case YY_STATE_EOF(SearchBaseClasses): case YY_STATE_EOF(ReadBaseClass): case YY_STATE_EOF(SearchRefName): case YY_STATE_EOF(ReadRefName): case YY_STATE_EOF(SearchArgs): case YY_STATE_EOF(ReadArgs): case YY_STATE_EOF(SearchWords): case YY_STATE_EOF(SkipHTMLTag): case YY_STATE_EOF(CheckConstructor): case YY_STATE_EOF(SkipPreformated): case YY_STATE_EOF(Qt3ReadType): case YY_STATE_EOF(Qt3ReadAnchor): case YY_STATE_EOF(Qt3ReadName): case YY_STATE_EOF(Qt3ReadOperator): case YY_STATE_EOF(Qt3ReadArgs): case YY_STATE_EOF(DoxReadAnchor): case YY_STATE_EOF(DoxReadName): case YY_STATE_EOF(DoxReadArgs): case YY_STATE_EOF(DoxClassName): case YY_STATE_EOF(DoxClassBase): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed tagYYin at a new source and called * tagYYlex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = tagYYin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( tagYYwrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * tagYYtext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of tagYYlex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ tagYYrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; tagYYrestart(tagYYin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) tagYYrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); yy_current_state += YY_AT_BOL(); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 707 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 707 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 706); return yy_is_jam ? 0 : yy_current_state; } static void yyunput (int c, register char * yy_bp ) { register char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up tagYYtext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register yy_size_t number_to_move = (yy_n_chars) + 2; register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; register char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ tagYYrestart(tagYYin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( tagYYwrap( ) ) return 0; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve tagYYtext */ (yy_hold_char) = *++(yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n'); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void tagYYrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ tagYYensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = tagYY_create_buffer(tagYYin,YY_BUF_SIZE ); } tagYY_init_buffer(YY_CURRENT_BUFFER,input_file ); tagYY_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void tagYY_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * tagYYpop_buffer_state(); * tagYYpush_buffer_state(new_buffer); */ tagYYensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; tagYY_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (tagYYwrap()) processing, but the only time this flag * is looked at is after tagYYwrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void tagYY_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; tagYYin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE tagYY_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) tagYYalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in tagYY_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) tagYYalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in tagYY_create_buffer()" ); b->yy_is_our_buffer = 1; tagYY_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with tagYY_create_buffer() * */ void tagYY_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) tagYYfree((void *) b->yy_ch_buf ); tagYYfree((void *) b ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a tagYYrestart() or at EOF. */ static void tagYY_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; tagYY_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then tagYY_init_buffer was _probably_ * called from tagYYrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void tagYY_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) tagYY_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void tagYYpush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; tagYYensure_buffer_stack(); /* This block is copied from tagYY_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from tagYY_switch_to_buffer. */ tagYY_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void tagYYpop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; tagYY_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { tagYY_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void tagYYensure_buffer_stack (void) { yy_size_t num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)tagYYalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in tagYYensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)tagYYrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in tagYYensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE tagYY_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) tagYYalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in tagYY_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; tagYY_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to tagYYlex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * tagYY_scan_bytes() instead. */ YY_BUFFER_STATE tagYY_scan_string (yyconst char * yystr ) { return tagYY_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to tagYYlex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE tagYY_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) tagYYalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in tagYY_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = tagYY_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in tagYY_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up tagYYtext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ tagYYtext[tagYYleng] = (yy_hold_char); \ (yy_c_buf_p) = tagYYtext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ tagYYleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int tagYYget_lineno (void) { return tagYYlineno; } /** Get the input stream. * */ FILE *tagYYget_in (void) { return tagYYin; } /** Get the output stream. * */ FILE *tagYYget_out (void) { return tagYYout; } /** Get the length of the current token. * */ yy_size_t tagYYget_leng (void) { return tagYYleng; } /** Get the current token. * */ char *tagYYget_text (void) { return tagYYtext; } /** Set the current line number. * @param line_number * */ void tagYYset_lineno (int line_number ) { tagYYlineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see tagYY_switch_to_buffer */ void tagYYset_in (FILE * in_str ) { tagYYin = in_str ; } void tagYYset_out (FILE * out_str ) { tagYYout = out_str ; } int tagYYget_debug (void) { return tagYY_flex_debug; } void tagYYset_debug (int bdebug ) { tagYY_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from tagYYlex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT tagYYin = stdin; tagYYout = stdout; #else tagYYin = (FILE *) 0; tagYYout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * tagYYlex_init() */ return 0; } /* tagYYlex_destroy is for both reentrant and non-reentrant scanners. */ int tagYYlex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ tagYY_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; tagYYpop_buffer_state(); } /* Destroy the stack itself. */ tagYYfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * tagYYlex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *tagYYalloc (yy_size_t size ) { return (void *) malloc( size ); } void *tagYYrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void tagYYfree (void * ptr ) { free( (char *) ptr ); /* see tagYYrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 674 "doxytag.l" /*@ ---------------------------------------------------------------------------- */ void parse(QCString &s) { bases.clear(); nameBug = FALSE; //newClass = TRUE; inputString = s; inputPosition = 0; yyLineNr = 0; tagYYrestart( tagYYin ); BEGIN( Start ); tagYYlex(); //printf("Number of lines scanned: %d\n",yyLineNr); } void parseFile(QFileInfo &fi) { printf("Parsing file %s...\n",fi.fileName().data()); QFile f; f.setName(fi.absFilePath()); if (f.open(IO_ReadOnly)) { yyFileName = fi.fileName(); className.resize(0); memberName.resize(0); //printf("Parsing file %s...\n",fi.fileName().data()); QCString input(fi.size()+1); docBaseLink=fi.fileName(); docRefName=fi.fileName().copy(); //searchIndex.addReference(docRefName,docBaseLink); //searchIndex.addWord(docRefName,docRefName,TRUE); f.readBlock(input.data(),fi.size()); input.at(fi.size())='\0'; parse(input); } else { fprintf(stderr,"Warning: Cannot open file %s\n",fi.fileName().data()); } } void parseFileOrDir(const char *fileName) { QFileInfo fi(fileName); if (fi.exists()) { if (fi.isFile()) { parseFile(fi); } else if (fi.isDir()) { QDir dir(fileName); dir.setFilter( QDir::Files ); dir.setNameFilter( "*.html" ); const QFileInfoList *list = dir.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *cfi; for ( it.toFirst() ; (cfi=it.current()) ; ++it) { if (cfi->isFile()) { parseFile(*cfi); } } } } else { fprintf(stderr,"Warning: File %s does not exist\n",fileName); } } void usage(const char *name) { fprintf(stderr,"Doxytag version %s\nCopyright Dimitri van Heesch 1997-2010\n\n", versionString); fprintf(stderr," Generates a tag file and/or a search index for a set of HTML files\n\n"); fprintf(stderr,"Usage: %s [-t tag_file] [ html_file [html_file...] ]\n",name); fprintf(stderr,"Options:\n"); fprintf(stderr," -t <tag_file> Generate tag file <tag_file>.\n"); fprintf(stderr,"If no HTML files are given all files in the current dir that\n" "have a .html extension are parsed.\n\n"); exit(1); } const char *getArg(int argc,char **argv,int &optind,const char c) { char *s=0; if (strlen(&argv[optind][2])>0) s=&argv[optind][2]; else if (optind+1<argc) s=argv[++optind]; else { fprintf(stderr,"option -%c requires an argument\n",c); exit(1); } return s; } int main(int argc,char **argv) { QCString tagName; QCString indexName; int optind=1; const char *arg; while (optind<argc && argv[optind][0]=='-') { switch(argv[optind][1]) { case 't': arg=getArg(argc,argv,optind,'t'); tagName=arg; break; case 's': arg=getArg(argc,argv,optind,'s'); indexName=arg; break; case 'h': case '?': usage(argv[0]); break; default: fprintf(stderr,"Unknown option -%c\n",argv[optind][1]); usage(argv[0]); } optind++; } genTag = !tagName.isEmpty(); genIndex = !indexName.isEmpty(); if (!genTag && !genIndex) { fprintf(stderr,"Nothing to do !\n\n"); usage(argv[0]); } int i; if (optind>=argc) { parseFileOrDir("."); } else { for (i=optind;i<argc;i++) { parseFileOrDir(argv[i]); } } if (genIndex) { fprintf(stderr,"Error: doxytag cannot be used to generate a search index anymore.\n" "This functionality has been integrated into doxygen.\n"); // printf("Writing search index\n"); // if (!searchIndex.saveIndex(indexName)) // { // fprintf(stderr,"Error: Could not write search index\n"); // } // QFileInfo fi(indexName); // if (fi.exists()) // { // QCString dir=convertToQCString(fi.dir().absPath()); // fi.setFile(dir+"/search.png"); // if (!fi.exists()) writeSearchButton(dir); // fi.setFile(dir+"/doxygen.png"); // if (!fi.exists()) writeLogo(dir); // fi.setFile(dir+"/search.cgi"); // if (!fi.exists()) // { // QFile f; // f.setName(dir+"/search.cgi"); // if (f.open(IO_WriteOnly)) // { // QTextStream t(&f); // t << "#!/bin/sh" << endl // << "DOXYSEARCH=" << endl // << "DOXYPATH=" << endl // << "if [ -f $DOXYSEARCH ]" << endl // << "then" << endl // << " $DOXYSEARCH $DOXYPATH" << endl // << "else" << endl // << " echo \"Content-Type: text/html\"" << endl // << " echo \"\"" << endl // << " echo \"<H1>Error: $DOXYSEARCH not found. Check cgi script!\"" << endl // << "fi" << endl; // f.close(); // } // else // { // fprintf(stderr,"Error: could not open file %s for writing\n",(dir+"/search.cgi").data()); // } // } // } } if (genTag) { QFile f; f.setName(tagName); if (f.open(IO_WriteOnly)) { QTextStream t(&f); t << "<tagfile>" << endl; ClassDef *cd=classList.first(); while (cd) { t << " <compound kind=\""; if (cd->isFile) t << "file"; else t << "class"; t << "\">" << endl; t << " <name>" << convertToXML(cd->name) << "</name>" << endl; char *base=cd->bases.first(); while (base) { t << " <base>" << convertToXML(base) << "</base>" << endl; base=cd->bases.next(); } t << " <filename>" << convertToXML(cd->fileName) << "</filename>" << endl; MemberDef *md=cd->memberList.first(); while (md) { if (md->anchor.right(5)=="-enum") { t << " <member kind=\"enum\">" << endl; } else { t << " <member kind=\"function\">" << endl; } t << " <name>" << convertToXML(md->name) << "</name>" << endl; t << " <anchor>" << convertToXML(md->anchor) << "</anchor>" << endl; t << " <arglist>" << convertToXML(md->args) << "</arglist>" << endl; t << " </member>" << endl; md=cd->memberList.next(); } t << " </compound>" << endl; cd=classList.next(); } t << "</tagfile>" << endl; } else { fprintf(stderr,"Error: Could not write tag file %s\n",tagName.data()); } } return 0; } extern "C" { int tagYYwrap() { return 1 ; } };
TextusData/Mover
thirdparty/doxygen-1.7.1/src/doxytag.cpp
C++
gpl-3.0
116,429
/******************************************************************************* File: PulseSignal.cpp Project: OpenSonATA Authors: The OpenSonATA code is the result of many programmers over many years Copyright 2011 The SETI Institute OpenSonATA 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. OpenSonATA 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 OpenSonATA. If not, see<http://www.gnu.org/licenses/>. Implementers of this code are requested to include the caption "Licensed through SETI" with a link to setiQuest.org. For alternate licensing arrangements, please contact The SETI Institute at www.seti.org or setiquest.org. *******************************************************************************/ // // Pulse signal class // // $Header: /home/cvs/nss/sonata-pkg/dx/lib/PulseSignal.cpp,v 1.3 2009/02/22 04:41:42 kes Exp $ // #include <fftw3.h> #include "System.h" #include "PulseSignal.h" using std::cout; using namespace sonata_lib; namespace dx { PulseSignal::PulseSignal(PulseSignalHeader *sig_) { int32_t pulses = sig_->train.numberOfPulses; size_t len = sizeof(PulseSignalHeader) + pulses * sizeof(Pulse); PartitionSet *partitionSet = PartitionSet::getInstance(); blk = partitionSet->alloc(len); Assert(blk); signal = static_cast<PulseSignalHeader *> (blk->getData()); *signal = *sig_; // cout << "PulseSignal, signal " << *signal; Pulse *dp = (Pulse *) (signal + 1); Pulse *sp = (Pulse *) (sig_ + 1); for (int32_t i = 0; i < pulses; ++i) dp[i] = sp[i]; } PulseSignal::~PulseSignal() { blk->free(); } PulseSignal * PulseSignal::getPulse() { return (this); } void PulseSignal::setConfirmationStats(ConfirmationStats& cfm_) { signal->cfm = cfm_; } PulseSignalHeader * PulseSignal::getSignal() { // Debug(DEBUG_NEVER, (void *) signal, "signal"); return (signal); } SignalDescription& PulseSignal::getSignalDescription() { return (signal->sig); } SignalId& PulseSignal::getSignalId() { return (signal->sig.signalId); } SignalId& PulseSignal::getOrigSignalId() { return (signal->sig.origSignalId); } void PulseSignal::setClass(SignalClass sigClass_) { signal->sig.sigClass = sigClass_; } void PulseSignal::setReason(SignalClassReason reason_) { signal->sig.reason = reason_; } SignalClass PulseSignal::getClass() { return (signal->sig.sigClass); } SignalClassReason PulseSignal::getReason() { return (signal->sig.reason); } ConfirmationStats * PulseSignal::getConfirmationStats() { return (&signal->cfm); } float64_t PulseSignal::getRfFreq() { return (signal->sig.path.rfFreq); } float32_t PulseSignal::getDrift() { return (signal->sig.path.drift); } float32_t PulseSignal::getWidth() { return (signal->sig.path.width); } float32_t PulseSignal::getPower() { return (signal->sig.path.power); } Resolution PulseSignal::getResolution() { return (signal->train.res); } }
jonr925/SonATA
sig-pkg/dx/lib/PulseSignal.cpp
C++
gpl-3.0
3,309
/** * Copyright 2011 The ARIES Consortium (http://www.ariesonline.org) and * www.integratedmodelling.org. This file is part of Thinklab. Thinklab 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. Thinklab 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 Thinklab. If not, see <http://www.gnu.org/licenses/>. */ package org.integratedmodelling.corescience.transformations; import org.integratedmodelling.thinklab.interfaces.annotations.DataTransformation; import org.integratedmodelling.thinklab.transformations.ITransformation; @DataTransformation(id="log10plus1") public class Log10Plus1 implements ITransformation { @Override public double transform(Object value, Object[] parameters) { return Math.log10((Double)value + 1.0); } }
ariesteam/thinklab
plugins/org.integratedmodelling.thinklab.corescience/src/org/integratedmodelling/corescience/transformations/Log10Plus1.java
Java
gpl-3.0
1,243
#region License Information (GPL v3) /* ShareX - A program that allows you to take screenshots and share any file type Copyright (c) 2007-2022 ShareX Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Optionally you can also view the license at <http://www.gnu.org/licenses/>. */ #endregion License Information (GPL v3) using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; namespace ShareX.HelpersLib { public class GradientInfo { [DefaultValue(LinearGradientMode.Vertical)] public LinearGradientMode Type { get; set; } public List<GradientStop> Colors { get; set; } [JsonIgnore] public bool IsValid => Colors != null && Colors.Count > 0; [JsonIgnore] public bool IsVisible => IsValid && Colors.Any(x => x.Color.A > 0); [JsonIgnore] public bool IsTransparent => IsValid && Colors.Any(x => x.Color.IsTransparent()); public GradientInfo() { Type = LinearGradientMode.Vertical; Colors = new List<GradientStop>(); } public GradientInfo(params GradientStop[] colors) : this() { Colors = colors.ToList(); } public GradientInfo(params Color[] colors) : this() { for (int i = 0; i < colors.Length; i++) { Colors.Add(new GradientStop(colors[i], (int)Math.Round(100f / (colors.Length - 1) * i))); } } public void Clear() { Colors.Clear(); } public void Sort() { Colors.Sort((x, y) => x.Location.CompareTo(y.Location)); } public void Reverse() { Colors.Reverse(); foreach (GradientStop color in Colors) { color.Location = 100 - color.Location; } } public ColorBlend GetColorBlend() { List<GradientStop> colors = new List<GradientStop>(Colors.OrderBy(x => x.Location)); if (!colors.Any(x => x.Location == 0)) { colors.Insert(0, new GradientStop(colors[0].Color, 0f)); } if (!colors.Any(x => x.Location == 100)) { colors.Add(new GradientStop(colors[colors.Count - 1].Color, 100f)); } ColorBlend colorBlend = new ColorBlend(); colorBlend.Colors = colors.Select(x => x.Color).ToArray(); colorBlend.Positions = colors.Select(x => x.Location / 100).ToArray(); return colorBlend; } public LinearGradientBrush GetGradientBrush(Rectangle rect) { LinearGradientBrush brush = new LinearGradientBrush(rect, Color.Transparent, Color.Transparent, Type); brush.InterpolationColors = GetColorBlend(); return brush; } public void Draw(Graphics g, Rectangle rect) { if (IsValid) { try { using (LinearGradientBrush brush = GetGradientBrush(new Rectangle(0, 0, rect.Width, rect.Height))) { g.FillRectangle(brush, rect); } } catch { } } } public void Draw(Image img) { if (IsValid) { using (Graphics g = Graphics.FromImage(img)) { Draw(g, new Rectangle(0, 0, img.Width, img.Height)); } } } public Bitmap CreateGradientPreview(int width, int height, bool border = false, bool checkers = false) { Bitmap bmp = new Bitmap(width, height); Rectangle rect = new Rectangle(0, 0, width, height); using (Graphics g = Graphics.FromImage(bmp)) { if (checkers && IsTransparent) { using (Image checker = ImageHelpers.CreateCheckerPattern()) using (Brush checkerBrush = new TextureBrush(checker, WrapMode.Tile)) { g.FillRectangle(checkerBrush, rect); } } Draw(g, rect); if (border) { g.DrawRectangleProper(Pens.Black, rect); } } return bmp; } public override string ToString() { return "Gradient"; } } }
L1Q/ShareX
ShareX.HelpersLib/Colors/GradientInfo.cs
C#
gpl-3.0
5,390
<?php /** * @package Arastta eCommerce * @copyright 2015-2017 Arastta Association. All rights reserved. * @copyright See CREDITS.txt for credits and other copyright notices. * @license GNU GPL version 3; see LICENSE.txt * @link https://arastta.org */ class ControllerCommonForgotten extends Controller { private $error = array(); public function index() { if ($this->user->isLogged() && isset($this->request->get['token']) && ($this->request->get['token'] == $this->session->data['token'])) { $this->response->redirect($this->url->link('common/dashboard', '', 'SSL')); } if (!$this->config->get('config_password')) { $this->response->redirect($this->url->link('common/login', '', 'SSL')); } $this->load->language('common/forgotten'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('user/user'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->load->language('mail/forgotten'); $code = sha1(uniqid(mt_rand(), true)); $this->model_user_user->editCode($this->request->post['email'], $code); $subject = sprintf($this->language->get('text_subject'), $this->config->get('config_name')); $message = sprintf($this->language->get('text_greeting'), $this->config->get('config_name')) . "\n\n"; $message .= $this->language->get('text_change') . "\n\n"; $message .= $this->url->link('common/reset', 'code=' . $code, 'SSL') . "\n\n"; $message .= sprintf($this->language->get('text_ip'), $this->request->server['REMOTE_ADDR']) . "\n\n"; $mail = new Mail($this->config->get('config_mail')); $mail->setTo(html_entity_decode($this->request->post['email'], ENT_QUOTES, 'UTF-8')); $mail->setFrom(html_entity_decode($this->config->get('config_email'), ENT_QUOTES, 'UTF-8')); $mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8')); $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8')); $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8')); $mail->send(); $this->session->data['success'] = $this->language->get('text_success'); $args = ''; if (!empty($this->request->post['admin_keyword'])) { $args = '&' . $this->request->post['admin_keyword']; } $this->response->redirect($this->url->link('common/login', $args, 'SSL')); } $data['heading_title'] = $this->language->get('heading_title'); $data['text_your_email'] = $this->language->get('text_your_email'); $data['text_email'] = $this->language->get('text_email'); $data['entry_email'] = $this->language->get('entry_email'); $data['button_reset'] = $this->language->get('button_reset'); $data['button_cancel'] = $this->language->get('button_cancel'); if (isset($this->error['warning'])) { $data['error_warning'] = $this->error['warning']; } else { $data['error_warning'] = ''; } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', '', 'SSL') ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('common/forgotten', 'token=' . '', 'SSL') ); $data['action'] = $this->url->link('common/forgotten', '', 'SSL'); $data['cancel'] = $this->url->link('common/login', '', 'SSL'); if (isset($this->request->post['email'])) { $data['email'] = $this->request->post['email']; } else { $data['email'] = ''; } $this->load->model('tool/image'); if ($this->config->get('config_image') && is_file(DIR_IMAGE . $this->config->get('config_image'))) { $data['thumb'] = $this->model_tool_image->resize($this->config->get('config_image'), 85, 85); } else { $data['thumb'] = $this->model_tool_image->resize('no_image.png', 85, 85); } $data['store'] = array( 'name' => $this->config->get('config_name'), 'href' => ($this->request->server['HTTPS']) ? HTTPS_CATALOG : HTTP_CATALOG ); $data['admin_keyword'] = ''; if ($this->config->get('config_sec_admin_keyword')) { if (isset($this->request->get[$this->config->get('config_sec_admin_keyword')])) { $data['admin_keyword'] = $this->config->get('config_sec_admin_keyword'); } } $data['header'] = $this->load->controller('common/header'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('common/forgotten.tpl', $data)); } protected function validate() { if (!isset($this->request->post['email'])) { $this->error['warning'] = $this->language->get('error_email'); } elseif (!$this->model_user_user->getTotalUsersByEmail($this->request->post['email'])) { $this->error['warning'] = $this->language->get('error_email'); } return !$this->error; } }
cuneytsenturk/arastta
admin/controller/common/forgotten.php
PHP
gpl-3.0
5,502
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM 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. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. ************************************************************************/ Espo.define('Views.Email.Record.DetailQuick', 'Views.Email.Record.Detail', function (Dep, Detail) { return Dep.extend({ isWide: true, sideView: false, init: function () { Dep.prototype.init.call(this); this.columnCount = 2; }, setup: function () { Dep.prototype.setup.call(this); }, }); });
onerinas/espocrm-3.4.2
frontend/client/src/views/email/record/detail-quick.js
JavaScript
gpl-3.0
1,356
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MindSageWeb.Repositories.Models; using MongoDB.Driver; using Microsoft.Extensions.OptionsModel; namespace MindSageWeb.Repositories { /// <summary> /// ตัวติดต่อกับ notification /// </summary> public class NotificationRepository : INotificationRepository { #region Fields private readonly string TableName; private MongoAccess.MongoUtil _mongoUtil; #endregion Fields #region Constructors /// <summary> /// Initialize repository /// </summary> /// <param name="mongoUtil">Mongo access utility</param> public NotificationRepository(MongoAccess.MongoUtil mongoUtil, IOptions<DatabaseTableOptions> option) { _mongoUtil = mongoUtil; TableName = option.Value.Notifications; } #endregion Constructors #region INotificationRepository members /// <summary> /// ขอข้อมูล notification จากรหัสผู้ใช้และ class room /// </summary> /// <param name="userprofileId">ชื่อผู้ใช้ที่ต้องการค้นหาข้อมูล</param> /// <param name="classRoomId">Class room id</param> public IEnumerable<Notification> GetNotificationByUserIdAndClassRoomId(string userprofileId, string classRoomId) { var qry = _mongoUtil.GetCollection<Notification>(TableName) .Find(it => !it.HideDate.HasValue && it.ClassRoomId == classRoomId && it.ToUserProfileId == userprofileId) .ToEnumerable(); return qry; } /// <summary> /// อัพเดทหรือเพิ่มข้อมูล notification /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void Upsert(Notification data) { var update = Builders<Notification>.Update .Set(it => it.LastReadedDate, data.LastReadedDate) .Set(it => it.LastUpdateDate, data.LastUpdateDate) .Set(it => it.ToUserProfileId, data.ToUserProfileId) .Set(it => it.ClassRoomId, data.ClassRoomId) .Set(it => it.LessonId, data.LessonId) .Set(it => it.CreatedDate, data.CreatedDate) .Set(it => it.HideDate, data.HideDate) .Set(it => it.Message, data.Message) .Set(it => it.ByUserProfileId, data.ByUserProfileId) .Set(it => it.TotalLikes, data.TotalLikes) .Set(it => it.Tag, data.Tag); var updateOption = new UpdateOptions { IsUpsert = true }; _mongoUtil.GetCollection<Notification>(TableName) .UpdateOne(it => it.id == data.id, update, updateOption); } /// <summary> /// เพิ่มข้อมูล notification /// </summary> /// <param name="data">ข้อมูลที่ต้องการดำเนินการ</param> public void Insert(IEnumerable<Notification> data) { if (!data.Any()) return; _mongoUtil.GetCollection<Notification>(TableName) .InsertMany(data); } #endregion INotificationRepository members } }
teerachail/mindsage2016
WebAppSolution/src/MindSageWeb/Repositories/NotificationRepository.cs
C#
gpl-3.0
3,495
<!DOCTYPE html> <html @yield('head-style')> <head> @section('title')<title>Survey-X</title>@show <meta charset="utf-8"> <link rel="stylesheet" href="{{ elixir("css/all.css") }}" /> <script src="{{ elixir("js/all.js") }}"></script> @yield('head') </head> <body> @yield('header') @if($errors->has('page')) <div class="uk-container uk-container-center"> <div class="uk-alert uk-alert-danger"> <a href="" class="uk-alert-close uk-close"></a> <p>{{$errors->first('page')}}</p> </div> </div> @endif <div class="uk-grid"> <div class="uk-width-1-4 uk-conatiner-center"> <div class="uk-panel uk-panel-box uk-margin-large-left uk-margin-bottom"> <ul class="uk-nav uk-nav-side" data-uk-nav> @include("partials.sidebar") @yield('sidenav') <li class="uk-nav-divider"></li> <li class="uk-parent"> <a href="#"><i class="fa fa-info-circle"></i> Hilfe zu diesem Fenster</a> <ul class="uk-nav-sub"> <li><p>@yield('helptext')</p></li> </ul> </li> </ul> </div> </div> <div class="uk-width-3-4">@yield('content')</div> </div> @yield('footer') </body>
dabaer/survey
resources/views/partials/app.blade.php
PHP
gpl-3.0
1,371
// Torc - Copyright 2011-2013 University of Southern California. All Rights Reserved. // $HeadURL$ // $Id$ // 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 HAVE_CONFIG_H #include "torc/generic/config.h" #endif #include "torc/generic/ObjectFactory.hpp" namespace torc { namespace generic { ObjectFactory::ObjectFactory() : Cell::Factory(), Design::Factory(), Library::Factory(), InstanceArray::Factory(), InstanceArrayMember::Factory(), NetBundle::Factory(), ParameterArray::Factory(), PortBundle::Factory(), PortBundleReference::Factory(), Property::Factory(), ParameterArrayElement::Factory(), PortList::Factory(), PortListAlias::Factory(), Root::Factory(), ScalarNet::Factory(), ScalarPort::Factory(), ScalarPortReference::Factory(), SingleInstance::Factory(), SingleParameter::Factory(), Status::Factory(), VectorNet::Factory(), VectorNetBit::Factory(), VectorPort::Factory(), VectorPortBit::Factory(), VectorPortReference::Factory(), VectorPortBitReference::Factory(), View::Factory(), Written::Factory(), Permutable::Factory(), InterfaceJoinedInfo::Factory(), LogicValue::Factory(), SimulationInfo::Factory(), Simulate::Factory(), Apply::Factory(), LogicalResponse::Factory(), LogicElement::Factory(), WaveValue::Factory(), Timing::Factory(), PathDelay::Factory(), Event::Factory(), ForbiddenEvent::Factory() {} ObjectFactory::~ObjectFactory() throw() {} } // namespace generic } // namespace torc
torc-isi/torc
src/torc/generic/ObjectFactory.cpp
C++
gpl-3.0
2,183
/** * */ package org.openwis.datasource.server.service.impl; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.jws.WebParam; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.openwis.dataservice.common.domain.entity.cache.PatternMetadataMapping; import org.openwis.dataservice.common.domain.entity.enumeration.ProductMetadataColumn; import org.openwis.dataservice.common.domain.entity.enumeration.SortDirection; import org.openwis.dataservice.common.domain.entity.request.ProductMetadata; import org.openwis.dataservice.common.domain.entity.request.Request; import org.openwis.dataservice.common.exception.CannotDeleteAllProductMetadataException; import org.openwis.dataservice.common.exception.CannotDeleteProductMetadataException; import org.openwis.dataservice.common.service.ProductMetadataService; import org.openwis.dataservice.common.util.DateTimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Session Bean implementation of class Product metadata service */ @Remote(ProductMetadataService.class) @Stateless(name = "ProductMetadataService") @WebService(targetNamespace = "http://dataservice.openwis.org/", name = "ProductMetadataService", portName = "ProductMetadataServicePort", serviceName = "ProductMetadataService") @SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public class ProductMetadataServiceImpl implements ProductMetadataService { /** The Constant STOP_GAP_GTS_CATEGORY. */ private static final String STOP_GAP_GTS_CATEGORY = "WMO Additional"; /** The Constant STOP_GAP_DATA_POLICY. */ private static final String STOP_GAP_DATA_POLICY = "additional-default"; /** The Constant STOP_GAP_PROCESS. */ private static final String STOP_GAP_PROCESS = "LOCAL"; /** The Constant STOP_GAP_TITLE_TEMPLATE. */ private static final String STOP_GAP_TITLE_TEMPLATE = "[Draft] for {0}"; /** The Constant STOP_GAP_URN_TEMPLATE. */ private static final String STOP_GAP_URN_TEMPLATE = "urn:x-wmo:md:int.wmo.wis::{0}"; /** The logger */ private static Logger logger = LoggerFactory.getLogger(ProductMetadataServiceImpl.class); /** * The entity manager. */ @PersistenceContext private EntityManager entityManager; /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getProductMetadataByUrn(java.lang.String) */ @Override public ProductMetadata getProductMetadataByUrn(@WebParam(name = "productMetadataUrn") String urn) { ProductMetadata result; logger.debug("Get a ProductMetaData by URN: {}", urn); if (urn == null) { throw new IllegalArgumentException("Product Metadata urn must not be null!"); } Query query = entityManager.createNamedQuery("ProductMetadata.FindByUrn").setParameter("urn", urn); try { result = (ProductMetadata) query.getSingleResult(); } catch (NoResultException e) { result = null; } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getProductMetadataById(java.lang.Long) */ @Override public ProductMetadata getProductMetadataById(@WebParam(name = "id") Long id) { ProductMetadata result = null; logger.debug("Get a ProductMetaData by id: {}", id); if (id != null) { result = entityManager.find(ProductMetadata.class, id); } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * getAllProductsMetadata(int, int, org.openwis.dataservice.common.domain.entity.enumeration.ProductMetadataColumn, * org.openwis.dataservice.common.domain.entity.enumeration.SortDirection) */ @SuppressWarnings("unchecked") @Override public List<ProductMetadata> getAllProductsMetadata( @WebParam(name = "firstResult") int firstResult, @WebParam(name = "maxResults") int maxResults, @WebParam(name = "column") ProductMetadataColumn column, @WebParam(name = "sortDirection") SortDirection sortDirection) { List<ProductMetadata> result; logger.debug("Get All ProductMetaData"); // Check arguments if (firstResult < 0) { throw new IllegalArgumentException("FirstResult must be ≥ 0!"); } if (maxResults <= 0) { throw new IllegalArgumentException("MaxResults must be > 0!"); } // Default column is URN ProductMetadataColumn col; if (column != null) { col = column; } else { col = ProductMetadataColumn.URN; } // Default direction is Descending SortDirection dir; if (sortDirection != null) { dir = sortDirection; } else { dir = SortDirection.ASC; } // Create query String q = MessageFormat.format("SELECT pm FROM ProductMetadata pm ORDER BY pm.{0} {1}", col.getAttribute(), dir); Query query = entityManager.createQuery(q); query.setFirstResult(firstResult); query.setMaxResults(maxResults); // Process query try { result = query.getResultList(); } catch (NoResultException e) { result = Collections.emptyList(); } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getLastStopGapMetadata(java.lang.String) */ @SuppressWarnings("unchecked") @Override public List<ProductMetadata> getLastStopGapMetadata(@WebParam(name = "since") String since) { List<ProductMetadata> result = null; Query query = null; try { Date date = DateTimeUtils.parseDateTime(since); query = entityManager.createNamedQuery("ProductMetadata.getLastStopGap"); query.setParameter("since", date); } catch (Exception e) { // ParseException or NullPointerException query = entityManager.createNamedQuery("ProductMetadata.getAllStopGap"); } result = query.getResultList(); return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#createStopGapMetadata(java.lang.String, java.lang.String, java.lang.String, int) */ @Override public Long createStopGapMetadata(@WebParam(name = "ttaaii") String ttaaii, @WebParam(name = "originator") String originator, @WebParam(name = "priority") int priority) { ProductMetadata pm = new ProductMetadata(); pm.setUrn(MessageFormat.format(STOP_GAP_URN_TEMPLATE, ttaaii)); pm.setOriginator(originator); pm.setPriority(priority); pm.setTitle(MessageFormat.format(STOP_GAP_TITLE_TEMPLATE, ttaaii)); pm.setProcess(STOP_GAP_PROCESS); pm.setDataPolicy(STOP_GAP_DATA_POLICY); pm.setGtsCategory(STOP_GAP_GTS_CATEGORY); pm.setStopGap(true); pm.setFed(Boolean.FALSE); pm.setIngested(Boolean.FALSE); pm.setLocalDataSource(""); return createProductMetadata(pm); } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getProductsMetadataCount() */ @Override public int getProductsMetadataCount() { Query query = entityManager.createNamedQuery("ProductMetadata.count"); Number result = (Number) query.getSingleResult(); return result.intValue(); } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * getProductsMetadataByUrns(java.util.List, int, int, * org.openwis.dataservice.common.domain.entity.enumeration.ProductMetadataColumn, * org.openwis.dataservice.common.domain.entity.enumeration.SortDirection) */ @SuppressWarnings("unchecked") @Override public List<ProductMetadata> getProductsMetadataByUrns( @WebParam(name = "urns") List<String> urns, @WebParam(name = "firstResult") int firstResult, @WebParam(name = "maxResults") int maxResults, @WebParam(name = "column") ProductMetadataColumn column, @WebParam(name = "sortDirection") SortDirection sortDirection) { List<ProductMetadata> result; logger.debug("Get ProductsMetaData by URNs: {}", urns); // Check arguments if (firstResult < 0) { throw new IllegalArgumentException("FirstResult must be ≥ 0 !"); } if (maxResults <= 0) { throw new IllegalArgumentException("MaxResults must be > 0 !"); } // Default column is URN ProductMetadataColumn col; if (column != null) { col = column; } else { col = ProductMetadataColumn.URN; } // Default direction is Descending SortDirection dir; if (sortDirection != null) { dir = sortDirection; } else { dir = SortDirection.ASC; } // build URNs if (urns == null || urns.isEmpty()) { result = Collections.emptyList(); } else { // create URN list String allUrns = buildUrns(urns); // Create query String q = MessageFormat .format( "SELECT pm FROM ProductMetadata pm WHERE lower(pm.urn) IN ({0}) ORDER BY pm.{1} {2}", allUrns, col.getAttribute(), dir); Query query = entityManager.createQuery(q); query.setFirstResult(firstResult); query.setMaxResults(maxResults); // Process query try { result = query.getResultList(); } catch (NoResultException e) { result = Collections.emptyList(); } } return result; } /** * Description goes here. * * @param urns the urns * @return the string */ private String buildUrns(List<String> urns) { StringBuffer allUrns = new StringBuffer(); boolean isFirst = true; for (String urn : urns) { if (StringUtils.isNotEmpty(urn)) { if (isFirst) { isFirst = false; } else { allUrns.append(", "); } allUrns.append('\''); allUrns.append(StringEscapeUtils.escapeSql(urn.toLowerCase())); allUrns.append('\''); } } return allUrns.toString(); } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * createProductMetadata(org.openwis.dataservice.common.domain.entity.request.ProductMetadata) */ @Override public Long createProductMetadata( @WebParam(name = "productMetadata") ProductMetadata productMetadata) { if (productMetadata == null) { throw new IllegalArgumentException("ProductMetadata must not being null !"); } // Check URN String urn = productMetadata.getUrn(); if (StringUtils.isEmpty(urn)) { throw new IllegalArgumentException("URN must not being empty !"); } // Check Unicity if (getProductMetadataByUrn(urn) != null) { throw new IllegalArgumentException("A product with the same URN already exists"); } if (productMetadata.getCreationDate() == null) { productMetadata.setCreationDate(DateTimeUtils.getUTCTime()); } logger.info("Creating a ProductMetaData: " + urn); // Creation entityManager.persist(productMetadata); // Get pattern String pmPattern; if (productMetadata.getOverridenFncPattern() != null) { pmPattern = productMetadata.getOverridenFncPattern(); } else { pmPattern = productMetadata.getFncPattern(); } // Handle pattern mapping PatternMetadataMapping pmm; if (StringUtils.isNotBlank(pmPattern)) { // Create pmm = new PatternMetadataMapping(); pmm.setPattern(pmPattern); pmm.setProductMetadata(productMetadata); entityManager.persist(pmm); } entityManager.flush(); return productMetadata.getId(); } /** * Gets the all pattern metadata mapping. * * @return the all pattern metadata mapping */ @SuppressWarnings("unchecked") @Override public List<PatternMetadataMapping> getAllPatternMetadataMapping() { Query query = entityManager.createNamedQuery("PatternMetadataMapping.all"); List<PatternMetadataMapping> result = query.getResultList(); if (result == null) { result = new ArrayList<PatternMetadataMapping>(); } return result; } /** * {@inheritDoc} * @throws CannotDeleteProductMetadataException * @see org.openwis.dataservice.common.service.ProductMetadataService#deleteProductMetadata(java.lang.Long) */ @Override public void deleteProductMetadata(@WebParam(name = "productMetadataId") Long id) { ProductMetadata productMetadata = entityManager.find(ProductMetadata.class, id); if (productMetadata != null) { logger.info("Removing a ProductMetaData: " + productMetadata.getUrn()); PatternMetadataMapping pmm = retrievePatternMetadataMapping(productMetadata); if (pmm != null) { entityManager.remove(pmm); } entityManager.remove(productMetadata); } } /** * Retrieve pattern metadata mapping. * * @param productMetadata the product metadata * @return the pattern metadata mapping */ private PatternMetadataMapping retrievePatternMetadataMapping(ProductMetadata productMetadata) { PatternMetadataMapping result = null; if (productMetadata != null) { Query query = entityManager.createNamedQuery("PatternMetadataMapping.byProductMetadata"); query.setParameter("pm", productMetadata); try { result = (PatternMetadataMapping) query.getSingleResult(); } catch (NoResultException e) { result = null; } } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * updateProductMetadata(org.openwis.dataservice.common.domain.entity.request.ProductMetadata) */ @Override public void updateProductMetadata( @WebParam(name = "productMetadata") ProductMetadata productMetadata) { logger.info("Updating a ProductMetaData: " + productMetadata.getUrn()); entityManager.merge(productMetadata); // Get pattern String pmPattern; if (productMetadata.getOverridenFncPattern() != null) { pmPattern = productMetadata.getOverridenFncPattern(); } else { pmPattern = productMetadata.getFncPattern(); } // Handle pattern mapping PatternMetadataMapping pmm = retrievePatternMetadataMapping(productMetadata); if (pmm == null && StringUtils.isNotBlank(pmPattern)) { // Create pmm = new PatternMetadataMapping(); pmm.setPattern(pmPattern); pmm.setProductMetadata(productMetadata); entityManager.persist(pmm); } else if (pmm != null && !pmm.getPattern().equals(pmPattern)) { if (pmPattern == null) { entityManager.remove(pmm); } else { // need update pmm.setPattern(pmPattern); entityManager.merge(pmm); } } } /** * {@inheritDoc} * @throws CannotDeleteProductMetadataException * @see org.openwis.dataservice.common.service.ProductMetadataService#deleteProductMetadataByURN(java.lang.String) */ @Override public void deleteProductMetadataByURN(@WebParam(name = "productMetadataUrn") String urn) throws CannotDeleteProductMetadataException { ProductMetadata productMetadata = getProductMetadataByUrn(urn); if (productMetadata != null) { // Check delete ability Query query = entityManager.createNamedQuery("Request.byProductMetadata"); query.setParameter("pm", productMetadata); @SuppressWarnings("unchecked") List<Request> lst = query.getResultList(); if (lst.isEmpty()) { deleteProductMetadata(productMetadata.getId()); } else { throw new CannotDeleteProductMetadataException(urn); } } } /** * {@inheritDoc} */ @Override public void deleteProductMetadatasWithURN(List<String> urns) throws CannotDeleteAllProductMetadataException { List<String> metadataThatCouldNotBeDeleted = null; for (String urn : urns) { try { deleteProductMetadataByURN(urn); } catch (CannotDeleteProductMetadataException e) { // Record metadata records that cannot be deleted if (metadataThatCouldNotBeDeleted == null) { metadataThatCouldNotBeDeleted = new ArrayList<String>(); } metadataThatCouldNotBeDeleted.add(urn); } } // The operation did not fully complete, so raise an exception providing the metadata URNs // that could not be deleted. if (metadataThatCouldNotBeDeleted != null) { throw new CannotDeleteAllProductMetadataException(metadataThatCouldNotBeDeleted.toArray(new String[metadataThatCouldNotBeDeleted.size()])); } } }
OpenWIS/openwis
openwis-dataservice/openwis-dataservice-server/openwis-dataservice-server-ejb/src/main/java/org/openwis/datasource/server/service/impl/ProductMetadataServiceImpl.java
Java
gpl-3.0
17,721
using System.Collections.Generic; using System.Threading.Tasks; using Octokit; namespace GithubXamarin.Core.Contracts.Repository { public interface IFileRepository { Task<IEnumerable<RepositoryContent>> GetContentForRepository(long repositoryId, string path, GitHubClient gitHubClient); Task<IEnumerable<RepositoryContent>> GetRootContentForRepository(long repositoryId, GitHubClient githubClient); Task<Readme> GetReadmeForRepository(long repositoryId, GitHubClient authorizedGitHubClient); Task<RepositoryContentChangeSet> CreateFile(long repositoryId, string path, string message, string content, GitHubClient gitHubClient); Task<RepositoryContentChangeSet> UpdateFile(long repositoryId, string path, string message, string content, string sha, GitHubClient gitHubClient); Task DeleteFile(long repositoryId, string path, string message, string sha, GitHubClient gitHubClient); } }
prajjwaldimri/GithubXamarin
GithubXamarin.Core/Contracts/Repository/IFileRepository.cs
C#
gpl-3.0
972
<?php /** * The erase view file of extension module of ZenTaoPMS. * * @copyright Copyright 2009-2012 青岛易软天创网络科技有限公司 (QingDao Nature Easy Soft Network Technology Co,LTD www.cnezsoft.com) * @license LGPL (http://www.gnu.org/licenses/lgpl.html) * @author Chunsheng Wang <chunsheng@cnezsoft.com> * @package extension * @version $Id$ * @link http://www.zentao.net */ ?> <?php include '../../common/view/header.lite.html.php';?> <table class='table-1'> <caption><?php echo $header->title;?></caption> <tr> <td valign='middle'> <?php echo "<h3 class='a-center success'>{$header->title}</h3>"; if($removeCommands) { echo "<p class='strong'>{$lang->extension->unremovedFiles}</p>"; echo join($removeCommands, '<br />'); } echo "<p class='a-center'>" . html::commonButton($lang->extension->viewAvailable, 'onclick=parent.location.href="' . inlink('browse', 'type=available') . '"') . '</p>'; ?> </td> </tr> </table> </body> </html>
isleon/zentao
module/extension/view/erase.html.php
PHP
gpl-3.0
1,061
/* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * 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 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. */ package org.voltdb.quarantine; import java.io.File; import org.voltdb.BackendTarget; import org.voltdb.VoltDB.Configuration; import org.voltdb.client.Client; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcedureCallback; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.compiler.VoltProjectBuilder.GroupInfo; import org.voltdb.compiler.VoltProjectBuilder.ProcedureInfo; import org.voltdb.compiler.VoltProjectBuilder.UserInfo; import org.voltdb.export.ExportTestClient; import org.voltdb.exportclient.ExportClientException; import org.voltdb.quarantine.TestExportSuite; import org.voltdb.regressionsuites.LocalCluster; import org.voltdb.regressionsuites.MultiConfigSuiteBuilder; import org.voltdb.regressionsuites.RegressionSuite; import org.voltdb.regressionsuites.TestOrderBySuite; import org.voltdb.regressionsuites.TestSQLTypesSuite; import org.voltdb.regressionsuites.VoltServerConfig; import org.voltdb.utils.MiscUtils; import org.voltdb.utils.VoltFile; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.Insert; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.InsertAddedTable; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.InsertBase; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.RollbackInsert; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.Update_Export; /** * End to end Export tests using the RawProcessor and the ExportSinkServer. * * Note, this test reuses the TestSQLTypesSuite schema and procedures. * Each table in that schema, to the extent the DDL is supported by the * DB, really needs an Export round trip test. */ public class TestExportSuiteTestExportAndDroppedTableThenShutdown extends RegressionSuite { private ExportTestClient m_tester; /** Shove a table name and pkey in front of row data */ private Object[] convertValsToParams(String tableName, final int i, final Object[] rowdata) { final Object[] params = new Object[rowdata.length + 2]; params[0] = tableName; params[1] = i; for (int ii=0; ii < rowdata.length; ++ii) params[ii+2] = rowdata[ii]; return params; } /** Push pkey into expected row data */ private Object[] convertValsToRow(final int i, final char op, final Object[] rowdata) { final Object[] row = new Object[rowdata.length + 2]; row[0] = (byte)(op == 'I' ? 1 : 0); row[1] = i; for (int ii=0; ii < rowdata.length; ++ii) row[ii+2] = rowdata[ii]; return row; } /** Push pkey into expected row data */ @SuppressWarnings("unused") private Object[] convertValsToLoaderRow(final int i, final Object[] rowdata) { final Object[] row = new Object[rowdata.length + 1]; row[0] = i; for (int ii=0; ii < rowdata.length; ++ii) row[ii+1] = rowdata[ii]; return row; } private void quiesce(final Client client) throws Exception { client.drain(); client.callProcedure("@Quiesce"); } private void quiesceAndVerifyRetryWorkOnIOException(final Client client, ExportTestClient tester) throws Exception { quiesce(client); while (true) { try { tester.work(); } catch (ExportClientException e) { boolean success = reconnect(tester); assertTrue(success); System.out.println(e.toString()); continue; } break; } assertTrue(tester.allRowsVerified()); assertTrue(tester.verifyExportOffsets()); } @Override public void setUp() throws Exception { m_username = "default"; m_password = "password"; VoltFile.recursivelyDelete(new File("/tmp/" + System.getProperty("user.name"))); File f = new File("/tmp/" + System.getProperty("user.name")); f.mkdirs(); super.setUp(); callbackSucceded = true; m_tester = new ExportTestClient(getServerConfig().getNodeCount()); m_tester.addCredentials("export", "export"); try { m_tester.connect(); } catch (ExportClientException e) { e.printStackTrace(); assertTrue(false); } } @Override public void tearDown() throws Exception { super.tearDown(); m_tester.disconnect(); assertTrue(callbackSucceded); } private boolean callbackSucceded = true; class RollbackCallback implements ProcedureCallback { @Override public void clientCallback(ClientResponse clientResponse) { if (clientResponse.getStatus() != ClientResponse.USER_ABORT) { callbackSucceded = false; System.err.println(clientResponse.getException()); } } } private boolean reconnect(ExportTestClient client) throws ExportClientException { for (int ii = 0; ii < 3; ii++) { m_tester.disconnect(); m_tester.reserveVerifiers(); boolean success = client.connect(); if (success) return true; } return false; } // Test Export of a DROPPED table. Queues some data to a table. // Then drops the table and restarts the server. Verifies that Export can successfully // drain the dropped table. IE, drop table doesn't lose Export data. // public void testExportAndDroppedTableThenShutdown() throws Exception { System.out.println("testExportAndDroppedTableThenShutdown"); Client client = getClient(); for (int i=0; i < 10; i++) { final Object[] rowdata = TestSQLTypesSuite.m_midValues; m_tester.addRow( m_tester.m_generationsSeen.first(), "NO_NULLS", i, convertValsToRow(i, 'I', rowdata)); final Object[] params = convertValsToParams("NO_NULLS", i, rowdata); client.callProcedure("Insert", params); } // now drop the no-nulls table final String newCatalogURL = Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.jar"); final String deploymentURL = Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml"); final ClientResponse callProcedure = client.callProcedure("@UpdateApplicationCatalog", newCatalogURL, deploymentURL); assertTrue(callProcedure.getStatus() == ClientResponse.SUCCESS); quiesce(client); m_config.shutDown(); m_config.startUp(false); client = getClient(); /** * There will be 3 disconnects. Once for the shutdown, once for first generation, * another for the 2nd generation created by the catalog change. The predicate is a complex * way of saying make sure that the tester has created verifiers for */ for (int ii = 0; m_tester.m_generationsSeen.size() < 3 || m_tester.m_verifiers.get(m_tester.m_generationsSeen.last()).size() < 6; ii++) { Thread.sleep(500); boolean threwException = false; try { m_tester.work(1000); } catch (ExportClientException e) { boolean success = reconnect(m_tester); assertTrue(success); System.out.println(e.toString()); threwException = true; } if (ii < 3) { assertTrue(threwException); } } for (int i=10; i < 20; i++) { final Object[] rowdata = TestSQLTypesSuite.m_midValues; m_tester.addRow( m_tester.m_generationsSeen.last(), "NO_NULLS", i, convertValsToRow(i, 'I', rowdata)); final Object[] params = convertValsToParams("NO_NULLS", i, rowdata); client.callProcedure("Insert", params); } client.drain(); // must still be able to verify the export data. quiesceAndVerifyRetryWorkOnIOException(client, m_tester); } static final GroupInfo GROUPS[] = new GroupInfo[] { new GroupInfo("export", false, false), new GroupInfo("proc", true, true), new GroupInfo("admin", true, true) }; static final UserInfo[] USERS = new UserInfo[] { new UserInfo("export", "export", new String[]{"export"}), new UserInfo("default", "password", new String[]{"proc"}), new UserInfo("admin", "admin", new String[]{"proc", "admin"}) }; /* * Test suite boilerplate */ static final ProcedureInfo[] PROCEDURES = { new ProcedureInfo( new String[]{"proc"}, Insert.class), new ProcedureInfo( new String[]{"proc"}, InsertBase.class), new ProcedureInfo( new String[]{"proc"}, RollbackInsert.class), new ProcedureInfo( new String[]{"proc"}, Update_Export.class) }; static final ProcedureInfo[] PROCEDURES2 = { new ProcedureInfo( new String[]{"proc"}, Update_Export.class) }; static final ProcedureInfo[] PROCEDURES3 = { new ProcedureInfo( new String[]{"proc"}, InsertAddedTable.class) }; public TestExportSuiteTestExportAndDroppedTableThenShutdown(final String name) { super(name); } public static void main(final String args[]) { org.junit.runner.JUnitCore.runClasses(TestOrderBySuite.class); } static public junit.framework.Test suite() throws Exception { VoltServerConfig config; final MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestExportSuiteTestExportAndDroppedTableThenShutdown.class); VoltProjectBuilder project = new VoltProjectBuilder(); project.setSecurityEnabled(true); project.addGroups(GROUPS); project.addUsers(USERS); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql")); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql")); project.addExport("org.voltdb.export.processors.RawProcessor", true /*enabled*/, java.util.Arrays.asList(new String[]{"export"})); // "WITH_DEFAULTS" is a non-exported persistent table project.setTableAsExportOnly("ALLOW_NULLS"); project.setTableAsExportOnly("NO_NULLS"); project.addPartitionInfo("NO_NULLS", "PKEY"); project.addPartitionInfo("ALLOW_NULLS", "PKEY"); project.addPartitionInfo("WITH_DEFAULTS", "PKEY"); project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY"); project.addPartitionInfo("JUMBO_ROW", "PKEY"); project.addProcedures(PROCEDURES); // JNI, single server // Use the cluster only config. Multiple topologies with the extra catalog for the // Add drop tests is harder. Restrict to the single (complex) topology. // // config = new LocalSingleProcessServer("export-ddl.jar", 2, // BackendTarget.NATIVE_EE_JNI); // config.compile(project); // builder.addServerConfig(config); /* * compile the catalog all tests start with */ config = new LocalCluster("export-ddl-cluster-rep.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true); boolean compile = config.compile(project); assertTrue(compile); builder.addServerConfig(config); /* * compile a catalog without the NO_NULLS table for add/drop tests */ config = new LocalCluster("export-ddl-sans-nonulls.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true); project = new VoltProjectBuilder(); project.addGroups(GROUPS); project.addUsers(USERS); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql")); project.addExport("org.voltdb.export.processors.RawProcessor", true, //enabled java.util.Arrays.asList(new String[]{"export"})); // "WITH_DEFAULTS" is a non-exported persistent table project.setTableAsExportOnly("ALLOW_NULLS"); // and then project builder as normal project.addPartitionInfo("ALLOW_NULLS", "PKEY"); project.addPartitionInfo("WITH_DEFAULTS", "PKEY"); project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY"); project.addPartitionInfo("JUMBO_ROW", "PKEY"); project.addProcedures(PROCEDURES2); compile = config.compile(project); MiscUtils.copyFile(project.getPathToDeployment(), Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml")); assertTrue(compile); /* * compile a catalog with an added table for add/drop tests */ config = new LocalCluster("export-ddl-addedtable.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true); project = new VoltProjectBuilder(); project.addGroups(GROUPS); project.addUsers(USERS); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql")); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql")); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-addedtable-ddl.sql")); project.addExport("org.voltdb.export.processors.RawProcessor", true /*enabled*/, java.util.Arrays.asList(new String[]{"export"})); // "WITH_DEFAULTS" is a non-exported persistent table project.setTableAsExportOnly("ALLOW_NULLS"); // persistent table project.setTableAsExportOnly("ADDED_TABLE"); // persistent table project.setTableAsExportOnly("NO_NULLS"); // streamed table // and then project builder as normal project.addPartitionInfo("ALLOW_NULLS", "PKEY"); project.addPartitionInfo("ADDED_TABLE", "PKEY"); project.addPartitionInfo("WITH_DEFAULTS", "PKEY"); project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY"); project.addPartitionInfo("JUMBO_ROW", "PKEY"); project.addPartitionInfo("NO_NULLS", "PKEY"); project.addProcedures(PROCEDURES); project.addProcedures(PROCEDURES3); compile = config.compile(project); MiscUtils.copyFile(project.getPathToDeployment(), Configuration.getPathToCatalogForTest("export-ddl-addedtable.xml")); assertTrue(compile); return builder; } }
ifcharming/original2.0
tests/frontend/org/voltdb/quarantine/TestExportSuiteTestExportAndDroppedTableThenShutdown.java
Java
gpl-3.0
16,157
//+build gtk_3_6 gtk_3_8 gtk_3_10 gtk_3_12 gtk_3_14 gtk_3_16 gtk_3_18 gtk_deprecated package gtk // #include <gtk/gtk.h> // #include <stdlib.h> import "C" import ( "unsafe" ) /* * GtkRange */ // TODO: // gtk_range_get_min_slider_size(). // gtk_range_set_min_slider_size(). /* * GtkToolbar */ // TODO: // GtkToolbarSpaceStyle /* * GtkFileChooserButton */ // GetFocusOnClick is a wrapper around gtk_file_chooser_button_get_focus_on_click(). func (v *FileChooserButton) GetFocusOnClick() bool { return gobool(C.gtk_file_chooser_button_get_focus_on_click(v.native())) } // SetFocusOnClick is a wrapper around gtk_file_chooser_button_set_focus_on_click(). func (v *FileChooserButton) SetFocusOnClick(grabFocus bool) { C.gtk_file_chooser_button_set_focus_on_click(v.native(), gbool(grabFocus)) } /* * GtkButton */ // GetFocusOnClick is a wrapper around gtk_button_get_focus_on_click(). func (v *Button) GetFocusOnClick() bool { c := C.gtk_button_get_focus_on_click(v.native()) return gobool(c) } // SetFocusOnClick is a wrapper around gtk_button_set_focus_on_click(). func (v *Button) SetFocusOnClick(focusOnClick bool) { C.gtk_button_set_focus_on_click(v.native(), gbool(focusOnClick)) } /* * GtkTextIter */ // BeginsTag is a wrapper around gtk_text_iter_begins_tag(). func (v *TextIter) BeginsTag(v1 *TextTag) bool { return gobool(C.gtk_text_iter_begins_tag(v.native(), v1.native())) } /* * GtkWindow */ // ParseGeometry is a wrapper around gtk_window_parse_geometry(). func (v *Window) ParseGeometry(geometry string) bool { cstr := C.CString(geometry) defer C.free(unsafe.Pointer(cstr)) c := C.gtk_window_parse_geometry(v.native(), (*C.gchar)(cstr)) return gobool(c) } // ResizeToGeometry is a wrapper around gtk_window_resize_to_geometry(). func (v *Window) ResizeToGeometry(width, height int) { C.gtk_window_resize_to_geometry(v.native(), C.gint(width), C.gint(height)) } // SetDefaultGeometry is a wrapper around gtk_window_set_default_geometry(). func (v *Window) SetDefaultGeometry(width, height int) { C.gtk_window_set_default_geometry(v.native(), C.gint(width), C.gint(height)) }
twstrike/coyim
vendor/github.com/gotk3/gotk3/gtk/gtk_deprecated_since_3_20.go
GO
gpl-3.0
2,129
<?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/>. /** * Provides support for the conversion of moodle1 backup to the moodle2 format * * @package mod * @subpackage folder * @copyright 2011 Andrew Davis <andrew@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Folder conversion handler. This resource handler is called by moodle1_mod_resource_handler */ class moodle1_mod_folder_handler extends moodle1_resource_successor_handler { /** @var moodle1_file_manager instance */ protected $fileman = null; /** * Converts /MOODLE_BACKUP/COURSE/MODULES/MOD/RESOURCE data * Called by moodle1_mod_resource_handler::process_resource() */ public function process_legacy_resource($data) { // get the course module id and context id $instanceid = $data['id']; $currentcminfo = $this->get_cminfo($instanceid); $moduleid = $currentcminfo['id']; $contextid = $this->converter->get_contextid(CONTEXT_MODULE, $moduleid); // convert legacy data into the new folder record $folder = array(); $folder['id'] = $data['id']; $folder['name'] = $data['name']; $folder['intro'] = $data['intro']; $folder['introformat'] = $data['introformat']; $folder['revision'] = 1; $folder['timemodified'] = $data['timemodified']; // get a fresh new file manager for this instance $this->fileman = $this->converter->get_file_manager($contextid, 'mod_folder'); // migrate the files embedded into the intro field $this->fileman->filearea = 'intro'; $this->fileman->itemid = 0; $folder['intro'] = moodle1_converter::migrate_referenced_files($folder['intro'], $this->fileman); // migrate the folder files $this->fileman->filearea = 'content'; $this->fileman->itemid = 0; if (empty($data['reference'])) { $this->fileman->migrate_directory('course_files'); } else { $this->fileman->migrate_directory('course_files/'.$data['reference']); } // write folder.xml $this->open_xml_writer("activities/folder_{$moduleid}/folder.xml"); $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $moduleid, 'modulename' => 'folder', 'contextid' => $contextid)); $this->write_xml('folder', $folder, array('/folder/id')); $this->xmlwriter->end_tag('activity'); $this->close_xml_writer(); // write inforef.xml $this->open_xml_writer("activities/folder_{$moduleid}/inforef.xml"); $this->xmlwriter->begin_tag('inforef'); $this->xmlwriter->begin_tag('fileref'); foreach ($this->fileman->get_fileids() as $fileid) { $this->write_xml('file', array('id' => $fileid)); } $this->xmlwriter->end_tag('fileref'); $this->xmlwriter->end_tag('inforef'); $this->close_xml_writer(); } }
orvsd/moodle22
mod/folder/backup/moodle1/lib.php
PHP
gpl-3.0
3,744
# @file plugin.py # # Connect Zen Coding to Pluma. # # Adapted to pluma by Joao Manoel (joaomanoel7@gmail.com) # # Original Author Franck Marcia (franck.marcia@gmail.com) # import pluma, gobject, gtk, os from zen_editor import ZenEditor zencoding_ui_str = """ <ui> <menubar name="MenuBar"> <menu name="EditMenu" action="Edit"> <placeholder name="EditOps_5"> <menu action="ZenCodingMenuAction"> <menuitem name="ZenCodingExpand" action="ZenCodingExpandAction"/> <menuitem name="ZenCodingExpandW" action="ZenCodingExpandWAction"/> <menuitem name="ZenCodingWrap" action="ZenCodingWrapAction"/> <separator/> <menuitem name="ZenCodingInward" action="ZenCodingInwardAction"/> <menuitem name="ZenCodingOutward" action="ZenCodingOutwardAction"/> <menuitem name="ZenCodingMerge" action="ZenCodingMergeAction"/> <separator/> <menuitem name="ZenCodingPrev" action="ZenCodingPrevAction"/> <menuitem name="ZenCodingNext" action="ZenCodingNextAction"/> <separator/> <menuitem name="ZenCodingRemove" action="ZenCodingRemoveAction"/> <menuitem name="ZenCodingSplit" action="ZenCodingSplitAction"/> <menuitem name="ZenCodingComment" action="ZenCodingCommentAction"/> </menu> </placeholder> </menu> </menubar> </ui> """ class ZenCodingPlugin(pluma.Plugin): """A Pluma plugin to implement Zen Coding's HTML and CSS shorthand expander.""" def activate(self, window): actions = [ ('ZenCodingMenuAction', None, '_Zen Coding', None, "Zen Coding tools", None), ('ZenCodingExpandAction', None, '_Expand abbreviation', '<Ctrl>E', "Expand abbreviation to raw HTML/CSS", self.expand_abbreviation), ('ZenCodingExpandWAction', None, 'E_xpand dynamic abbreviation...', '<Ctrl><Alt>E', "Dynamically expand abbreviation as you type", self.expand_with_abbreviation), ('ZenCodingWrapAction', None, '_Wrap with abbreviation...', '<Ctrl><Shift>E', "Wrap with code expanded from abbreviation", self.wrap_with_abbreviation), ('ZenCodingInwardAction', None, 'Balance tag _inward', '<Ctrl><Alt>I', "Select inner tag's content", self.match_pair_inward), ('ZenCodingOutwardAction', None, 'Balance tag _outward', '<Ctrl><Alt>O', "Select outer tag's content", self.match_pair_outward), ('ZenCodingMergeAction', None, '_Merge lines', '<Ctrl><Alt>M', "Merge all lines of the current selection", self.merge_lines), ('ZenCodingPrevAction', None, '_Previous edit point', '<Alt>Left', "Place the cursor at the previous edit point", self.prev_edit_point), ('ZenCodingNextAction', None, '_Next edit point', '<Alt>Right', "Place the cursor at the next edit point", self.next_edit_point), ('ZenCodingRemoveAction', None, '_Remove tag', '<Ctrl><Alt>R', "Remove a tag", self.remove_tag), ('ZenCodingSplitAction', None, 'Split or _join tag', '<Ctrl><Alt>J', "Toggle between single and double tag", self.split_join_tag), ('ZenCodingCommentAction', None, 'Toggle _comment', '<Ctrl><Alt>C', "Toggle an XML or HTML comment", self.toggle_comment) ] windowdata = dict() window.set_data("ZenCodingPluginDataKey", windowdata) windowdata["action_group"] = gtk.ActionGroup("PlumaZenCodingPluginActions") windowdata["action_group"].add_actions(actions, window) manager = window.get_ui_manager() manager.insert_action_group(windowdata["action_group"], -1) windowdata["ui_id"] = manager.add_ui_from_string(zencoding_ui_str) window.set_data("ZenCodingPluginInfo", windowdata) self.editor = ZenEditor() error = self.editor.get_user_settings_error() if error: md = gtk.MessageDialog(window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, "There is an error in user settings:") message = "{0} on line {1} at character {2}\n\nUser settings will not be available." md.set_title("Zen Coding error") md.format_secondary_text(message.format(error['msg'], error['lineno'], error['offset'])) md.run() md.destroy() def deactivate(self, window): windowdata = window.get_data("ZenCodingPluginDataKey") manager = window.get_ui_manager() manager.remove_ui(windowdata["ui_id"]) manager.remove_action_group(windowdata["action_group"]) def update_ui(self, window): view = window.get_active_view() windowdata = window.get_data("ZenCodingPluginDataKey") windowdata["action_group"].set_sensitive(bool(view and view.get_editable())) def expand_abbreviation(self, action, window): self.editor.expand_abbreviation(window) def expand_with_abbreviation(self, action, window): self.editor.expand_with_abbreviation(window) def wrap_with_abbreviation(self, action, window): self.editor.wrap_with_abbreviation(window) def match_pair_inward(self, action, window): self.editor.match_pair_inward(window) def match_pair_outward(self, action, window): self.editor.match_pair_outward(window) def merge_lines(self, action, window): self.editor.merge_lines(window) def prev_edit_point(self, action, window): self.editor.prev_edit_point(window) def next_edit_point(self, action, window): self.editor.next_edit_point(window) def remove_tag(self, action, window): self.editor.remove_tag(window) def split_join_tag(self, action, window): self.editor.split_join_tag(window) def toggle_comment(self, action, window): self.editor.toggle_comment(window)
jmanoel7/pluma-plugins-0
plugins/zencoding/plugin.py
Python
gpl-3.0
6,126
/*global module */ module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { //define the string to go between each file in the concat'd output separator: ';' }, dist: { //files to concatenate src: ['src/**/*.js'], //destination js file dest: 'build/js/<%= pkg.name %>.js' } }, uglify: { options: { // the banner to stamp at top of output banner: '/* <%= pkg.name %> <%= grunt.template.today("dd-mm-yy") %> /* \n' }, dist: { files: { 'build/js/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { //files to lint files: ['Gruntfile.js', 'src/**/*.js'], options: { globals: { jQuery: true, console: true, module: true } } }, compass: { dist: { options: { sassDir: 'src/sass', cssDir: 'build/css' } } }, watch: { css: { files: 'src/sass/*.scss', tasks: ['compass'] }, js: { files: ['src/js/*.js'], tasks: ['jshint', 'uglify', 'concat'] } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.registerTask('default', ['jshint', 'concat', 'uglify', 'compass']); }; //exports
fredericksilva/Mobile-Dropbox-Website-Builder
Gruntfile.js
JavaScript
gpl-3.0
1,990
<?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/>. /** * Resource module admin settings and defaults * * @package mod_label * @copyright 2013 Davo Smith, Synergy Learning * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; if ($ADMIN->fulltree) { $settings->add(new admin_setting_configcheckbox('label/dndmedia', get_string('dndmedia', 'mod_label'), get_string('configdndmedia', 'mod_label'), 1)); $settings->add(new admin_setting_configtext('label/dndresizewidth', get_string('dndresizewidth', 'mod_label'), get_string('configdndresizewidth', 'mod_label'), 400, PARAM_INT, 6)); $settings->add(new admin_setting_configtext('label/dndresizeheight', get_string('dndresizeheight', 'mod_label'), get_string('configdndresizeheight', 'mod_label'), 400, PARAM_INT, 6)); }
murilotimo/moodle
mod/label/settings.php
PHP
gpl-3.0
1,549
<?php // checking for minimum PHP version if (version_compare(PHP_VERSION, '5.3.7', '<')) { exit("Sorry, Simple PHP Login does not run on a PHP version smaller than 5.3.7 !"); } else if (version_compare(PHP_VERSION, '5.5.0', '<')) { // if you are using PHP 5.3 or PHP 5.4 you have to include the password_api_compatibility_library.php // (this library adds the PHP 5.5 password hashing functions to older versions of PHP) require_once("libraries/password_compatibility_library.php"); } // include the configs / constants for the database connection require_once("config/db.php"); // load the login class require_once("classes/Login.php"); // load the functions require_once("includes/functions.php"); // create a login object. when this object is created, it will do all login/logout stuff automatically // so this single line handles the entire login process. in consequence, you can simply ... $login = new Login(); // ... ask if we are logged in here: if ($login->isUserLoggedIn() == true) { // the user is logged in. you can do whatever you want here. // for demonstration purposes, we simply show the "you are logged in" view. //include("views/index_old.php"); ?> <!DOCTYPE html> <html> <?php include "includes/head.php";?> <body> <div id="wrapper"> <nav class="navbar navbar-default navbar-fixed-top" role="navigation" style="margin-bottom: 0"> <?php include 'navbar-header.php'; ?> <!-- /.navbar-top-links --> <?php include 'navbar-top-links.php'; ?> <!-- /.navbar-static-side --> </nav> <div id="page-wrapper"> <?php include 'includes/run_check.php';?> <div class="row"> <div class="col-lg-12"> <h3 class="page-header">Overview</h3> </div> <!-- /.col-lg-12 --> </div> <?php checkuserruns(); ?> <div class = "row"> <div class="col-lg-12"> <h4 class="page-header">News</h4> <div id="newstarget">To get news messages your installation of minoTour must be on a server which can connect to the outside world.<br></div> </div> </div> <div class = "row"> <div class="col-lg-12"> <h4 class="page-header">Important Notice:</h4> <div id="notice">minoTour is a platform in development. It is realeased as an 0.x version and may contain <strong>errors</strong> and <strong>bugs</strong>.<br><br>A rudimentary bug reporting system is included within this application. Please make full use of it.<br><br>In order for bugs and feature requests to be reported we are collecting information from you. The version checks above request information from our central website as to the current version of the tools to notify you if we have made a new release available.<br><br>Alongside this error reporting, we intend to collect usage statistics from you. Every time a new dataset is uploaded into minoTour we will log the username on our own servers along with the date and time. This will allow us to collect usage statistics to support the development of these tools.<br><br>We will <strong>not</strong> store any other information about your run, your run data or any of your personal information. </div> </div> </div> </div> </div> <!-- /#wrapper --> <!-- Core Scripts - Include with every page --> <script src="js/jquery-1.10.2.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/plugins/metisMenu/jquery.metisMenu.js"></script> <!-- Page-Level Plugin Scripts - Dashboard --> <script type="text/javascript" src="js/pnotify.custom.min.js"></script> <script type="text/javascript"> PNotify.prototype.options.styling = "fontawesome"; </script> <script src="js/plugins/morris/raphael-2.1.0.min.js"></script> <script src="js/plugins/morris/morris.js"></script> <!-- SB Admin Scripts - Include with every page --> <script src="js/sb-admin.js"></script> <!-- Page-Level Demo Scripts - Dashboard - Use for reference --> <script src="js/demo/dashboard-demo.js"></script> <script> $( "#infodiv" ).load( "alertcheck.php" ).fadeIn("slow"); eval(document.getElementById("infodiv").innerHTML); var auto_refresh = setInterval(function () { $( "#infodiv" ).load( "alertcheck.php" ).fadeIn("slow"); eval(document.getElementById("infodiv").innerHTML); }, 10000); // refresh every 5000 milliseconds </script> <script> $.getJSON('http://www.nottingham.ac.uk/~plzloose/minoTourhome/message.php?callback=?', function(result) { $.each(result, function(key,value){ //checking version info. if (key == 'version'){ if (value == '<?php echo $_SESSION['minotourversion'];?>'){ $('#newstarget').html("You are running the most recent version of minoTour - version "+value+".<br>"); }else if (value < '<?php echo $_SESSION['minotourversion'];?>'){ $('#newstarget').html("You appear to be in the fortunate position of running a future version of the minoTour web application "+value+". If you have modified the code yourself - great. If not then there might be an issue somewhere!.<br>"); }else if (value > '<?php echo $_SESSION['minotourversion'];?>'){ $('#newstarget').html("You are running an outdated version of the minoTour web application. The most recent version of minoTour is version "+value+".<br>"+"Instructions for upgrading will be posted below.<br>"); } }else if (key.substring(0, 7) == 'message') { $('#newstarget').append(value + "<br>"); } }); }); </script> <?php include "includes/reporting.php";?> </body> </html> <?php } else { // the user is not logged in. you can do whatever you want here. // for demonstration purposes, we simply show the "you are not logged in" view. include("views/not_logged_in.php"); } ?>
sdh100shaun/minoTour
mT_web/minoTour/views/index_old.php
PHP
gpl-3.0
6,077
package cn.nukkit; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import com.google.gson.Gson; import com.google.gson.JsonObject; import cn.nukkit.AdventureSettings.Type; import cn.nukkit.block.Block; import cn.nukkit.block.BlockAir; import cn.nukkit.block.BlockCommand; import cn.nukkit.block.BlockDoor; import cn.nukkit.block.BlockEnderChest; import cn.nukkit.block.BlockNoteblock; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityBeacon; import cn.nukkit.blockentity.BlockEntityCommandBlock; import cn.nukkit.blockentity.BlockEntityItemFrame; import cn.nukkit.blockentity.BlockEntitySign; import cn.nukkit.blockentity.BlockEntitySpawnable; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.command.data.CommandDataVersions; import cn.nukkit.entity.Attribute; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.EntityInteractable; import cn.nukkit.entity.EntityLiving; import cn.nukkit.entity.data.EntityData; import cn.nukkit.entity.data.EntityMetadata; import cn.nukkit.entity.data.IntPositionEntityData; import cn.nukkit.entity.data.ShortEntityData; import cn.nukkit.entity.data.Skin; import cn.nukkit.entity.data.StringEntityData; import cn.nukkit.entity.item.EntityBoat; import cn.nukkit.entity.item.EntityItem; import cn.nukkit.entity.item.EntityMinecartAbstract; import cn.nukkit.entity.item.EntityMinecartEmpty; import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.entity.item.EntityXPOrb; import cn.nukkit.entity.projectile.EntityArrow; import cn.nukkit.entity.projectile.EntityFishingHook; import cn.nukkit.event.block.ItemFrameDropItemEvent; import cn.nukkit.event.block.SignChangeEvent; import cn.nukkit.event.entity.EntityDamageByBlockEvent; import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityDamageEvent.DamageModifier; import cn.nukkit.event.inventory.CraftItemEvent; import cn.nukkit.event.inventory.InventoryCloseEvent; import cn.nukkit.event.player.PlayerAnimationEvent; import cn.nukkit.event.player.PlayerBedEnterEvent; import cn.nukkit.event.player.PlayerBedLeaveEvent; import cn.nukkit.event.player.PlayerBlockPickEvent; import cn.nukkit.event.player.PlayerChatEvent; import cn.nukkit.event.player.PlayerChunkRequestEvent; import cn.nukkit.event.player.PlayerCommandPreprocessEvent; import cn.nukkit.event.player.PlayerDeathEvent; import cn.nukkit.event.player.PlayerGameModeChangeEvent; import cn.nukkit.event.player.PlayerInteractEntityEvent; import cn.nukkit.event.player.PlayerInteractEvent; import cn.nukkit.event.player.PlayerInteractEvent.Action; import cn.nukkit.event.player.PlayerInvalidMoveEvent; import cn.nukkit.event.player.PlayerItemConsumeEvent; import cn.nukkit.event.player.PlayerJoinEvent; import cn.nukkit.event.player.PlayerKickEvent; import cn.nukkit.event.player.PlayerLoginEvent; import cn.nukkit.event.player.PlayerMapInfoRequestEvent; import cn.nukkit.event.player.PlayerModalFormCloseEvent; import cn.nukkit.event.player.PlayerModalFormResponseEvent; import cn.nukkit.event.player.PlayerMouseOverEntityEvent; import cn.nukkit.event.player.PlayerMoveEvent; import cn.nukkit.event.player.PlayerPreLoginEvent; import cn.nukkit.event.player.PlayerQuitEvent; import cn.nukkit.event.player.PlayerRespawnEvent; import cn.nukkit.event.player.PlayerServerSettingsChangedEvent; import cn.nukkit.event.player.PlayerTeleportEvent; import cn.nukkit.event.player.PlayerTeleportEvent.TeleportCause; import cn.nukkit.event.player.PlayerToggleFlightEvent; import cn.nukkit.event.player.PlayerToggleGlideEvent; import cn.nukkit.event.player.PlayerToggleSneakEvent; import cn.nukkit.event.player.PlayerToggleSprintEvent; import cn.nukkit.event.server.DataPacketReceiveEvent; import cn.nukkit.event.server.DataPacketSendEvent; import cn.nukkit.inventory.AnvilInventory; import cn.nukkit.inventory.BeaconInventory; import cn.nukkit.inventory.BigCraftingGrid; import cn.nukkit.inventory.BigShapedRecipe; import cn.nukkit.inventory.BigShapelessRecipe; import cn.nukkit.inventory.CraftingGrid; import cn.nukkit.inventory.EnchantInventory; import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.inventory.PlayerCursorInventory; import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.inventory.Recipe; import cn.nukkit.inventory.ShapedRecipe; import cn.nukkit.inventory.ShapelessRecipe; import cn.nukkit.inventory.TradingInventory; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.inventory.transaction.SimpleInventoryTransaction; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.inventory.transaction.action.SlotChangeAction; import cn.nukkit.inventory.transaction.data.ReleaseItemData; import cn.nukkit.inventory.transaction.data.UseItemData; import cn.nukkit.inventory.transaction.data.UseItemOnEntityData; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemBucket; import cn.nukkit.item.ItemGlassBottle; import cn.nukkit.item.ItemMap; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.item.food.Food; import cn.nukkit.lang.TextContainer; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.level.ChunkLoader; import cn.nukkit.level.Level; import cn.nukkit.level.Location; import cn.nukkit.level.Position; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.particle.CriticalParticle; import cn.nukkit.level.particle.PunchBlockParticle; import cn.nukkit.level.sound.ExperienceOrbSound; import cn.nukkit.level.sound.ItemFrameItemRemovedSound; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockVector3; import cn.nukkit.math.NukkitMath; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector2; import cn.nukkit.math.Vector3; import cn.nukkit.metadata.MetadataValue; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.ByteTag; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.nbt.tag.Tag; import cn.nukkit.network.SourceInterface; import cn.nukkit.network.protocol.AdventureSettingsPacket; import cn.nukkit.network.protocol.AnimatePacket; import cn.nukkit.network.protocol.AvailableCommandsPacket; import cn.nukkit.network.protocol.BatchPacket; import cn.nukkit.network.protocol.BlockEntityDataPacket; import cn.nukkit.network.protocol.BlockPickRequestPacket; import cn.nukkit.network.protocol.ChangeDimensionPacket; import cn.nukkit.network.protocol.ChunkRadiusUpdatedPacket; import cn.nukkit.network.protocol.ClientboundMapItemDataPacket; import cn.nukkit.network.protocol.CommandBlockUpdatePacket; import cn.nukkit.network.protocol.CommandRequestPacket; import cn.nukkit.network.protocol.ContainerClosePacket; import cn.nukkit.network.protocol.CraftingEventPacket; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.network.protocol.DisconnectPacket; import cn.nukkit.network.protocol.EntityEventPacket; import cn.nukkit.network.protocol.FullChunkDataPacket; import cn.nukkit.network.protocol.InteractPacket; import cn.nukkit.network.protocol.InventoryContentPacket; import cn.nukkit.network.protocol.InventoryTransactionPacket; import cn.nukkit.network.protocol.ItemFrameDropItemPacket; import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.network.protocol.LoginPacket; import cn.nukkit.network.protocol.MapInfoRequestPacket; import cn.nukkit.network.protocol.MobEquipmentPacket; import cn.nukkit.network.protocol.ModalFormRequestPacket; import cn.nukkit.network.protocol.ModalFormResponsePacket; import cn.nukkit.network.protocol.MovePlayerPacket; import cn.nukkit.network.protocol.PlayStatusPacket; import cn.nukkit.network.protocol.PlayerActionPacket; import cn.nukkit.network.protocol.PlayerHotbarPacket; import cn.nukkit.network.protocol.PlayerInputPacket; import cn.nukkit.network.protocol.PlayerSkinPacket; import cn.nukkit.network.protocol.ProtocolInfo; import cn.nukkit.network.protocol.RemoveEntityPacket; import cn.nukkit.network.protocol.RequestChunkRadiusPacket; import cn.nukkit.network.protocol.ResourcePackChunkDataPacket; import cn.nukkit.network.protocol.ResourcePackChunkRequestPacket; import cn.nukkit.network.protocol.ResourcePackClientResponsePacket; import cn.nukkit.network.protocol.ResourcePackDataInfoPacket; import cn.nukkit.network.protocol.ResourcePackStackPacket; import cn.nukkit.network.protocol.ResourcePacksInfoPacket; import cn.nukkit.network.protocol.RespawnPacket; import cn.nukkit.network.protocol.ServerSettingsResponsePacket; import cn.nukkit.network.protocol.SetCommandsEnabledPacket; import cn.nukkit.network.protocol.SetEntityMotionPacket; import cn.nukkit.network.protocol.SetPlayerGameTypePacket; import cn.nukkit.network.protocol.SetSpawnPositionPacket; import cn.nukkit.network.protocol.SetTimePacket; import cn.nukkit.network.protocol.SetTitlePacket; import cn.nukkit.network.protocol.ShowProfilePacket; import cn.nukkit.network.protocol.StartGamePacket; import cn.nukkit.network.protocol.TextPacket; import cn.nukkit.network.protocol.TransferPacket; import cn.nukkit.network.protocol.UpdateAttributesPacket; import cn.nukkit.network.protocol.UpdateBlockPacket; import cn.nukkit.network.protocol.types.ContainerIds; import cn.nukkit.network.protocol.types.NetworkInventoryAction; import cn.nukkit.permission.PermissibleBase; import cn.nukkit.permission.Permission; import cn.nukkit.permission.PermissionAttachment; import cn.nukkit.permission.PermissionAttachmentInfo; import cn.nukkit.plugin.Plugin; import cn.nukkit.potion.Effect; import cn.nukkit.potion.Potion; import cn.nukkit.resourcepacks.ResourcePack; import cn.nukkit.resourcepacks.ResourcePackManager; import cn.nukkit.utils.Binary; import cn.nukkit.utils.BlockIterator; import cn.nukkit.utils.ClientChainData; import cn.nukkit.utils.FastAppender; import cn.nukkit.utils.MainLogger; import cn.nukkit.utils.TextFormat; import cn.nukkit.utils.Utils; import cn.nukkit.utils.Zlib; import cn.nukkit.window.FormWindow; import cn.nukkit.window.ServerSettingsWindow; import co.aikar.timings.Timing; import co.aikar.timings.Timings; /** * author: MagicDroidX & Box * Nukkit Project */ public class Player extends EntityHuman implements CommandSender, InventoryHolder, ChunkLoader, IPlayer { public static final int SURVIVAL = 0; public static final int CREATIVE = 1; public static final int ADVENTURE = 2; public static final int SPECTATOR = 3; public static final int VIEW = SPECTATOR; public static final int SURVIVAL_SLOTS = 36; public static final int CREATIVE_SLOTS = 112; public static final int CRAFTING_SMALL = 0; public static final int CRAFTING_BIG = 1; public static final int CRAFTING_ANVIL = 2; public static final int CRAFTING_ENCHANT = 3; public static final int CRAFTING_STONECUTTER = 4;//使用されていない(PMMPから引用) public static final float DEFAULT_SPEED = 0.1f; public static final float MAXIMUM_SPEED = 0.5f; public static final int PERMISSION_CUSTOM = 3; public static final int PERMISSION_OPERATOR = 2; public static final int PERMISSION_MEMBER = 1; public static final int PERMISSION_VISITOR = 0; protected final SourceInterface interfaz; public boolean playedBefore; public boolean spawned = false; public boolean loggedIn = false; public int gamemode; public long lastBreak; protected int windowCnt = 2; protected Map<Inventory, Integer> windows; protected Map<Integer, Inventory> windowIndex = new HashMap<>(); protected Set<Integer> permanentWindows = new HashSet<>(); protected int messageCounter = 2; private String clientSecret; public Vector3 speed = null; public final HashSet<String> achievements = new HashSet<>(); public int craftingType = CRAFTING_SMALL; public long creationTime = 0; protected long randomClientId; protected Vector3 forceMovement = null; protected Vector3 teleportPosition = null; protected boolean connected = true; protected final String ip; protected boolean removeFormat = true; protected final int port; protected String username; protected String iusername; protected String displayName; protected String xuid; protected int startAction = -1; protected Vector3 sleeping = null; protected Long clientID = null; private Integer loaderId = null; protected float stepHeight = 0.6f; public Map<Long, Boolean> usedChunks = new HashMap<>(); protected int chunkLoadCount = 0; protected Map<Long, Integer> loadQueue = new HashMap<Long, Integer>(); protected int nextChunkOrderRun = 5; protected Map<UUID, Player> hiddenPlayers = new HashMap<>(); protected Vector3 newPosition = null; protected int chunkRadius; protected int viewDistance; protected final int chunksPerTick; protected final int spawnThreshold; protected Position spawnPosition = null; protected int inAirTicks = 0; protected int startAirTicks = 5; protected AdventureSettings adventureSettings = new AdventureSettings(this); protected boolean checkMovement = true; private final Map<Integer, Boolean> needACK = new HashMap<>(); private Map<Integer, List<DataPacket>> batchedPackets = new TreeMap<>(); private PermissibleBase perm = null; private int exp = 0; private int expLevel = 0; protected PlayerFood foodData = null; private Entity killer = null; private final AtomicReference<Locale> locale = new AtomicReference<>(null); private int hash; private String buttonText = ""; protected boolean enableClientCommand = true; private BlockEnderChest viewingEnderChest = null; protected int lastEnderPearl = -1; public boolean mute = false; public EntityFishingHook fishingHook; private boolean keepInventory = true; private boolean keepExperience = true; protected boolean enableRevert = true; public ClientChainData loginChainData; public int pickedXPOrb = 0; //看板関係 private String signText1; private String signText2; private String signText3; private String signText4; private BlockEntity blockEntity; private FormWindow activeWindow = null; private LinkedHashMap<Integer, ServerSettingsWindow> serverSettings = new LinkedHashMap<>(); private boolean printPackets; public void linkHookToPlayer(EntityFishingHook entity){ this.fishingHook = entity; EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getFishingHook().getId(); pk.event = EntityEventPacket.FISH_HOOK_HOOK; Server.broadcastPacket(this.getLevel().getPlayers().values(), pk); } public void unlinkHookFromPlayer(){ if (this.isFishing()){ EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getFishingHook().getId(); pk.event = EntityEventPacket.FISH_HOOK_TEASE; Server.broadcastPacket(this.getLevel().getPlayers().values(), pk); this.fishingHook.close(); this.fishingHook = null; } } @Deprecated public void setAllowFlight(boolean value) { this.getAdventureSettings().set(Type.ALLOW_FLIGHT, value); this.getAdventureSettings().update(); } @Deprecated public boolean getAllowFlight() { return this.getAdventureSettings().get(Type.ALLOW_FLIGHT); } @Deprecated public void setAutoJump(boolean value) { this.getAdventureSettings().set(Type.AUTO_JUMP, value); this.getAdventureSettings().update(); } @Deprecated public boolean hasAutoJump() { return this.getAdventureSettings().get(Type.AUTO_JUMP); } public int getStartActionTick() { return startAction; } public void startAction() { this.startAction = this.server.getTick(); } public void stopAction() { this.startAction = -1; } public int getLastEnderPearlThrowingTick() { return lastEnderPearl; } public void onThrowEnderPearl() { this.lastEnderPearl = this.server.getTick(); } public boolean isFishing(){ return this.fishingHook != null; } public EntityFishingHook getFishingHook(){ return this.fishingHook; } public BlockEnderChest getViewingEnderChest() { return viewingEnderChest; } public void setViewingEnderChest(BlockEnderChest chest) { if (chest == null && this.viewingEnderChest != null) { this.viewingEnderChest.getViewers().remove(this); } else if (chest != null) { chest.getViewers().add(this); } this.viewingEnderChest = chest; } public TranslationContainer getLeaveMessage() { return new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.left", this.getDisplayName()); } public String getClientSecret() { return clientSecret; } public ClientChainData getLoginChainData(){ return this.loginChainData; } /** * ClientChainDataクラスを使用してください。 */ @Deprecated public Long getClientId() { return randomClientId; } @Override public boolean isBanned() { return this.server.getNameBans().isBanned(this.getName()); } @Override public void setBanned(boolean value) { if (value) { this.server.getNameBans().addBan(this.getName(), null, null, null); this.kick(PlayerKickEvent.Reason.NAME_BANNED, "Banned by admin"); } else { this.server.getNameBans().remove(this.getName()); } } @Override public boolean isWhitelisted() { return this.server.isWhitelisted(this.getName().toLowerCase()); } @Override public void setWhitelisted(boolean value) { if (value) { this.server.addWhitelist(this.getName().toLowerCase()); } else { this.server.removeWhitelist(this.getName().toLowerCase()); } } /** * プレイヤーオブジェクトを取得します。 * @return Player */ @Override public Player getPlayer() { return this; } @Override public Long getFirstPlayed() { return this.namedTag != null ? this.namedTag.getLong("firstPlayed") : null; } @Override public Long getLastPlayed() { return this.namedTag != null ? this.namedTag.getLong("lastPlayed") : null; } @Override public boolean hasPlayedBefore() { return this.playedBefore; } /* public void setCanDestroyBlock(boolean setting){ AdventureSettings adventuresettings = this.getAdventureSettings(); adventuresettings.setCanDestroyBlock(setting); this.setAdventureSettings(adventuresettings); } */ public AdventureSettings getAdventureSettings() { return adventureSettings; } public void setAdventureSettings(AdventureSettings adventureSettings) { this.adventureSettings = adventureSettings.clone(this); this.adventureSettings.update(); } public void resetInAirTicks() { this.inAirTicks = 0; } @Override public void spawnTo(Player player) { if (this.spawned && player.spawned && this.isAlive() && player.isAlive() && player.getLevel() == this.level && player.canSee(this) && !this.isSpectator()) { super.spawnTo(player); } } /** * プレイヤーからサーバーオブジェクトを取得します。 * @return Server */ @Override public Server getServer() { return this.server; } public boolean getRemoveFormat() { return removeFormat; } public void setRemoveFormat() { this.setRemoveFormat(true); } public void setRemoveFormat(boolean remove) { this.removeFormat = remove; } public boolean canSee(Player player) { return !this.hiddenPlayers.containsKey(player.getUniqueId()); } public void hidePlayer(Player player) { if (this == player) { return; } this.hiddenPlayers.put(player.getUniqueId(), player); player.despawnFrom(this); } public void showPlayer(Player player) { if (this == player) { return; } this.hiddenPlayers.remove(player.getUniqueId()); if (player.isOnline()) { player.spawnTo(this); } } @Override public boolean canCollideWith(Entity entity) { return false; } @Override public void resetFallDistance() { super.resetFallDistance(); if (this.inAirTicks != 0) { this.startAirTicks = 5; } this.inAirTicks = 0; this.highestPosition = this.y; } @Override public boolean isOnline() { return this.connected && this.loggedIn; } /** * OPかどうかを取得します。 * @return boolean trueがOP/falseが非OP */ @Override public boolean isOp() { return this.server.isOp(this.getName()); } public void setOp(){ this.setOp(true); } /** * プレイヤーをOPにします。 * @param value trueがOP/falseが非OP * @return void */ @Override public void setOp(boolean value) { if (value == this.isOp()) { return; } if (value) { this.server.addOp(this.getName()); } else { this.server.removeOp(this.getName()); } this.recalculatePermissions(); this.getAdventureSettings().update(); this.sendCommandData(); } @Override public boolean isPermissionSet(String name) { return this.perm.isPermissionSet(name); } @Override public boolean isPermissionSet(Permission permission) { return this.perm.isPermissionSet(permission); } @Override public boolean hasPermission(String name) { return this.perm != null && this.perm.hasPermission(name); } @Override public boolean hasPermission(Permission permission) { return this.perm.hasPermission(permission); } @Override public PermissionAttachment addAttachment(Plugin plugin) { return this.addAttachment(plugin, null); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name) { return this.addAttachment(plugin, name, null); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, Boolean value) { return this.perm.addAttachment(plugin, name, value); } @Override public void removeAttachment(PermissionAttachment attachment) { this.perm.removeAttachment(attachment); } @Override public void recalculatePermissions() { this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_USERS, this); this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); if (this.perm == null) { return; } this.perm.recalculatePermissions(); if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); } if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); } if (this.isEnableClientCommand()) this.sendCommandData(); } public boolean isEnableClientCommand() { return this.enableClientCommand; } public void setEnableClientCommand(boolean enable) { this.enableClientCommand = enable; SetCommandsEnabledPacket pk = new SetCommandsEnabledPacket(); pk.enabled = enable; this.dataPacket(pk); if (enable) this.sendCommandData(); } public void sendCommandData() { AvailableCommandsPacket pk = new AvailableCommandsPacket(); Map<String, CommandDataVersions> data = new HashMap<>(); int count = 0; for (Command command : this.server.getCommandMap().getCommands().values()) { if (!command.testPermissionSilent(this)) { continue; } ++count; CommandDataVersions data0 = command.generateCustomCommandData(this); data.put(command.getName(), data0); } if (count > 0) { //TODO: structure checking pk.commands = data; int identifier = this.dataPacket(pk, true); // We *need* ACK so we can be sure that the client received the packet or not Thread t = new Thread() { public void run() { // We are going to wait 3 seconds, if after 3 seconds we didn't receive a reply from the client, resend the packet. try { Thread.sleep(3000); boolean status = needACK.get(identifier); if (!status && isOnline()) { sendCommandData(); return; } } catch (InterruptedException e) {} } }; t.start(); } } @Override public Map<String, PermissionAttachmentInfo> getEffectivePermissions() { return this.perm.getEffectivePermissions(); } public Player(SourceInterface interfaz, Long clientID, String ip, int port) { super(null, new CompoundTag()); this.interfaz = interfaz; this.windows = new HashMap<>(); this.perm = new PermissibleBase(this); this.server = Server.getInstance(); this.lastBreak = Long.MAX_VALUE; this.ip = ip; this.port = port; this.clientID = clientID; this.loaderId = Level.generateChunkLoaderId(this); this.chunksPerTick = (int) this.server.getConfig("chunk-sending.per-tick", 4); this.spawnThreshold = (int) this.server.getConfig("chunk-sending.spawn-threshold", 56); this.spawnPosition = null; this.gamemode = this.server.getDefaultGamemode(); this.setLevel(this.server.getDefaultLevel()); this.viewDistance = this.server.getViewDistance(); this.chunkRadius = viewDistance; //this.newPosition = new Vector3(0, 0, 0); this.boundingBox = new AxisAlignedBB(0, 0, 0, 0, 0, 0); this.uuid = null; this.rawUUID = null; this.creationTime = System.currentTimeMillis(); this.enableRevert = this.server.getJupiterConfigBoolean("enable-revert"); this.server.getJupiterConfigBoolean("allow-snowball"); this.server.getJupiterConfigBoolean("allow-egg"); this.server.getJupiterConfigBoolean("allow-enderpearl"); this.server.getJupiterConfigBoolean("allow-experience-bottle"); this.server.getJupiterConfigBoolean("allow-splash-potion"); this.server.getJupiterConfigBoolean("allow-bow"); this.server.getJupiterConfigBoolean("allow-fishing-rod"); this.printPackets = this.getServer().printPackets(); } /** * プレイヤーオブジェクトかどうかを取得します。 * この場合、trueしか返ってきません。 * @return boolean true */ public boolean isPlayer() { return true; } public void removeAchievement(String achievementId) { achievements.remove(achievementId); } public boolean hasAchievement(String achievementId) { return achievements.contains(achievementId); } public boolean isConnected() { return connected; } /** * プレイヤーのチャット上の名前を取得します。 * @return String プレイヤーのチャット上の名前 */ public String getDisplayName() { return this.displayName; } /** * プレイヤーのチャット上の名前を設定します。 * @param displayName 設定する名前 * @return void */ public void setDisplayName(String displayName) { this.displayName = displayName; if (this.spawned) { this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), this.getSkin(), this.getLoginChainData().getXUID()); } } /** * プレイヤーのスキンを設定します。 * @param skin スキンデータ * @return void */ @Override public void setSkin(Skin skin) { super.setSkin(skin); if (this.spawned) { this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), skin, this.getLoginChainData().getXUID()); } } /** * プレイヤーのIPアドレスを取得します。 * @return String プレイヤーのIPアドレス */ public String getAddress() { return this.ip; } /** * プレイヤーのポートを取得します。 * @return int プレイヤーのポート */ public int getPort() { return port; } public Position getNextPosition() { return this.newPosition != null ? new Position(this.newPosition.x, this.newPosition.y, this.newPosition.z, this.level) : this.getPosition(); } /** * プレイヤーが寝ているかどうかをを取得します。 * @return boolean trueが寝ている/falseが寝ていない */ public boolean isSleeping() { return this.sleeping != null; } public int getInAirTicks() { return this.inAirTicks; } public String getButtonText() { return this.buttonText; } public void setButtonText(String text) { if (!(text.equals(this.getButtonText()))) { this.buttonText = text; this.setDataProperty(new StringEntityData(Entity.DATA_INTERACTIVE_TAG, this.buttonText)); } } @Override protected boolean switchLevel(Level targetLevel) { Level oldLevel = this.level; if (super.switchLevel(targetLevel)) { for (long index : new ArrayList<>(this.usedChunks.keySet())) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); this.unloadChunk(chunkX, chunkZ, oldLevel); } this.usedChunks = new HashMap<>(); SetTimePacket pk = new SetTimePacket(); pk.time = this.level.getTime(); this.dataPacket(pk); // TODO: Remove this hack int distance = this.viewDistance * 2 * 16 * 2; this.sendPosition(this.add(distance, 0, distance), this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); return true; } return false; } public void unloadChunk(int x, int z) { this.unloadChunk(x, z, null); } public void unloadChunk(int x, int z, Level level) { level = level == null ? this.level : level; long index = Level.chunkHash(x, z); if (this.usedChunks.containsKey(index)) { for (Entity entity : level.getChunkEntities(x, z).values()) { if (entity != this) { entity.despawnFrom(this); } } this.usedChunks.remove(index); } level.unregisterChunkLoader(this, x, z); this.loadQueue.remove(index); } public Position getSpawn() { if (this.spawnPosition != null && this.spawnPosition.getLevel() != null && this.getServer().getJupiterConfigString("spawnpoint").equals("fromplayerdata")) { return this.spawnPosition; } else { return this.server.getDefaultLevel().getSafeSpawn(); } } public void sendChunk(int x, int z, DataPacket packet) { if (!this.connected) { return; } this.usedChunks.put(Level.chunkHash(x, z), true); this.chunkLoadCount++; this.dataPacket(packet); if (this.spawned) { for (Entity entity : this.level.getChunkEntities(x, z).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } } public void sendChunk(int x, int z, byte[] payload) { if (!this.connected) { return; } this.usedChunks.put(Level.chunkHash(x, z), true); this.chunkLoadCount++; FullChunkDataPacket pk = new FullChunkDataPacket(); pk.chunkX = x; pk.chunkZ = z; pk.data = payload; this.batchDataPacket(pk); if (this.spawned) { for (Entity entity : this.level.getChunkEntities(x, z).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } } protected void sendNextChunk() { if (!this.connected) { return; } Timings.playerChunkSendTimer.startTiming(); int count = 0; List<Map.Entry<Long, Integer>> entryList = new ArrayList<>(this.loadQueue.entrySet()); entryList.sort(Comparator.comparingInt(Map.Entry::getValue)); for (Map.Entry<Long, Integer> entry : entryList) { long index = entry.getKey(); if (count >= this.chunksPerTick) { break; } int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); ++count; this.usedChunks.put(index, false); this.level.registerChunkLoader(this, chunkX, chunkZ, false); if (!this.level.populateChunk(chunkX, chunkZ)) { if (this.spawned && this.teleportPosition == null) { continue; } else { break; } } this.loadQueue.remove(index); PlayerChunkRequestEvent ev = new PlayerChunkRequestEvent(this, chunkX, chunkZ); this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.level.requestChunk(chunkX, chunkZ, this); } } if (this.chunkLoadCount >= this.spawnThreshold && !this.spawned && this.teleportPosition == null) { this.doFirstSpawn(); } Timings.playerChunkSendTimer.stopTiming(); } protected void doFirstSpawn() { this.spawned = true; this.server.sendRecipeList(this); this.getAdventureSettings().update(); this.sendPotionEffects(this); this.sendData(this); this.inventory.sendContents(this); this.inventory.sendArmorContents(this); this.offhandInventory.sendContents(this); this.offhandInventory.sendOffhandItem(this); SetTimePacket setTimePacket = new SetTimePacket(); setTimePacket.time = this.level.getTime(); this.dataPacket(setTimePacket); PlayStatusPacket playStatusPacket = new PlayStatusPacket(); playStatusPacket.status = PlayStatusPacket.PLAYER_SPAWN; this.dataPacket(playStatusPacket); PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(this, new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.joined", new String[]{ this.getDisplayName() }) ); this.server.getPluginManager().callEvent(playerJoinEvent); if (playerJoinEvent.getJoinMessage().toString().trim().length() > 0) { //デフォルトの参加時メッセージを送るかどうかを確認 if(this.server.getJupiterConfigBoolean("join-quit-message")) this.server.broadcastMessage(playerJoinEvent.getJoinMessage()); } this.noDamageTicks = 60; for (long index : this.usedChunks.keySet()) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); for (Entity entity : this.level.getChunkEntities(chunkX, chunkZ).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } this.sendExperience(this.getExperience()); this.sendExperienceLevel(this.getExperienceLevel()); if (!this.isSpectator()) { this.spawnToAll(); } //todo Updater RespawnPacket respawnPacket = new RespawnPacket(); Position pos = this.getSpawn(); respawnPacket.x = (float) pos.x; respawnPacket.y = (float) pos.y; respawnPacket.z = (float) pos.z; this.dataPacket(respawnPacket); this.sendPlayStatus(PlayStatusPacket.PLAYER_SPAWN); //Weather this.getLevel().sendWeather(this); //FoodLevel this.getFoodData().sendFoodLevel(); if (this.isSpectator()) { InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; this.dataPacket(inventoryContentPacket); } else if(this.isCreative()) { InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; inventoryContentPacket.slots = Item.getCreativeItems().stream().toArray(Item[]::new); this.dataPacket(inventoryContentPacket); } } protected boolean orderChunks() { if (!this.connected) { return false; } Timings.playerChunkOrderTimer.startTiming(); this.nextChunkOrderRun = 200; Map<Long, Integer> newOrder = new HashMap<>(); Map<Long, Boolean> lastChunk = this.usedChunks; int centerX = (int) this.x >> 4; int centerZ = (int) this.z >> 4; for (int x = -this.chunkRadius; x <= this.chunkRadius; x++) { for (int z = -this.chunkRadius; z <= this.chunkRadius; z++) { int chunkX = x + centerX; int chunkZ = z + centerZ; int distance = (int) Math.sqrt((double) x * x + (double) z * z); if (distance <= this.chunkRadius) { long index; if (!(this.usedChunks.containsKey(index = Level.chunkHash(chunkX, chunkZ))) || !this.usedChunks.get(index)) { newOrder.put(index, distance); } lastChunk.remove(index); } } } for (long index : new ArrayList<>(lastChunk.keySet())) { this.unloadChunk(Level.getHashX(index), Level.getHashZ(index)); } this.loadQueue = newOrder; Timings.playerChunkOrderTimer.stopTiming(); return true; } public boolean batchDataPacket(DataPacket packet) { if (!this.connected) { return false; } try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent event = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) { timing.stopTiming(); return false; } if (!this.batchedPackets.containsKey(packet.getChannel())) { this.batchedPackets.put(packet.getChannel(), new ArrayList<>()); } this.batchedPackets.get(packet.getChannel()).add(packet.clone()); } return true; } /** * プレイヤーにパケットを送信します。 * @param packet 送るパケット * @return boolean */ public boolean dataPacket(DataPacket packet) { return this.dataPacket(packet, false) != -1; } public int dataPacket(DataPacket packet, boolean needACK) { if (!this.connected) { return -1; } if(this.printPackets) this.getServer().getLogger().info(TextFormat.YELLOW + "[SEND] " + TextFormat.WHITE + packet.getName()); try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { timing.stopTiming(); return -1; } Integer identifier = this.interfaz.putPacket(this, packet, needACK, false); if (needACK && identifier != null) { this.needACK.put(identifier.intValue(), false); timing.stopTiming(); return identifier; } } return 0; } /** * 0 is true * -1 is false * other is identifer */ public boolean directDataPacket(DataPacket packet) { return this.directDataPacket(packet, false) != -1; } public int directDataPacket(DataPacket packet, boolean needACK) { if (!this.connected) { return -1; } if(this.printPackets) this.getServer().getLogger().info(TextFormat.LIGHT_PURPLE + "[SEND-DIRECT] " + TextFormat.WHITE + packet.getClass().getSimpleName()); try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { timing.stopTiming(); return -1; } Integer identifier = this.interfaz.putPacket(this, packet, needACK, true); if (needACK && identifier != null) { this.needACK.put(identifier.intValue(), false); timing.stopTiming(); return identifier; } } return 0; } public int getPing() { return this.interfaz.getNetworkLatency(this); } public boolean sleepOn(Vector3 pos) { if (!this.isOnline()) { return false; } for (Entity p : this.level.getNearbyEntities(this.boundingBox.grow(2, 1, 2), this)) { if (p instanceof Player) { if (((Player) p).sleeping != null && pos.distance(((Player) p).sleeping) <= 0.1) { return false; } } } PlayerBedEnterEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerBedEnterEvent(this, this.level.getBlock(pos))); if (ev.isCancelled()) { return false; } this.sleeping = pos.clone(); this.teleport(new Location(pos.x + 0.5, pos.y - 0.5, pos.z + 0.5, this.yaw, this.pitch, this.level), null); this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, (int) pos.x, (int) pos.y, (int) pos.z)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, true); this.setSpawn(pos); this.level.sleepTicks = 60; return true; } /** * プレイヤーのスポーン地点を設定します。 * @param pos 設定する座標 * @return void * @see "Vector3" * @see Vector3 */ public void setSpawn(Vector3 pos) { Level level; if (!(pos instanceof Position)) { level = this.level; } else { level = ((Position) pos).getLevel(); } this.spawnPosition = new Position(pos.x, pos.y, pos.z, level); SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_PLAYER_SPAWN; pk.x = (int) this.spawnPosition.x; pk.y = (int) this.spawnPosition.y; pk.z = (int) this.spawnPosition.z; this.dataPacket(pk); } public void startSleep(){ this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, true); this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, (int) this.x, (int) this.y, (int) this.z), true); this.sleeping = this.getPosition(); this.server.getPluginManager().callEvent(new PlayerBedEnterEvent(this, this.level.getBlock(this.sleeping))); } public void stopSleep() { if (this.sleeping != null) { this.server.getPluginManager().callEvent(new PlayerBedLeaveEvent(this, this.level.getBlock(this.sleeping))); this.sleeping = null; this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, 0, 0, 0)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false); this.level.sleepTicks = 0; AnimatePacket pk = new AnimatePacket(); pk.entityRuntimeId = this.id; pk.action = 3; //Wake up this.dataPacket(pk); } } /** * プレイヤーのゲームモードを取得します。 * <br>0:サバイバルモード * <br>1:クリエイティブモード * <br>2:アドベンチャーモード * <br>3:スペクテイターモード * @return int プレイヤーのゲームモード */ public int getGamemode() { return gamemode; } private static int getClientFriendlyGamemode(int gamemode) { gamemode &= 0x03; if (gamemode == Player.SPECTATOR) { return Player.CREATIVE; } return gamemode; } /** * プレイヤーのゲームモードを設定します。 * @param gamemode ゲームモード * <br>0:サバイバルモード * <br>1:クリエイティブモード * <br>2:アドベンチャーモード * <br>3:スペクテイターモード * @return boolean */ public boolean setGamemode(int gamemode) { return this.setGamemode(gamemode, false, null); } public boolean setGamemode(int gamemode, boolean clientSide) { return this.setGamemode(gamemode, clientSide, null); } public boolean setGamemode(int gamemode, boolean clientSide, AdventureSettings newSettings) { if (gamemode < 0 || gamemode > 3) { return false; } if (newSettings == null) { newSettings = this.getAdventureSettings().clone(this); newSettings.set(Type.BUILD_AND_MINE, gamemode != 3); newSettings.set(Type.WORLD_BUILDER, gamemode != 3); newSettings.set(Type.NO_CLIP, gamemode == 3); newSettings.set(Type.WORLD_IMMUTABLE, gamemode == 3); newSettings.set(Type.NO_PVP, gamemode == 3); newSettings.set(Type.FLYING, gamemode == 1 || gamemode == 3); newSettings.set(Type.ALLOW_FLIGHT, gamemode == 1 || gamemode == 3); } PlayerGameModeChangeEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerGameModeChangeEvent(this, gamemode, newSettings)); if (ev.isCancelled()) { return false; } this.gamemode = gamemode; if (this.isSpectator()) { this.keepMovement = true; this.despawnFromAll(); } else { this.keepMovement = false; this.spawnToAll(); } this.namedTag.putInt("playerGameType", gamemode); if (!clientSide) { SetPlayerGameTypePacket pk = new SetPlayerGameTypePacket(); pk.gamemode = getClientFriendlyGamemode(gamemode); this.dataPacket(pk); } this.setAdventureSettings(ev.getNewAdventureSettings()); this.getAdventureSettings().update(); if (this.isSpectator()) { this.teleport(this.temporalVector.setComponents(this.x, this.y + 0.1, this.z)); InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; this.dataPacket(inventoryContentPacket); } else { InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; inventoryContentPacket.slots = Item.getCreativeItems().stream().toArray(Item[]::new); this.dataPacket(inventoryContentPacket); } this.resetFallDistance(); this.inventory.sendContents(this); this.inventory.sendContents(this.getViewers().values()); this.inventory.sendHeldItem(this.hasSpawned.values()); return true; } @Deprecated public void sendSettings() { this.getAdventureSettings().update(); } public boolean isSurvival() { return (this.gamemode & 0x01) == 0; } public boolean isCreative() { return (this.gamemode & 0x01) > 0; } public boolean isSpectator() { return this.gamemode == 3; } public boolean isAdventure() { return (this.gamemode & 0x02) > 0; } @Override public Item[] getDrops() { if (!this.isCreative()) { return super.getDrops(); } return new Item[0]; } @Override public boolean setDataProperty(EntityData data) { return setDataProperty(data, true); } @Override public boolean setDataProperty(EntityData data, boolean send) { if (super.setDataProperty(data, send)) { if (send) this.sendData(this, new EntityMetadata().put(this.getDataProperty(data.getId()))); return true; } return false; } @Override protected void checkGroundState(double movX, double movY, double movZ, double dx, double dy, double dz) { if (!this.onGround || movX != 0 || movY != 0 || movZ != 0) { boolean onGround = false; AxisAlignedBB bb = this.boundingBox.clone(); bb.maxY = bb.minY + 0.5; bb.minY -= 1; AxisAlignedBB realBB = this.boundingBox.clone(); realBB.maxY = realBB.minY + 0.1; realBB.minY -= 0.2; int minX = NukkitMath.floorDouble(bb.minX); int minY = NukkitMath.floorDouble(bb.minY); int minZ = NukkitMath.floorDouble(bb.minZ); int maxX = NukkitMath.ceilDouble(bb.maxX); int maxY = NukkitMath.ceilDouble(bb.maxY); int maxZ = NukkitMath.ceilDouble(bb.maxZ); for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z)); if (!block.canPassThrough() && block.collidesWithBB(realBB)) { onGround = true; break; } } } } this.onGround = onGround; } this.isCollided = this.onGround; } @Override protected void checkBlockCollision() { boolean portal = false; Block block = this.getLevelBlock(); if (block.getId() == Block.NETHER_PORTAL) { portal = true; } block.onEntityCollide(this); if (portal) { inPortalTicks++; } } protected void checkNearEntities() { for (Entity entity : this.level.getNearbyEntities(this.boundingBox.grow(1, 0.5, 1), this)) { entity.scheduleUpdate(); if (!entity.isAlive() || !this.isAlive()) { continue; } this.pickupEntity(entity, true); } } protected void processMovement(int tickDiff) { if (!this.isAlive() || !this.spawned || this.newPosition == null || this.teleportPosition != null || this.isSleeping()) { return; } Vector3 newPos = this.newPosition; double distanceSquared = newPos.distanceSquared(this); boolean revert = false; if ((distanceSquared / ((double) (tickDiff * tickDiff))) > 100 && (newPos.y - this.y) > -5) { revert = true; } else { if (this.chunk == null || !this.chunk.isGenerated()) { BaseFullChunk chunk = this.level.getChunk((int) newPos.x >> 4, (int) newPos.z >> 4, false); if (chunk == null || !chunk.isGenerated()) { revert = true; this.nextChunkOrderRun = 0; } else { if (this.chunk != null) { this.chunk.removeEntity(this); } this.chunk = chunk; } } } double tdx = newPos.x - this.x; double tdz = newPos.z - this.z; double distance = Math.sqrt(tdx * tdx + tdz * tdz); if (!revert && distanceSquared != 0) { double dx = newPos.x - this.x; double dy = newPos.y - this.y; double dz = newPos.z - this.z; this.fastMove(dx, dy, dz); double diffX = this.x - newPos.x; double diffY = this.y - newPos.y; double diffZ = this.z - newPos.z; double yS = 0.5 + this.ySize; if (diffY >= -yS || diffY <= yS) { diffY = 0; } if (diffX != 0 || diffY != 0 || diffZ != 0) { if (this.checkMovement && !server.getAllowFlight() && this.isSurvival()) { if (!this.isSleeping() && this.riding == null) { double diffHorizontalSqr = (diffX * diffX + diffZ * diffZ) / ((double) (tickDiff * tickDiff)); if (diffHorizontalSqr > 0.125) { if(enableRevert){ PlayerInvalidMoveEvent ev; this.getServer().getPluginManager().callEvent(ev = new PlayerInvalidMoveEvent(this, true)); if (!ev.isCancelled()) { revert = ev.isRevert(); if (revert) { this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidMove", this.getName())); } } } } } } this.x = newPos.x; this.y = newPos.y; this.z = newPos.z; double radius = this.getWidth() / 2; this.boundingBox.setBounds(this.x - radius, this.y, this.z - radius, this.x + radius, this.y + this.getHeight(), this.z + radius); } } Location from = new Location( this.lastX, this.lastY, this.lastZ, this.lastYaw, this.lastPitch, this.level); Location to = this.getLocation(); if (!revert && (Math.pow(this.lastX - to.x, 2) + Math.pow(this.lastY - to.y, 2) + Math.pow(this.lastZ - to.z, 2)) > (1d / 16d) || (Math.abs(this.lastYaw - to.yaw) + Math.abs(this.lastPitch - to.pitch)) > 10) { boolean isFirst = this.firstMove; this.firstMove = false; this.lastX = to.x; this.lastY = to.y; this.lastZ = to.z; this.lastYaw = to.yaw; this.lastPitch = to.pitch; if (!isFirst) { List<Block> blocksAround = this.blocksAround; List<Block> collidingBlocks = this.collisionBlocks; PlayerMoveEvent ev = new PlayerMoveEvent(this, from, to); this.blocksAround = null; this.collisionBlocks = null; this.server.getPluginManager().callEvent(ev); if (!(revert = ev.isCancelled())) { //Yes, this is intended if (!to.equals(ev.getTo())) { //If plugins modify the destination this.teleport(ev.getTo(), null); } else { this.broadcastMovement(); //this.addMovement(this.x, this.y + this.getEyeHeight(), this.z, this.yaw, this.pitch, this.yaw); } } else { this.blocksAround = blocksAround; this.collisionBlocks = collidingBlocks; } if (this.isFishing()){ if (this.distance(this.getFishingHook()) > 33 | this.getInventory().getItemInHand().getId() != Item.FISHING_ROD){ this.unlinkHookFromPlayer(); } } } if (!this.isSpectator()) { this.checkNearEntities(); } if (this.speed == null) speed = new Vector3(from.x - to.x, from.y - to.y, from.z - to.z); else this.speed.setComponents(from.x - to.x, from.y - to.y, from.z - to.z); } else { if (this.speed == null) speed = new Vector3(0, 0, 0); else this.speed.setComponents(0, 0, 0); } if (!revert && (this.isFoodEnabled() || this.getServer().getDifficulty() == 0)) { if ((this.isSurvival() || this.isAdventure())/* && !this.getRiddingOn() instanceof Entity*/) { //UpdateFoodExpLevel if (distance >= 0.05) { double jump = 0; double swimming = this.isInsideOfWater() ? 0.015 * distance : 0; if (swimming != 0) distance = 0; if (this.isSprinting()) { //Running if (this.inAirTicks == 3 && swimming == 0) { jump = 0.7; } this.getFoodData().updateFoodExpLevel(0.025 * distance + jump + swimming); } else { if (this.inAirTicks == 3 && swimming == 0) { jump = 0.2; } this.getFoodData().updateFoodExpLevel(0.01 * distance + jump + swimming); } } } } if (revert) { this.lastX = from.x; this.lastY = from.y; this.lastZ = from.z; this.lastYaw = from.yaw; this.lastPitch = from.pitch; this.sendPosition(from, from.yaw, from.pitch, MovePlayerPacket.MODE_RESET); //this.sendSettings(); this.forceMovement = new Vector3(from.x, from.y, from.z); } else { this.forceMovement = null; if (distanceSquared != 0 && this.nextChunkOrderRun > 20) { this.nextChunkOrderRun = 20; } } this.newPosition = null; } @Override public boolean setMotion(Vector3 motion) { if (super.setMotion(motion)) { if (this.chunk != null) { //this.getLevel().addEntityMotion(this.chunk.getX(), this.chunk.getZ(), this.getId(), this.motionX, this.motionY, this.motionZ); //Send to others this.broadcastMotion(); SetEntityMotionPacket pk = new SetEntityMotionPacket(); pk.entityRuntimeId = this.id; pk.motionX = (float) motion.x; pk.motionY = (float) motion.y; pk.motionZ = (float) motion.z; this.dataPacket(pk); //Send to self } if (this.motionY > 0) { //todo: check this this.startAirTicks = (int) ((-(Math.log(this.getGravity() / (this.getGravity() + this.getDrag() * this.motionY))) / this.getDrag()) * 2 + 5); } return true; } return false; } public void sendAttributes() { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entityRuntimeId = this.getId(); pk.entries = new Attribute[]{ Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0), Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(this.getFoodData().getLevel()), Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(this.getMovementSpeed()), Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(this.getExperienceLevel()), Attribute.getAttribute(Attribute.EXPERIENCE).setValue(((float) this.getExperience()) / calculateRequireExperience(this.getExperienceLevel())) }; this.dataPacket(pk); } @Override public boolean onUpdate(int currentTick) { if (!this.loggedIn) { return false; } int tickDiff = currentTick - this.lastUpdate; if (tickDiff <= 0) { return true; } this.messageCounter = 2; this.lastUpdate = currentTick; if (!this.isAlive() && this.spawned) { ++this.deadTicks; if (this.deadTicks >= 10) { this.despawnFromAll(); } return true; } if (this.spawned) { this.processMovement(tickDiff); this.entityBaseTick(tickDiff); if (this.getServer().getDifficulty() == 0 && this.level.getGameRules().getBoolean("naturalRegeneration")) { if (this.getHealth() < this.getMaxHealth() && this.ticksLived % 20 == 0) { this.heal(1); } PlayerFood foodData = this.getFoodData(); if (foodData.getLevel() < 20 && this.ticksLived % 10 == 0) { foodData.addFoodLevel(1, 0); } } if (this.isOnFire() && this.lastUpdate % 10 == 0) { if (this.isCreative() && !this.isInsideOfFire()) { this.extinguish(); } else if (this.getLevel().isRaining()) { if (this.getLevel().canBlockSeeSky(this)) { this.extinguish(); } } } if (!this.isSpectator() && this.speed != null) { if (this.onGround) { if (this.inAirTicks != 0) { this.startAirTicks = 5; } this.inAirTicks = 0; this.highestPosition = this.y; } else { if (!this.isGliding() && !server.getAllowFlight() && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && this.inAirTicks > 10 && !this.isSleeping() && !this.isImmobile()) { double expectedVelocity = (-this.getGravity()) / ((double) this.getDrag()) - ((-this.getGravity()) / ((double) this.getDrag())) * Math.exp(-((double) this.getDrag()) * ((double) (this.inAirTicks - this.startAirTicks))); double diff = (this.speed.y - expectedVelocity) * (this.speed.y - expectedVelocity); if (!this.hasEffect(Effect.JUMP) && diff > 0.6 && expectedVelocity < this.speed.y) { if (this.inAirTicks < 100) { //this.sendSettings(); this.setMotion(new Vector3(0, expectedVelocity, 0)); } else if (this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server")) { return false; } } } if (this.y > highestPosition) { this.highestPosition = this.y; } if (this.isGliding()) this.resetFallDistance(); ++this.inAirTicks; } if (this.isSurvival() || this.isAdventure()) { if (this.getFoodData() != null) this.getFoodData().update(tickDiff); } } } this.checkTeleportPosition(); this.checkInteractNearby(); /* if (this.spawned && this.dummyBossBars.size() > 0 && currentTick % 100 == 0) { this.dummyBossBars.values().forEach(DummyBossBar::updateBossEntityPosition); } */ return true; } public void checkInteractNearby() { int interactDistance = isCreative() ? 5 : 3; EntityInteractable onInteract; if(this.canInteract(this, interactDistance) && (onInteract = this.getEntityPlayerLookingAt(interactDistance)) != null) { this.setButtonText(onInteract.getInteractButtonText()); } else if (this.getInventory().getItemInHand().getId() == Item.FISHING_ROD) { this.setButtonText("釣りをする"); } else { this.setButtonText(""); } } /** * Returns the Entity the player is looking at currently * * @param maxDistance the maximum distance to check for entities * @return Entity|null either NULL if no entity is found or an instance of the entity */ public EntityInteractable getEntityPlayerLookingAt(int maxDistance) { timing.startTiming(); EntityInteractable entity = null; // just a fix because player MAY not be fully initialized if (temporalVector != null) { Entity[] nearbyEntities = level.getNearbyEntities(boundingBox.grow(maxDistance, maxDistance, maxDistance), this); // get all blocks in looking direction until the max interact distance is reached (it's possible that startblock isn't found!) try { BlockIterator itr = new BlockIterator(level, getPosition(), getDirectionVector(), getEyeHeight(), maxDistance); if (itr.hasNext()) { Block block; while (itr.hasNext()) { block = itr.next(); entity = getEntityAtPosition(nearbyEntities, block.getFloorX(), block.getFloorY(), block.getFloorZ()); if (entity != null) { break; } } } } catch (Exception ex) { // nothing to log here! } } timing.stopTiming(); return entity; } private EntityInteractable getEntityAtPosition(Entity[] nearbyEntities, int x, int y, int z) { for (Entity nearestEntity : nearbyEntities) { if (nearestEntity.getFloorX() == x && nearestEntity.getFloorY() == y && nearestEntity.getFloorZ() == z && nearestEntity instanceof EntityInteractable && ((EntityInteractable) nearestEntity).canDoInteraction()) { return (EntityInteractable) nearestEntity; } } return null; } private Block breakingBlock; public void checkNetwork() { if (!this.isOnline()) { return; } if (this.nextChunkOrderRun-- <= 0 || this.chunk == null) { this.orderChunks(); } if (!this.loadQueue.isEmpty() || !this.spawned) { this.sendNextChunk(); } if (!this.batchedPackets.isEmpty()) { for (int channel : this.batchedPackets.keySet()) { this.server.batchPackets(new Player[]{this}, batchedPackets.get(channel).stream().toArray(DataPacket[]::new), false); } this.batchedPackets = new TreeMap<>(); } } public boolean canInteract(Vector3 pos, double maxDistance) { return this.canInteract(pos, maxDistance, 0.5); } public boolean canInteract(Vector3 pos, double maxDistance, double maxDiff) { if (this.distanceSquared(pos) > maxDistance * maxDistance) { return false; } Vector2 dV = this.getDirectionPlane(); double dot = dV.dot(new Vector2(this.x, this.z)); double dot1 = dV.dot(new Vector2(pos.x, pos.z)); return (dot1 - dot) >= -maxDiff; } protected void processLogin() { if (!this.server.isWhitelisted((this.getName()).toLowerCase())) { this.kick(PlayerKickEvent.Reason.NOT_WHITELISTED, "Server is white-listed"); return; } else if (this.isBanned()) { this.kick(PlayerKickEvent.Reason.NAME_BANNED, "You are banned"); return; } else if (this.server.getIPBans().isBanned(this.getAddress())) { this.kick(PlayerKickEvent.Reason.IP_BANNED, "You are banned"); return; } if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); } if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); } for (Player p : this.server.getOnlinePlayers().values()) { if (p != this && p.getName() != null && p.getName().equalsIgnoreCase(this.getName())) { if (!p.kick(PlayerKickEvent.Reason.NEW_CONNECTION, "logged in from another location")) { this.close(this.getLeaveMessage(), "Already connected"); return; } } else if (p.loggedIn && this.getUniqueId().equals(p.getUniqueId())) { if (!p.kick(PlayerKickEvent.Reason.NEW_CONNECTION, "logged in from another location")) { this.close(this.getLeaveMessage(), "Already connected"); return; } } } namedTag = this.server.getOfflinePlayerData(this.username); if (namedTag == null) { this.close(this.getLeaveMessage(), "Invalid data"); return; } this.playedBefore = (namedTag.getLong("lastPlayed") - namedTag.getLong("firstPlayed")) > 1; boolean alive = true; namedTag.putString("NameTag", this.username); if (0 >= namedTag.getShort("Health")) { alive = false; } int exp = namedTag.getInt("EXP"); int expLevel = namedTag.getInt("expLevel"); this.setExperience(exp, expLevel); this.setGamemode(namedTag.getInt("playerGameType") & 0x03); if (this.server.getForceGamemode()) { this.gamemode = this.server.getDefaultGamemode(); namedTag.putInt("playerGameType", this.gamemode); } Level level; if ((level = this.server.getLevelByName(namedTag.getString("Level"))) == null || !alive) { this.setLevel(this.server.getDefaultLevel()); namedTag.putString("Level", this.level.getName()); namedTag.getList("Pos", DoubleTag.class) .add(new DoubleTag("0", this.level.getSpawnLocation().x)) .add(new DoubleTag("1", this.level.getSpawnLocation().y)) .add(new DoubleTag("2", this.level.getSpawnLocation().z)); } else { this.setLevel(level); } for (Tag achievement : namedTag.getCompound("Achievements").getAllTags()) { if (!(achievement instanceof ByteTag)) { continue; } if (((ByteTag) achievement).getData() > 0) { this.achievements.add(achievement.getName()); } } namedTag.putLong("lastPlayed", System.currentTimeMillis() / 1000); if (this.server.getAutoSave()) { this.server.saveOfflinePlayerData(this.username, namedTag, true); } ListTag<DoubleTag> posList = namedTag.getList("Pos", DoubleTag.class); super.init(this.level.getChunk((int) posList.get(0).data >> 4, (int) posList.get(2).data >> 4, true), namedTag); if (!this.namedTag.contains("foodLevel")) { this.namedTag.putInt("foodLevel", 20); } int foodLevel = this.namedTag.getInt("foodLevel"); if (!this.namedTag.contains("FoodSaturationLevel")) { this.namedTag.putFloat("FoodSaturationLevel", 20); } float foodSaturationLevel = this.namedTag.getFloat("foodSaturationLevel"); this.foodData = new PlayerFood(this, foodLevel, foodSaturationLevel); PlayerLoginEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerLoginEvent(this, "Plugin reason")); if (ev.isCancelled()) { this.close(this.getLeaveMessage(), ev.getKickMessage()); return; } this.server.addOnlinePlayer(this); this.loggedIn = true; if (this.isCreative()) { this.inventory.setHeldItemSlot(0); } else { this.inventory.setHeldItemSlot(this.inventory.getHotbarSlotIndex(0)); } if (this.isSpectator()) this.keepMovement = true; if (this.spawnPosition == null && this.namedTag.contains("SpawnLevel") && (level = this.server.getLevelByName(this.namedTag.getString("SpawnLevel"))) != null) { this.spawnPosition = new Position(this.namedTag.getInt("SpawnX"), this.namedTag.getInt("SpawnY"), this.namedTag.getInt("SpawnZ"), level); } Position spawnPosition = this.getSpawn(); StartGamePacket startGamePacket = new StartGamePacket(); startGamePacket.entityUniqueId = this.id; startGamePacket.entityRuntimeId = this.id; startGamePacket.playerGamemode = getClientFriendlyGamemode(this.gamemode); startGamePacket.x = (float) this.x; startGamePacket.y = (float) this.y; startGamePacket.z = (float) this.z; startGamePacket.yaw = (float) this.yaw; startGamePacket.pitch = (float) this.pitch; startGamePacket.seed = -1; startGamePacket.dimension = (byte) (spawnPosition.level.getDimension() & 0xff); startGamePacket.worldGamemode = getClientFriendlyGamemode(this.gamemode); startGamePacket.difficulty = this.server.getDifficulty(); startGamePacket.spawnX = (int) spawnPosition.x; startGamePacket.spawnY = (int) spawnPosition.y + (int) this.getEyeHeight(); startGamePacket.spawnZ = (int) spawnPosition.z; startGamePacket.hasAchievementsDisabled = true; startGamePacket.dayCycleStopTime = -1; startGamePacket.eduMode = false; startGamePacket.rainLevel = 0; startGamePacket.lightningLevel = 0; startGamePacket.commandsEnabled = this.isEnableClientCommand(); startGamePacket.levelId = ""; startGamePacket.worldName = this.getServer().getNetwork().getName(); startGamePacket.generator = 1; //0 old, 1 infinite, 2 flat this.dataPacket(startGamePacket); SetTimePacket setTimePacket = new SetTimePacket(); setTimePacket.time = this.level.getTime(); this.dataPacket(setTimePacket); this.setMovementSpeed(DEFAULT_SPEED); this.sendAttributes(); this.setNameTagVisible(true); this.setNameTagAlwaysVisible(true); this.setCanClimb(true); this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logIn", FastAppender.get(TextFormat.AQUA, this.username, TextFormat.WHITE), this.ip, String.valueOf(this.port), String.valueOf(this.id), this.level.getName(), String.valueOf(NukkitMath.round(this.x, 4)), String.valueOf(NukkitMath.round(this.y, 4)), String.valueOf(NukkitMath.round(this.z, 4)))); if (this.isOp()) { this.setRemoveFormat(false); } this.setEnableClientCommand(true); this.server.sendFullPlayerListData(this); this.forceMovement = this.teleportPosition = this.getPosition(); this.server.onPlayerLogin(this); ResourcePacksInfoPacket pk = new ResourcePacksInfoPacket(); ResourcePackManager manager = this.server.getResourcePackManager(); pk.resourcePackEntries = manager.getResourceStack(); pk.mustAccept = true; this.dataPacket(pk); } @Override protected void initEntity() { super.initEntity(); this.addDefaultWindows(); } public void handleDataPacket(DataPacket packet) { if (!connected) { return; } try (Timing timing = Timings.getReceiveDataPacketTiming(packet)) { DataPacketReceiveEvent ev = new DataPacketReceiveEvent(this, packet); this.server.getPluginManager().callEvent(ev); if(this.printPackets) { this.getServer().getLogger().info(TextFormat.AQUA + "[RECEIVE] " + TextFormat.WHITE + packet.getName()); } if (ev.isCancelled()) { timing.stopTiming(); return; } if (packet.pid() == ProtocolInfo.BATCH_PACKET) { timing.stopTiming(); this.server.getNetwork().processBatch((BatchPacket) packet, this); return; } Item item; Block block; packetswitch: switch (packet.pid()) { case ProtocolInfo.LOGIN_PACKET: if (this.loggedIn) { break; } LoginPacket loginPacket = (LoginPacket) packet; String message; if (loginPacket.getProtocol() < ProtocolInfo.CURRENT_PROTOCOL) { if (loginPacket.getProtocol() < ProtocolInfo.CURRENT_PROTOCOL) { message = "disconnectionScreen.outdatedClient"; this.sendPlayStatus(PlayStatusPacket.LOGIN_FAILED_CLIENT); } else { message = "disconnectionScreen.outdatedServer"; this.sendPlayStatus(PlayStatusPacket.LOGIN_FAILED_SERVER); } this.close("", message, false); break; } this.loginChainData = new ClientChainData(loginPacket); this.serverSettings = this.server.getDefaultServerSettings(); this.username = TextFormat.clean(this.loginChainData.getUsername()); this.displayName = this.username; this.iusername = this.username.toLowerCase(); this.setDataProperty(new StringEntityData(DATA_NAMETAG, this.username), false); if (this.server.getOnlinePlayers().size() >= this.server.getMaxPlayers() && this.kick(PlayerKickEvent.Reason.SERVER_FULL, "disconnectionScreen.serverFull", false)) { break; } this.randomClientId = this.loginChainData.getClientId(); this.uuid = this.loginChainData.getClientUUID(); this.rawUUID = Binary.writeUUID(this.uuid); boolean valid = true; int len = this.username.length(); if (len > 16 || len < 3) { valid = false; } for (int i = 0; i < len && valid; i++) { char c = this.username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == ' ' ) { continue; } valid = false; break; } if (!valid || Objects.equals(this.iusername, "rcon") || Objects.equals(this.iusername, "console")) { this.close("", "disconnectionScreen.invalidName"); break; } if (!this.loginChainData.getSkin().isValid()) { this.close("", "disconnectionScreen.invalidSkin"); break; } else { this.setSkin(this.loginChainData.getSkin()); } PlayerPreLoginEvent playerPreLoginEvent; this.server.getPluginManager().callEvent(playerPreLoginEvent = new PlayerPreLoginEvent(this, "Plugin reason")); if (playerPreLoginEvent.isCancelled()) { this.close("", playerPreLoginEvent.getKickMessage()); break; } this.sendPlayStatus(PlayStatusPacket.LOGIN_SUCCESS); ResourcePacksInfoPacket infoPacket = new ResourcePacksInfoPacket(); infoPacket.resourcePackEntries = this.server.getResourcePackManager().getResourceStack(); infoPacket.mustAccept = this.server.getForceResources(); this.dataPacket(infoPacket); break; case ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET: ResourcePackClientResponsePacket responsePacket = (ResourcePackClientResponsePacket) packet; switch (responsePacket.responseStatus) { case ResourcePackClientResponsePacket.STATUS_REFUSED: this.close("", "disconnectionScreen.noReason"); break; case ResourcePackClientResponsePacket.STATUS_SEND_PACKS: for (String id : responsePacket.packIds) { ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(id); if (resourcePack == null) { this.close("", "disconnectionScreen.resourcePack"); break; } ResourcePackDataInfoPacket dataInfoPacket = new ResourcePackDataInfoPacket(); dataInfoPacket.packId = resourcePack.getPackId(); dataInfoPacket.maxChunkSize = 1048576; //megabyte dataInfoPacket.chunkCount = resourcePack.getPackSize() / dataInfoPacket.maxChunkSize; dataInfoPacket.compressedPackSize = resourcePack.getPackSize(); dataInfoPacket.sha256 = resourcePack.getSha256(); this.dataPacket(dataInfoPacket); } break; case ResourcePackClientResponsePacket.STATUS_HAVE_ALL_PACKS: ResourcePackStackPacket stackPacket = new ResourcePackStackPacket(); stackPacket.mustAccept = this.server.getForceResources(); stackPacket.resourcePackStack = this.server.getResourcePackManager().getResourceStack(); this.dataPacket(stackPacket); break; case ResourcePackClientResponsePacket.STATUS_COMPLETED: this.processLogin(); break; } break; case ProtocolInfo.RESOURCE_PACK_CHUNK_REQUEST_PACKET: ResourcePackChunkRequestPacket requestPacket = (ResourcePackChunkRequestPacket) packet; ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(requestPacket.packId); if (resourcePack == null) { this.close("", "disconnectionScreen.resourcePack"); break; } ResourcePackChunkDataPacket dataPacket = new ResourcePackChunkDataPacket(); dataPacket.packId = resourcePack.getPackId(); dataPacket.chunkIndex = requestPacket.chunkIndex; dataPacket.data = resourcePack.getPackChunk(1048576 * requestPacket.chunkIndex, 1048576); dataPacket.progress = 1048576 * requestPacket.chunkIndex; this.dataPacket(dataPacket); break; case ProtocolInfo.PLAYER_INPUT_PACKET: if (!this.isAlive() || !this.spawned) { break; } PlayerInputPacket ipk = (PlayerInputPacket) packet; if (riding instanceof EntityMinecartAbstract) { ((EntityMinecartEmpty) riding).setCurrentSpeed(ipk.motionY); } break; case ProtocolInfo.MOVE_PLAYER_PACKET: if (this.teleportPosition != null) { break; } MovePlayerPacket movePlayerPacket = (MovePlayerPacket) packet; Vector3 newPos = new Vector3(movePlayerPacket.x, movePlayerPacket.y - this.getEyeHeight(), movePlayerPacket.z); if (newPos.distanceSquared(this) < 0.01 && movePlayerPacket.yaw % 360 == this.yaw && movePlayerPacket.pitch % 360 == this.pitch) { break; } boolean revert = false; if (!this.isAlive() || !this.spawned) { revert = true; this.forceMovement = new Vector3(this.x, this.y, this.z); } if (this.forceMovement != null && (newPos.distanceSquared(this.forceMovement) > 0.1 || revert)) { this.sendPosition(this.forceMovement, movePlayerPacket.yaw, movePlayerPacket.pitch, MovePlayerPacket.MODE_RESET); } else { movePlayerPacket.yaw %= 360; movePlayerPacket.pitch %= 360; if (movePlayerPacket.yaw < 0) { movePlayerPacket.yaw += 360; } this.setRotation(movePlayerPacket.yaw, movePlayerPacket.pitch); this.newPosition = newPos; this.forceMovement = null; } if (riding != null) { if (riding instanceof EntityBoat) { riding.setPositionAndRotation(this.temporalVector.setComponents(movePlayerPacket.x, movePlayerPacket.y - 1, movePlayerPacket.z), (movePlayerPacket.headYaw + 90) % 360, 0); } } break; case ProtocolInfo.ADVENTURE_SETTINGS_PACKET: //TODO: player abilities, check for other changes AdventureSettingsPacket adventureSettingsPacket = (AdventureSettingsPacket) packet; if (adventureSettingsPacket.getFlag(AdventureSettingsPacket.ALLOW_FLIGHT) && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT)) { this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server"); break; } PlayerToggleFlightEvent playerToggleFlightEvent = new PlayerToggleFlightEvent(this, adventureSettingsPacket.getFlag(AdventureSettingsPacket.ALLOW_FLIGHT)); this.server.getPluginManager().callEvent(playerToggleFlightEvent); if (playerToggleFlightEvent.isCancelled()) { this.getAdventureSettings().update(); } else { this.getAdventureSettings().set(Type.FLYING, playerToggleFlightEvent.isFlying()); } break; case ProtocolInfo.MOB_EQUIPMENT_PACKET: if (!this.spawned || !this.isAlive()) { break; } MobEquipmentPacket mobEquipmentPacket = (MobEquipmentPacket) packet; Item item1 = this.inventory.getItem(mobEquipmentPacket.hotbarSlot); if (!item1.equals(mobEquipmentPacket.item)) { this.server.getLogger().debug("Tried to equip " + mobEquipmentPacket.item + " but have " + item1 + " in target slot"); this.inventory.sendContents(this); return; } this.inventory.equipItem(mobEquipmentPacket.hotbarSlot); this.setDataFlag(Player.DATA_FLAGS, Player.DATA_FLAG_ACTION, false); break; case ProtocolInfo.PLAYER_ACTION_PACKET: PlayerActionPacket playerActionPacket = (PlayerActionPacket) packet; if (!this.spawned || (!this.isAlive() && playerActionPacket.action != PlayerActionPacket.ACTION_RESPAWN && playerActionPacket.action != PlayerActionPacket.ACTION_DIMENSION_CHANGE_REQUEST)) { break; } playerActionPacket.entityRuntimeId = this.id; Vector3 pos = new Vector3(playerActionPacket.x, playerActionPacket.y, playerActionPacket.z); BlockFace face = BlockFace.fromIndex(playerActionPacket.face); switch (playerActionPacket.action) { case PlayerActionPacket.ACTION_START_BREAK: if (this.lastBreak != Long.MAX_VALUE || pos.distanceSquared(this) > 100) { break; } Block target = this.level.getBlock(pos); PlayerInteractEvent playerInteractEvent = new PlayerInteractEvent(this, this.inventory.getItemInHand(), target, face, target.getId() == 0 ? Action.LEFT_CLICK_AIR : Action.LEFT_CLICK_BLOCK); this.getServer().getPluginManager().callEvent(playerInteractEvent); if (playerInteractEvent.isCancelled()) { this.inventory.sendHeldItem(this); break; } if (target.getId() == Block.NOTEBLOCK) { ((BlockNoteblock) target).emitSound(); break; } Block block1 = target.getSide(face); if (block1.getId() == Block.FIRE) { this.level.setBlock(block1, new BlockAir(), true); break; } if (!this.isCreative()) { //improved this to take stuff like swimming, ladders, enchanted tools into account, fix wrong tool break time calculations for bad tools (pmmp/PocketMine-MP#211) //Done by lmlstarqaq double breakTime = Math.ceil(target.getBreakTime(this.inventory.getItemInHand(), this) * 20); if (breakTime > 0) { LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_BLOCK_START_BREAK; pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; pk.data = (int) (65535 / breakTime); this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); } } this.breakingBlock = target; this.lastBreak = System.currentTimeMillis(); break; case PlayerActionPacket.ACTION_ABORT_BREAK: this.lastBreak = Long.MAX_VALUE; this.breakingBlock = null; case PlayerActionPacket.ACTION_STOP_BREAK: LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_BLOCK_STOP_BREAK; pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; pk.data = 0; this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); this.breakingBlock = null; break; case PlayerActionPacket.ACTION_GET_UPDATED_BLOCK: break; //TODO case PlayerActionPacket.ACTION_DROP_ITEM: break; //TODO case PlayerActionPacket.ACTION_STOP_SLEEPING: this.stopSleep(); break; case PlayerActionPacket.ACTION_RESPAWN: if (!this.spawned || this.isAlive() || !this.isOnline()) { break; } if (this.server.isHardcore()) { this.setBanned(true); break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); PlayerRespawnEvent playerRespawnEvent = new PlayerRespawnEvent(this, this.getSpawn()); this.server.getPluginManager().callEvent(playerRespawnEvent); Position respawnPos = playerRespawnEvent.getRespawnPosition(); this.teleport(respawnPos, null); RespawnPacket respawnPacket = new RespawnPacket(); respawnPacket.x = (float) respawnPos.x; respawnPacket.y = (float) respawnPos.y; respawnPacket.z = (float) respawnPos.z; this.dataPacket(respawnPacket); this.setSprinting(false, true); this.setSneaking(false); this.extinguish(); this.setDataProperty(new ShortEntityData(Player.DATA_AIR, 400), false); this.deadTicks = 0; this.noDamageTicks = 60; this.removeAllEffects(); this.setHealth(this.getMaxHealth()); this.getFoodData().setLevel(20, 20); this.sendData(this); this.setMovementSpeed(DEFAULT_SPEED); this.getAdventureSettings().update(); this.inventory.sendContents(this); this.inventory.sendArmorContents(this); this.spawnToAll(); this.scheduleUpdate(); break; case PlayerActionPacket.ACTION_JUMP: break packetswitch; case PlayerActionPacket.ACTION_START_SPRINT: PlayerToggleSprintEvent playerToggleSprintEvent = new PlayerToggleSprintEvent(this, true); this.server.getPluginManager().callEvent(playerToggleSprintEvent); if (playerToggleSprintEvent.isCancelled()) { this.sendData(this); } else { this.setSprinting(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_SPRINT: playerToggleSprintEvent = new PlayerToggleSprintEvent(this, false); this.server.getPluginManager().callEvent(playerToggleSprintEvent); if (playerToggleSprintEvent.isCancelled()) { this.sendData(this); } else { this.setSprinting(false); } break packetswitch; case PlayerActionPacket.ACTION_START_SNEAK: PlayerToggleSneakEvent playerToggleSneakEvent = new PlayerToggleSneakEvent(this, true); this.server.getPluginManager().callEvent(playerToggleSneakEvent); if (playerToggleSneakEvent.isCancelled()) { this.sendData(this); } else { this.setSneaking(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_SNEAK: playerToggleSneakEvent = new PlayerToggleSneakEvent(this, false); this.server.getPluginManager().callEvent(playerToggleSneakEvent); if (playerToggleSneakEvent.isCancelled()) { this.sendData(this); } else { this.setSneaking(false); } break packetswitch; case PlayerActionPacket.ACTION_DIMENSION_CHANGE_ACK: break; //TODO case PlayerActionPacket.ACTION_START_GLIDE: PlayerToggleGlideEvent playerToggleGlideEvent = new PlayerToggleGlideEvent(this, true); this.server.getPluginManager().callEvent(playerToggleGlideEvent); if (playerToggleGlideEvent.isCancelled()) { this.sendData(this); } else { this.setGliding(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_GLIDE: playerToggleGlideEvent = new PlayerToggleGlideEvent(this, false); this.server.getPluginManager().callEvent(playerToggleGlideEvent); if (playerToggleGlideEvent.isCancelled()) { this.sendData(this); } else { this.setGliding(false); } break packetswitch; case PlayerActionPacket.ACTION_CONTINUE_BREAK: if (this.isBreakingBlock()) { block1 = this.level.getBlock(pos); this.level.addParticle(new PunchBlockParticle(pos, block1, face)); } break; } this.startAction = -1; this.setDataFlag(Player.DATA_FLAGS, Player.DATA_FLAG_ACTION, false); break; case ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET: break; case ProtocolInfo.INTERACT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); InteractPacket interactPacket = (InteractPacket) packet; Entity targetEntity = this.level.getEntity(interactPacket.target); if (targetEntity == null || !this.isAlive() || !targetEntity.isAlive()) { break; } if (targetEntity instanceof EntityItem || targetEntity instanceof EntityArrow || targetEntity instanceof EntityXPOrb) { this.kick(PlayerKickEvent.Reason.INVALID_PVE, "Attempting to interact with an invalid entity"); this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidEntity", this.getName())); break; } item1 = this.inventory.getItemInHand(); switch (interactPacket.action) { case InteractPacket.ACTION_MOUSEOVER: this.getServer().getPluginManager().callEvent(new PlayerMouseOverEntityEvent(this, targetEntity)); break; /* case InteractPacket.ACTION_VEHICLE_EXIT: if (!(targetEntity instanceof EntityRideable) || this.riding == null) { break; } ((EntityRideable) riding).mountEntity(this); break; */ } break; case ProtocolInfo.BLOCK_PICK_REQUEST_PACKET: BlockPickRequestPacket pickRequestPacket = (BlockPickRequestPacket) packet; Block block1 = this.level.getBlock(this.temporalVector.setComponents(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); item1 = block1.toItem(); if (pickRequestPacket.addUserData) { BlockEntity blockEntity = this.getLevel().getBlockEntity(new Vector3(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); if (blockEntity != null) { CompoundTag nbt = blockEntity.getCleanedNBT(); if (nbt != null) { Item item11 = this.getInventory().getItemInHand(); item11.setCustomBlockData(nbt); item11.setLore("+(DATA)"); this.getInventory().setItemInHand(item11); } } } PlayerBlockPickEvent pickEvent = new PlayerBlockPickEvent(this, block1, item1); if (!this.isCreative()) { this.server.getLogger().debug("Got block-pick request from " + this.getName() + " when not in creative mode (gamemode " + this.getGamemode() + ")"); pickEvent.setCancelled(); } this.server.getPluginManager().callEvent(pickEvent); if (!pickEvent.isCancelled()) { this.inventory.setItemInHand(pickEvent.getItem()); } break; case ProtocolInfo.ANIMATE_PACKET: if (!this.spawned || !this.isAlive()) { break; } PlayerAnimationEvent animationEvent = new PlayerAnimationEvent(this, ((AnimatePacket) packet).action); this.server.getPluginManager().callEvent(animationEvent); if (animationEvent.isCancelled()) { break; } AnimatePacket animatePacket = new AnimatePacket(); animatePacket.entityRuntimeId = this.getId(); animatePacket.action = animationEvent.getAnimationType(); Server.broadcastPacket(this.getViewers().values(), animatePacket); break; case ProtocolInfo.SET_HEALTH_PACKET: //use UpdateAttributePacket instead break; case ProtocolInfo.ENTITY_EVENT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); //this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); //TODO: check if this should be true EntityEventPacket entityEventPacket = (EntityEventPacket) packet; switch (entityEventPacket.event) { case EntityEventPacket.USE_ITEM: //Eating Item itemInHand = this.inventory.getItemInHand(); PlayerItemConsumeEvent consumeEvent = new PlayerItemConsumeEvent(this, itemInHand); this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } if (itemInHand.getId() == Item.POTION) { Potion potion = Potion.getPotion(itemInHand.getDamage()).setSplash(false); if (this.getGamemode() == SURVIVAL) { if (itemInHand.getCount() > 1) { ItemGlassBottle bottle = new ItemGlassBottle(); if (this.inventory.canAddItem(bottle)) { this.inventory.addItem(bottle); } --itemInHand.count; } else { itemInHand = new ItemGlassBottle(); } } if (potion != null) { potion.applyPotion(this); } } else { EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getId(); pk.event = EntityEventPacket.USE_ITEM; this.dataPacket(pk); Server.broadcastPacket(this.getViewers().values(), pk); Food food = Food.getByRelative(itemInHand); if (food != null) if (food.eatenBy(this)) --itemInHand.count; } this.inventory.setItemInHand(itemInHand); this.inventory.sendHeldItem(this); break; /*case EntityEventPacket.CONSUME_ITEM: EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getId(); pk.event = EntityEventPacket.CONSUME_ITEM; pk.itemId = this.inventory.getItemInHand().getId(); Server.broadcastPacket(this.getViewers().values(), pk); this.dataPacket(pk); break;*/ } break; case ProtocolInfo.COMMAND_REQUEST_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = 0; CommandRequestPacket commandRequestPacket = (CommandRequestPacket) packet; PlayerCommandPreprocessEvent playerCommandPreprocessEvent = new PlayerCommandPreprocessEvent(this, commandRequestPacket.command); this.server.getPluginManager().callEvent(playerCommandPreprocessEvent); if (playerCommandPreprocessEvent.isCancelled()) { break; } Timings.playerCommandTimer.startTiming(); this.server.dispatchCommand(playerCommandPreprocessEvent.getPlayer(), playerCommandPreprocessEvent.getMessage().substring(1)); Timings.playerCommandTimer.stopTiming(); break; case ProtocolInfo.TEXT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); TextPacket textPacket = (TextPacket) packet; if (textPacket.type == TextPacket.TYPE_CHAT) { textPacket.message = this.removeFormat ? TextFormat.clean(textPacket.message) : textPacket.message; for (String msg : textPacket.message.split("\n")) { if (!"".equals(msg.trim()) && msg.length() <= 255 && this.messageCounter-- > 0) { PlayerChatEvent chatEvent = new PlayerChatEvent(this, msg); this.server.getPluginManager().callEvent(chatEvent); if (!chatEvent.isCancelled()) { this.server.broadcastMessage(this.getServer().getLanguage().translateString(chatEvent.getFormat(), new String[]{chatEvent.getPlayer().getDisplayName(), chatEvent.getMessage()}), chatEvent.getRecipients()); } } } } break; case ProtocolInfo.CONTAINER_CLOSE_PACKET: ContainerClosePacket containerClosePacket = (ContainerClosePacket) packet; if (!this.spawned || containerClosePacket.windowId == 0) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); if (this.windowIndex.containsKey(containerClosePacket.windowId)) { /* * TODO PreSignChangeEvent * 看板を変更する画面を閉じたときにだけ呼ぶイベント。 * XがウィンドウIDだが、それが看板(未調査)の場合のみ実行。 if(containerClosePacket.windowid == X){ PreSignChangeEvent presignchangeevent = new PreSignChangeEvent(blockEntity.getBlock(), this, new String[]{ signText1, signText2, signText3, signText4 }); if (!blockEntity.namedTag.contains("Creator") || !Objects.equals(this.getUniqueId().toString(), blockEntity.namedTag.getString("Creator"))) { presignchangeevent.setCancelled(); } this.server.getPluginManager().callEvent(presignchangeevent); } */ this.server.getPluginManager().callEvent(new InventoryCloseEvent(this.windowIndex.get(containerClosePacket.windowId), this)); this.removeWindow(this.windowIndex.get(containerClosePacket.windowId)); } else { this.windowIndex.remove(containerClosePacket.windowId); } break; case ProtocolInfo.CRAFTING_EVENT_PACKET: CraftingEventPacket craftingEventPacket = (CraftingEventPacket) packet; if (!this.spawned || !this.isAlive()) { break; } Recipe recipe = this.server.getCraftingManager().getRecipe(craftingEventPacket.id); Recipe[] recipes = this.server.getCraftingManager().getRecipesByResult(craftingEventPacket.output[0]); boolean isValid = false; for (Recipe rec : recipes){ if (rec.getId().equals(recipe.getId())) { isValid = true; break; } } if (isValid) recipes = new Recipe[]{recipe}; if (!this.windowIndex.containsKey(craftingEventPacket.windowId)) { this.inventory.sendContents(this); containerClosePacket = new ContainerClosePacket(); containerClosePacket.windowId = craftingEventPacket.windowId; this.dataPacket(containerClosePacket); break; } if (isValid && (recipe == null || (((recipe instanceof BigShapelessRecipe) || (recipe instanceof BigShapedRecipe)) && this.craftingType == CRAFTING_SMALL))) { this.inventory.sendContents(this); break; } for (int i = 0; i < craftingEventPacket.input.length; i++) { Item inputItem = craftingEventPacket.input[i]; if (inputItem.getDamage() == -1 || inputItem.getDamage() == 0xffff) { inputItem.setDamage(null); } if (i < 9 && inputItem.getId() > 0) { inputItem.setCount(1); } } boolean canCraft = true; Map<String, Item> realSerialized = new HashMap<>(); for (Recipe rec : recipes) { ArrayList<Item> ingredientz = new ArrayList<>(); if (rec == null || (((rec instanceof BigShapelessRecipe) || (rec instanceof BigShapedRecipe)) && this.craftingType == CRAFTING_SMALL)) { continue; } if (rec instanceof ShapedRecipe) { Map<Integer, Map<Integer, Item>> ingredients = ((ShapedRecipe) rec).getIngredientMap(); for (Map<Integer, Item> map : ingredients.values()) { for (Item ingredient : map.values()) { if (ingredient != null && ingredient.getId() != Item.AIR) { ingredientz.add(ingredient); } } } } else if (recipe instanceof ShapelessRecipe) { ShapelessRecipe recipe0 = (ShapelessRecipe) recipe; for (Item ingredient : recipe0.getIngredientList()) { if (ingredient != null && ingredient.getId() != Item.AIR) { ingredientz.add(ingredient); } } } Map<String, Item> serialized = new HashMap<>(); for (Item ingredient : ingredientz) { String hash = ingredient.getId() + ":" + ingredient.getDamage(); Item r = serialized.get(hash); if (r != null) { r.count += ingredient.getCount(); continue; } serialized.put(hash, ingredient); } boolean isPossible = true; for (Item ingredient : serialized.values()) { if (!this.craftingGrid.contains(ingredient)) { if (isValid) { canCraft = false; break; } else { isPossible = false; break; } } } if (!isPossible) continue; recipe = rec; realSerialized = serialized; break; } if (!canCraft) { this.server.getLogger().debug("(1) Unmatched recipe " + craftingEventPacket.id + " from player " + this.getName() + " not anough ingredients"); return; } CraftItemEvent craftItemEvent = new CraftItemEvent(this, realSerialized.values().stream().toArray(Item[]::new), recipe); getServer().getPluginManager().callEvent(craftItemEvent); if (craftItemEvent.isCancelled()) { this.inventory.sendContents(this); break; } for (Item ingredient : realSerialized.values()) { this.craftingGrid.removeFromAll(ingredient); } this.inventory.addItem(recipe.getResult()); /* switch (recipe.getResult().getId()) { case Item.WORKBENCH: this.awardAchievement("buildWorkBench"); break; case Item.WOODEN_PICKAXE: this.awardAchievement("buildPickaxe"); break; case Item.FURNACE: this.awardAchievement("buildFurnace"); break; case Item.WOODEN_HOE: this.awardAchievement("buildHoe"); break; case Item.BREAD: this.awardAchievement("makeBread"); break; case Item.CAKE: //TODO: detect complex recipes like cake that leave remains this.awardAchievement("bakeCake"); this.inventory.addItem(new ItemBucket(0, 3)); break; case Item.STONE_PICKAXE: case Item.GOLD_PICKAXE: case Item.IRON_PICKAXE: case Item.DIAMOND_PICKAXE: this.awardAchievement("buildBetterPickaxe"); break; case Item.WOODEN_SWORD: this.awardAchievement("buildSword"); break; case Item.DIAMOND: this.awardAchievement("diamond"); break; default: break; } */ break; case ProtocolInfo.BLOCK_ENTITY_DATA_PACKET: if (!this.spawned || !this.isAlive()) { break; } BlockEntityDataPacket blockEntityDataPacket = (BlockEntityDataPacket) packet; this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); pos = new Vector3(blockEntityDataPacket.x, blockEntityDataPacket.y, blockEntityDataPacket.z); if (pos.distanceSquared(this) > 10000) { break; } BlockEntity t = this.level.getBlockEntity(pos); if (t instanceof BlockEntitySign) { CompoundTag nbt; try { nbt = NBTIO.read(blockEntityDataPacket.namedTag, ByteOrder.LITTLE_ENDIAN, true); } catch (IOException e) { throw new RuntimeException(e); } if (!BlockEntity.SIGN.equals(nbt.getString("id"))) { ((BlockEntitySign) t).spawnTo(this); } else { String[] texts = nbt.getString("Text").split("\n"); blockEntity = t; signText1 = texts.length > 0 ? texts[0] : ""; signText2 = texts.length > 1 ? texts[1] : ""; signText3 = texts.length > 2 ? texts[2] : ""; signText4 = texts.length > 3 ? texts[3] : ""; signText1 = this.removeFormat ? TextFormat.clean(signText1) : signText1; signText2 = this.removeFormat ? TextFormat.clean(signText2) : signText2; signText3 = this.removeFormat ? TextFormat.clean(signText3) : signText3; signText4 = this.removeFormat ? TextFormat.clean(signText4) : signText4; SignChangeEvent signChangeEvent = new SignChangeEvent(blockEntity.getBlock(), this, new String[]{ signText1, signText2, signText3, signText4 }); if (!t.namedTag.contains("Creator") || !Objects.equals(this.getUniqueId().toString(), t.namedTag.getString("Creator"))) { signChangeEvent.setCancelled(); } this.server.getPluginManager().callEvent(signChangeEvent); if (!signChangeEvent.isCancelled()) { ((BlockEntitySign) t).setText(signChangeEvent.getLine(0), signChangeEvent.getLine(1), signChangeEvent.getLine(2), signChangeEvent.getLine(3)); } else { ((BlockEntitySign) t).spawnTo(this); } } } else if (t instanceof BlockEntityBeacon) { CompoundTag nbt; try { nbt = NBTIO.read(blockEntityDataPacket.namedTag, ByteOrder.LITTLE_ENDIAN, true); } catch (IOException e) { throw new RuntimeException(e); } if (!BlockEntity.BEACON.equals(nbt.getString("id"))) { ((BlockEntitySign) t).spawnTo(this); } else { BlockEntityBeacon beacon = (BlockEntityBeacon) t; beacon.setPrimary(nbt.getInt("primary")); beacon.setSecondary(nbt.getInt("secondary")); BeaconInventory inventory = this.getBeacoInventory(); if (inventory != null) { inventory.setItem(0, Item.get(0)); } } } break; case ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET: RequestChunkRadiusPacket requestChunkRadiusPacket = (RequestChunkRadiusPacket) packet; ChunkRadiusUpdatedPacket chunkRadiusUpdatePacket = new ChunkRadiusUpdatedPacket(); this.chunkRadius = Math.max(3, Math.min(requestChunkRadiusPacket.radius, this.viewDistance)); chunkRadiusUpdatePacket.radius = this.chunkRadius; this.dataPacket(chunkRadiusUpdatePacket); break; case ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET: SetPlayerGameTypePacket setPlayerGameTypePacket = (SetPlayerGameTypePacket) packet; if (setPlayerGameTypePacket.gamemode != this.gamemode) { if (!this.hasPermission("nukkit.command.gamemode")) { SetPlayerGameTypePacket setPlayerGameTypePacket1 = new SetPlayerGameTypePacket(); setPlayerGameTypePacket1.gamemode = this.gamemode & 0x01; this.dataPacket(setPlayerGameTypePacket1); this.getAdventureSettings().update(); break; } this.setGamemode(setPlayerGameTypePacket.gamemode, true); Command.broadcastCommandMessage(this, new TranslationContainer("commands.gamemode.success.self", Server.getGamemodeString(this.gamemode))); } break; case ProtocolInfo.ITEM_FRAME_DROP_ITEM_PACKET: ItemFrameDropItemPacket itemFrameDropItemPacket = (ItemFrameDropItemPacket) packet; Vector3 vector3 = this.temporalVector.setComponents(itemFrameDropItemPacket.x, itemFrameDropItemPacket.y, itemFrameDropItemPacket.z); BlockEntity blockEntityItemFrame = this.level.getBlockEntity(vector3); BlockEntityItemFrame itemFrame = (BlockEntityItemFrame) blockEntityItemFrame; if (itemFrame != null) { block1 = itemFrame.getBlock(); Item itemDrop = itemFrame.getItem(); ItemFrameDropItemEvent itemFrameDropItemEvent = new ItemFrameDropItemEvent(this, block1, itemFrame, itemDrop); this.server.getPluginManager().callEvent(itemFrameDropItemEvent); if (!itemFrameDropItemEvent.isCancelled()) { if (itemDrop.getId() != Item.AIR) { vector3 = this.temporalVector.setComponents(itemFrame.x + 0.5, itemFrame.y, itemFrame.z + 0.5); this.level.dropItem(vector3, itemDrop); itemFrame.setItem(new ItemBlock(new BlockAir())); itemFrame.setItemRotation(0); this.getLevel().addSound(new ItemFrameItemRemovedSound(this)); } } else { itemFrame.spawnTo(this); } } break; case ProtocolInfo.MAP_INFO_REQUEST_PACKET: MapInfoRequestPacket pk = (MapInfoRequestPacket) packet; Item mapItem = null; for (Item item11 : this.inventory.getContents().values()) { if (item11 instanceof ItemMap && ((ItemMap) item11).getMapId() == pk.mapId) { mapItem = item11; } } if (mapItem == null) { for (BlockEntity be : this.level.getBlockEntities().values()) { if (be instanceof BlockEntityItemFrame) { BlockEntityItemFrame itemFrame1 = (BlockEntityItemFrame) be; if (itemFrame1.getItem() instanceof ItemMap && ((ItemMap) itemFrame1.getItem()).getMapId() == pk.mapId) { ((ItemMap) itemFrame1.getItem()).sendImage(this); break; } } } } if (mapItem != null) { PlayerMapInfoRequestEvent event; getServer().getPluginManager().callEvent(event = new PlayerMapInfoRequestEvent(this, mapItem)); if (!event.isCancelled()) { ((ItemMap) mapItem).sendImage(this); } } break; case ProtocolInfo.MODAL_FORM_RESPONSE_PACKET: ModalFormResponsePacket modalFormResponsePacket = (ModalFormResponsePacket) packet; if(this.activeWindow != null && this.activeWindow.getId() == modalFormResponsePacket.formId) { if (modalFormResponsePacket.data.trim().equals("null")) { PlayerModalFormCloseEvent mfce = new PlayerModalFormCloseEvent(this, modalFormResponsePacket.formId, this.activeWindow); this.activeWindow = null; this.getServer().getPluginManager().callEvent(mfce); } else { this.activeWindow.setResponse(modalFormResponsePacket.data); PlayerModalFormResponseEvent mfre = new PlayerModalFormResponseEvent(this, modalFormResponsePacket.formId, this.activeWindow); this.activeWindow = null; this.getServer().getPluginManager().callEvent(mfre); } } else { this.serverSettings.get(modalFormResponsePacket.formId).setResponse(modalFormResponsePacket.data); PlayerServerSettingsChangedEvent ssce = new PlayerServerSettingsChangedEvent(this, modalFormResponsePacket.formId, this.serverSettings.get(modalFormResponsePacket.formId)); this.getServer().getPluginManager().callEvent(ssce); } break; case ProtocolInfo.COMMAND_BLOCK_UPDATE_PACKET: if (!(this.isOp() && this.isCreative())) { break; } CommandBlockUpdatePacket update = (CommandBlockUpdatePacket) packet; if (update.isBlock) { Vector3 commandPos = new Vector3(update.x, update.y, update.z); block1 = this.level.getBlock(commandPos); if (block1 instanceof BlockCommand) { BlockEntityCommandBlock blockEntity = ((BlockCommand)block1).getBlockEntity(); if (blockEntity == null) { break; } Block place = Block.get(Block.COMMAND_BLOCK); switch (update.commandBlockMode) { case 0: place = Block.get(Block.COMMAND_BLOCK); place.setDamage(block1.getDamage()); break; case 1: place = Block.get(Block.REPEATING_COMMAND_BLOCK); place.setDamage(block1.getDamage()); break; case 2: place = Block.get(Block.CHAIN_COMMAND_BLOCK); place.setDamage(block1.getDamage()); break; } if (update.isConditional) { if (place.getDamage() < 8) { place.setDamage(place.getDamage() + 8); } } else { if (place.getDamage() > 8) { place.setDamage(place.getDamage() - 8); } } this.level.setBlock(block1, place, false, false); blockEntity = (BlockEntityCommandBlock) blockEntity.clone(); blockEntity.setName(update.name); blockEntity.setMode(update.commandBlockMode); blockEntity.setCommand(update.command); blockEntity.setLastOutPut(update.lastOutput); blockEntity.setAuto(!update.isRedstoneMode); blockEntity.setConditions(update.isConditional); blockEntity.spawnToAll(); } } else { //MinercartCommandBlock } break; case ProtocolInfo.LEVEL_SOUND_EVENT_PACKET: //LevelSoundEventPacket levelSoundEventPacket = (LevelSoundEventPacket) packet; //We just need to broadcast this packet to all viewers. this.level.addChunkPacket(this.getFloorX() >> 4, this.getFloorZ() >> 4, packet); break; case ProtocolInfo.INVENTORY_TRANSACTION_PACKET: InventoryTransactionPacket transactionPacket = (InventoryTransactionPacket) packet; boolean isCrafting = false; List<InventoryAction> actions = new ArrayList<>(); for (NetworkInventoryAction networkInventoryAction : transactionPacket.actions) { try { InventoryAction a = networkInventoryAction.createInventoryAction(this); if (a != null) { if (a instanceof SlotChangeAction) { if (((SlotChangeAction) a).getInventory() instanceof CraftingGrid) isCrafting = true; } actions.add(a); } } catch (Throwable e) { MainLogger.getLogger().debug("Unhandled inventory action from " + this.getName() + ": " + e.getMessage()); this.sendAllInventories(); break packetswitch; } } switch (transactionPacket.transactionType) { case InventoryTransactionPacket.TYPE_NORMAL: if (this.isSpectator()) { this.sendAllInventories(); break; } InventoryTransaction transaction = new SimpleInventoryTransaction(this, actions); if (!transaction.execute() && !isCrafting) { for (Inventory inventory : transaction.getInventories()) { inventory.sendContents(this); if (inventory instanceof PlayerInventory) { ((PlayerInventory) inventory).sendArmorContents(this); } } MainLogger.getLogger().debug("Failed to execute inventory transaction from " + this.getName() + " with actions: " + Arrays.toString(actions.stream().toArray())); //TODO: check more stuff that might need reversion break packetswitch; //oops! } //TODO: fix achievement for getting iron from furnace break packetswitch; case InventoryTransactionPacket.TYPE_MISMATCH: if (transactionPacket.actions.length > 0) { this.server.getLogger().debug("Expected 0 actions for mismatch, got " + transactionPacket.actions.length + ", " + Arrays.toString(transactionPacket.actions)); } this.sendAllInventories(); break packetswitch; case InventoryTransactionPacket.TYPE_USE_ITEM: UseItemData useItemData = (UseItemData) transactionPacket.transactionData; BlockVector3 blockVector = useItemData.blockPos; face = useItemData.face; int type = useItemData.actionType; switch (type) { case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_BLOCK: this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 13 : 7)) { if (this.isCreative()) { Item i = inventory.getItemInHand(); if (this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this) != null) { break packetswitch; } } else if (inventory.getItemInHand().equals(useItemData.itemInHand)) { Item i = inventory.getItemInHand(); Item oldItem = i.clone(); //TODO: Implement adventure mode checks if ((i = this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this)) != null) { if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { inventory.setItemInHand(i); inventory.sendHeldItem(this.getViewers().values()); } break packetswitch; } } } inventory.sendHeldItem(this); if (blockVector.distanceSquared(this) > 10000) { break packetswitch; } Block target = this.level.getBlock(blockVector.asVector3()); block = target.getSide(face); this.level.sendBlocks(new Player[]{this}, new Block[]{target, block}, UpdateBlockPacket.FLAG_ALL_PRIORITY); if (target instanceof BlockDoor) { BlockDoor door = (BlockDoor) target; Block part; if ((door.getDamage() & 0x08) > 0) { //up part = target.down(); if (part.getId() == target.getId()) { target = part; this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); } } } break packetswitch; case InventoryTransactionPacket.USE_ITEM_ACTION_BREAK_BLOCK: if (!this.spawned || !this.isAlive()) { break packetswitch; } this.resetCraftingGridType(); Item i = this.getInventory().getItemInHand(); Item oldItem = i.clone(); if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 13 : 7) && (i = this.level.useBreakOn(blockVector.asVector3(), i, this, true)) != null) { if (this.isSurvival()) { this.getFoodData().updateFoodExpLevel(0.025); if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { inventory.setItemInHand(i); inventory.sendHeldItem(this.getViewers().values()); } } break packetswitch; } inventory.sendContents(this); target = this.level.getBlock(blockVector.asVector3()); BlockEntity blockEntity = this.level.getBlockEntity(blockVector.asVector3()); this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); inventory.sendHeldItem(this); if (blockEntity instanceof BlockEntitySpawnable) { ((BlockEntitySpawnable) blockEntity).spawnTo(this); } break packetswitch; case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_AIR: Vector3 directionVector = this.getDirectionVector(); if (this.isCreative()) { item1 = this.inventory.getItemInHand(); } else if (!this.inventory.getItemInHand().equals(useItemData.itemInHand)) { this.inventory.sendHeldItem(this); break packetswitch; } else { item1 = this.inventory.getItemInHand(); } PlayerInteractEvent interactEvent = new PlayerInteractEvent(this, item1, directionVector, face, Action.RIGHT_CLICK_AIR); this.server.getPluginManager().callEvent(interactEvent); if (interactEvent.isCancelled()) { this.inventory.sendHeldItem(this); break packetswitch; } if (item1.onClickAir(this, directionVector) && this.isSurvival()) { this.inventory.setItemInHand(item1); } this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, true); this.startAction = this.server.getTick(); break packetswitch; default: //unknown break; } break; case InventoryTransactionPacket.TYPE_USE_ITEM_ON_ENTITY: UseItemOnEntityData useItemOnEntityData = (UseItemOnEntityData) transactionPacket.transactionData; Entity target = this.level.getEntity(useItemOnEntityData.entityRuntimeId); if (target == null) { return; } type = useItemOnEntityData.actionType; if (!useItemOnEntityData.itemInHand.equalsExact(this.inventory.getItemInHand())) { this.inventory.sendHeldItem(this); } item1 = this.inventory.getItemInHand(); switch (type) { case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_INTERACT: PlayerInteractEntityEvent playerInteractEntityEvent = new PlayerInteractEntityEvent(this, target, item1); if (this.isSpectator()) playerInteractEntityEvent.setCancelled(); getServer().getPluginManager().callEvent(playerInteractEntityEvent); if (playerInteractEntityEvent.isCancelled()) { break; } if (target.onInteract(this, item1) && this.isSurvival()) { if (item1.isTool()) { if (item1.useOn(target) && item1.getDamage() >= item1.getMaxDurability()) { item1 = new ItemBlock(new BlockAir()); } } else { if (item1.count > 1) { item1.count--; } else { item1 = new ItemBlock(new BlockAir()); } } this.inventory.setItemInHand(item1); } break; case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_ATTACK: float itemDamage = item1.getAttackDamage(); for (Enchantment enchantment : item1.getEnchantments()) { itemDamage += enchantment.getDamageBonus(target); } Map<DamageModifier, Float> damage = new EnumMap<>(DamageModifier.class); damage.put(DamageModifier.BASE, itemDamage); if (!this.canInteract(target, isCreative() ? 8 : 5)) { break; } else if (target instanceof Player) { if ((((Player) target).getGamemode() & 0x01) > 0) { break; } else if (!this.server.getPropertyBoolean("pvp") || this.server.getDifficulty() == 0) { break; } } EntityDamageByEntityEvent entityDamageByEntityEvent = new EntityDamageByEntityEvent(this, target, DamageCause.ENTITY_ATTACK, damage); if (this.isSpectator()) entityDamageByEntityEvent.setCancelled(); if (!target.attack(entityDamageByEntityEvent)) { if (item1.isTool() && this.isSurvival()) { this.inventory.sendContents(this); } break; } for (Enchantment enchantment : item1.getEnchantments()) { enchantment.doPostAttack(this, target); } if (item1.isTool() && this.isSurvival()) { if (item1.useOn(target) && item1.getDamage() >= item1.getMaxDurability()) { this.inventory.setItemInHand(new ItemBlock(new BlockAir())); } else { this.inventory.setItemInHand(item1); } } return; default: break; //unknown } break; case InventoryTransactionPacket.TYPE_RELEASE_ITEM: if (this.isSpectator()) { this.sendAllInventories(); break packetswitch; } ReleaseItemData releaseItemData = (ReleaseItemData) transactionPacket.transactionData; try { type = releaseItemData.actionType; switch (type) { case InventoryTransactionPacket.RELEASE_ITEM_ACTION_RELEASE: if (this.isUsingItem()) { item1 = this.inventory.getItemInHand(); if (item1.onReleaseUsing(this)) { this.inventory.setItemInHand(item1); } } else { this.inventory.sendContents(this); } return; case InventoryTransactionPacket.RELEASE_ITEM_ACTION_CONSUME: Item itemInHand = this.inventory.getItemInHand(); PlayerItemConsumeEvent consumeEvent = new PlayerItemConsumeEvent(this, itemInHand); if (itemInHand.getId() == Item.POTION) { this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } Potion potion = Potion.getPotion(itemInHand.getDamage()).setSplash(false); if (this.getGamemode() == SURVIVAL) { --itemInHand.count; this.inventory.setItemInHand(itemInHand); this.inventory.addItem(new ItemGlassBottle()); } if (potion != null) { potion.applyPotion(this); } } else if (itemInHand.getId() == Item.BUCKET && itemInHand.getDamage() == 1) { //milk this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } EntityEventPacket eventPacket = new EntityEventPacket(); eventPacket.entityRuntimeId = this.getId(); eventPacket.event = EntityEventPacket.USE_ITEM; this.dataPacket(eventPacket); Server.broadcastPacket(this.getViewers().values(), eventPacket); if (this.isSurvival()) { itemInHand.count--; this.inventory.setItemInHand(itemInHand); this.inventory.addItem(new ItemBucket()); } this.removeAllEffects(); } else { this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } Food food = Food.getByRelative(itemInHand); if (food != null && food.eatenBy(this)) --itemInHand.count; this.inventory.setItemInHand(itemInHand); } return; default: break; } } finally { this.setUsingItem(false); } break; default: this.inventory.sendContents(this); break; } break; case ProtocolInfo.PLAYER_HOTBAR_PACKET: PlayerHotbarPacket hotbarPacket = (PlayerHotbarPacket) packet; if (hotbarPacket.windowId != ContainerIds.INVENTORY) { return; //In PE this should never happen } this.inventory.equipItem(hotbarPacket.selectedHotbarSlot); break; case ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET: this.serverSettings.forEach((id, window) -> { ServerSettingsResponsePacket re = new ServerSettingsResponsePacket(); re.formId = id; re.data = window.toJson(); this.dataPacket(re); }); break; case ProtocolInfo.PLAYER_SKIN_PACKET: PlayerSkinPacket skin = (PlayerSkinPacket) packet; this.setSkin(skin.skin); break; default: break; } } } public BufferedImage createMap(ItemMap mapItem) { new ArrayList<>(); List<BaseFullChunk> chunks = new ArrayList<>(); Color[][] blockColors = new Color[16][16]; BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D)img.getGraphics(); chunks.add(this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, false)); for(int x=0;x < 16;x++){ for( int y=0;y < 16;y++){ blockColors[x][y] = Block.get(chunks.get(0).getHighestBlockAt((int)this.x, (int)this.z)).getColor(); g2.drawImage(img, x, y, blockColors[x][y], null); } } BufferedImage data = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB); data.createGraphics().drawImage(img, 0, 0, null); return data; } /** * プレイヤーをサーバーから追放します。 * @return void */ public boolean kick() { return this.kick(""); } /** * プレイヤーをサーバーから追放します。 * 理由はPlayerkickEvent.Reason.UNKNOWNが使われます。 * @param reason 理由文 * @param isAdmin kicked by admin.を表示するかどうか * @return boolean * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(String reason, boolean isAdmin) { return this.kick(PlayerKickEvent.Reason.UNKNOWN, reason, isAdmin); } /** * プレイヤーをサーバーから追放します。 * 理由はPlayerkickEvent.Reason.UNKNOWNが使われます。 * @param reason 理由文 * @return boolean * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(String reason) { return kick(PlayerKickEvent.Reason.UNKNOWN, reason); } /** * プレイヤーをサーバーから追放します。 * kicked by admin.が表示されます。 * @param reason 理由 * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason) { return this.kick(reason, true); } /** * プレイヤーをサーバーから追放します。 * kicked by admin.が表示されます。 * @param reason 理由 * @param reasonString 理由文 * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason, String reasonString) { return this.kick(reason, reasonString, true); } /** * プレイヤーをサーバーから追放します。 * @param reason 理由 * @param isAdmin kicked by admin.を表示するかどうか * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason, boolean isAdmin) { return this.kick(reason, reason.toString(), isAdmin); } /** * プレイヤーをサーバーから追放します。 * @param reason 理由 * @param reasonString 理由文 * @param isAdmin kicked by admin.を表示するかどうか * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason, String reasonString, boolean isAdmin) { PlayerKickEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerKickEvent(this, reason, this.getLeaveMessage())); if (!ev.isCancelled()) { String message; if (isAdmin) { if (!this.isBanned()) { message = "Kicked by admin." + (!"".equals(reasonString) ? " Reason: " + reasonString : ""); } else { message = reasonString; } } else { if ("".equals(reasonString)) { message = "disconnectionScreen.noReason"; } else { message = reasonString; } } this.close(ev.getQuitMessage(), message); return true; } return false; } /** * プレイヤーにメッセージを送信します。 * ミュート状態では表示されません。 * (ミュート状態...isMuted()の戻り値) * @see "ミュート状態でも表示したい場合" * @see Player#sendImportantMessage(String) sendImportantMessage * @see Player#isMuted() isMuted() * @param message メッセージ内容 * @return void */ @Override public void sendMessage(String message) { if(mute)return; TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message); this.dataPacket(pk); } @Override public void sendMessage(TextContainer message) { if(mute)return; if (message instanceof TranslationContainer) { this.sendTranslation(message.getText(), ((TranslationContainer) message).getParameters()); return; } this.sendMessage(message.getText()); } public void sendTranslation(String message) { if(mute)return; this.sendTranslation(message, new String[0]); } public void sendTranslation(String message, String[] parameters) { if(mute)return; TextPacket pk = new TextPacket(); if (!this.server.isLanguageForced()) { pk.type = TextPacket.TYPE_TRANSLATION; pk.message = this.server.getLanguage().translateString(message, parameters, "nukkit."); for (int i = 0; i < parameters.length; i++) { parameters[i] = this.server.getLanguage().translateString(parameters[i], parameters, "nukkit."); } pk.parameters = parameters; } else { pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message, parameters); } this.dataPacket(pk); } /** * プレイヤーにポップアップを送信します。 * ミュート状態では表示されません。 * @param message メッセージ内容 * @return void */ public void sendPopup(String message) { if(mute)return; this.sendPopup(message, ""); } /** * プレイヤーにポップアップを送信します。 * ミュート状態では表示されません。 * @param message メッセージ内容 * @param subtitle サブタイトル * @return void */ public void sendPopup(String message, String subtitle) { if(mute)return; TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_POPUP; pk.source = message; pk.message = subtitle; this.dataPacket(pk); } /** * プレイヤーにチップを送信します。 * ミュート状態では表示されません。 * @param message メッセージ内容 * @return void */ public void sendTip(String message) { if(mute)return; TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_TIP; pk.message = message; this.dataPacket(pk); } /** * プレイヤーにメッセージを送信します。 * ただし、ミュート状態でも表示されます。 * @param message メッセージ内容 * @return void * @author Itsu */ public void sendImportantMessage(String message) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message); this.dataPacket(pk); } public void clearTitle() { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_CLEAR; this.dataPacket(pk); } /** * Resets both title animation times and subtitle for the next shown title */ public void resetTitleSettings() { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_RESET; this.dataPacket(pk); } /** * プレイヤーにタイトルを送信します。 * ミュート状態では表示されません。 * @param text タイトル内容 * @return void */ public void sendTitle(String text) { if(mute)return; SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_TITLE; pk.text = text; this.dataPacket(pk); } /** * プレイヤーにサブタイトルを送信します。 * ミュート状態では表示されません。 * @param text サブタイトル内容 * @return void */ public void setSubtitle(String text) { if(mute)return; SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_SUBTITLE; pk.text = text; this.dataPacket(pk); } public void sendActionBarTitle(String text) { if(mute)return; SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_ACTION_BAR; pk.text = text; this.dataPacket(pk); } /** * Sets times for title animations * @param fadeInTime For how long title fades in * @param stayTime For how long title is shown * @param fadeOutTime For how long title fades out */ public void setTitleAnimationTimes(int fadeInTime, int stayTime, int fadeOutTime) { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_ANIMATION_TIMES; pk.fadeInTime = fadeInTime; pk.stayTime = stayTime; pk.fadeOutTime = fadeOutTime; this.dataPacket(pk); } /** * 128x128の大きさでMapにpathの画像を貼り付けます。 * @param path 画像のパス * @param item Map * @return void * @author Megapix96 * @see "幅と高さを指定する場合" * @see Player#sendImage(String, ItemMap, int, int) sendImage(String, ItemMap, int, int) */ public void sendImage(String path, ItemMap item) throws IOException{ this.sendImage(path, item, 128, 128); } /** * 128x128の大きさでMapに画像を貼り付けます。 * @param img 画像 * @param item Map * @return void * @author Megapix96 * @see "幅と高さを指定する場合" * @see Player#sendImage(String, ItemMap, int, int) sendImage(String, ItemMap, int, int) */ public void sendImage(BufferedImage img, ItemMap item) throws IOException{ this.sendImage(img, item, 128, 128); } /** * Mapにpathの画像を貼り付けます。 * @param path 画像のパス * @param item Map * @param width 幅 * @param height 高さ * @return void * @author Megapix96 */ public void sendImage(String path, ItemMap item, int width, int height) throws IOException{ item.setImage(new File(path)); ClientboundMapItemDataPacket pk = new ClientboundMapItemDataPacket(); pk.mapId = item.getMapId(); pk.update = 2; pk.scale = 0; pk.width = width; pk.height = height; pk.offsetX = 0; pk.offsetZ = 0; pk.image = item.loadImageFromNBT(); this.dataPacket(pk); } /** * Mapにpathの画像を貼り付けます。 * @param img 画像 * @param item Map * @param width 幅 * @param height 高さ * @return void * @author Megapix96 */ public void sendImage(BufferedImage img, ItemMap item, int width, int height) throws IOException{ item.setImage(img); ClientboundMapItemDataPacket pk = new ClientboundMapItemDataPacket(); pk.mapId = item.getMapId(); pk.update = 2; pk.scale = 0; pk.width = width; pk.height = height; pk.offsetX = 0; pk.offsetZ = 0; pk.image = item.loadImageFromNBT(); this.dataPacket(pk); } @Override public void close() { this.close(""); } public void close(String message) { this.close(message, "generic"); } public void close(String message, String reason) { this.close(message, reason, true); } public void close(String message, String reason, boolean notify) { this.close(new TextContainer(message), reason, notify); } public void close(TextContainer message) { this.close(message, "generic"); } public void close(TextContainer message, String reason) { this.close(message, reason, true); } public void close(TextContainer message, String reason, boolean notify) { this.unlinkHookFromPlayer(); if (this.connected && !this.closed) { if (notify && reason.length() > 0) { DisconnectPacket pk = new DisconnectPacket(); pk.message = reason; this.directDataPacket(pk); } // this.connected = false; PlayerQuitEvent ev = null; if (this.getName() != null && this.getName().length() > 0) { this.server.getPluginManager().callEvent(ev = new PlayerQuitEvent(this, message, true, reason)); if (this.loggedIn && ev.getAutoSave()) { this.save(); } } for (Player player : this.server.getOnlinePlayers().values()) { if (!player.canSee(this)) { player.showPlayer(this); } } this.hiddenPlayers = new HashMap<>(); this.removeAllWindows(true); for (long index : new ArrayList<>(this.usedChunks.keySet())) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); this.level.unregisterChunkLoader(this, chunkX, chunkZ); this.usedChunks.remove(index); } super.close(); this.interfaz.close(this, notify ? reason : ""); if (this.loggedIn) { this.server.removeOnlinePlayer(this); } this.loggedIn = false; if (ev != null && !Objects.equals(this.username, "") && this.spawned && !Objects.equals(ev.getQuitMessage().toString(), "") && this.getServer().getJupiterConfigBoolean("join-quit-message")) { this.server.broadcastMessage(ev.getQuitMessage()); } this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_USERS, this); this.spawned = false; this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logOut", TextFormat.AQUA + (this.getName() == null ? "" : this.getName()) + TextFormat.WHITE, this.ip, String.valueOf(this.port), this.getServer().getLanguage().translateString(reason))); this.windows = new HashMap<>(); this.windowIndex = new HashMap<>(); this.usedChunks = new HashMap<>(); this.loadQueue = new HashMap<>(); this.hasSpawned = new HashMap<>(); this.spawnPosition = null; if (this.riding instanceof EntityVehicle) { ((EntityVehicle) this.riding).linkedEntity = null; } this.riding = null; } if (this.perm != null) { this.perm.clearPermissions(); this.perm = null; } if (this.inventory != null) { this.inventory = null; } this.chunk = null; this.server.removePlayer(this); } public void save() { this.save(false); } public void save(boolean async) { if (this.closed) { throw new IllegalStateException("Tried to save closed player"); } super.saveNBT(); if (this.level != null) { this.namedTag.putString("Level", this.level.getFolderName()); if (this.spawnPosition != null && this.spawnPosition.getLevel() != null) { this.namedTag.putString("SpawnLevel", this.spawnPosition.getLevel().getFolderName()); this.namedTag.putInt("SpawnX", (int) this.spawnPosition.x); this.namedTag.putInt("SpawnY", (int) this.spawnPosition.y); this.namedTag.putInt("SpawnZ", (int) this.spawnPosition.z); } CompoundTag achievements = new CompoundTag(); for (String achievement : this.achievements) { achievements.putByte(achievement, 1); } this.namedTag.putCompound("Achievements", achievements); this.namedTag.putInt("playerGameType", this.gamemode); this.namedTag.putLong("lastPlayed", System.currentTimeMillis() / 1000); this.namedTag.putString("lastIP", this.getAddress()); this.namedTag.putInt("EXP", this.getExperience()); this.namedTag.putInt("expLevel", this.getExperienceLevel()); this.namedTag.putInt("foodLevel", this.getFoodData().getLevel()); this.namedTag.putFloat("foodSaturationLevel", this.getFoodData().getFoodSaturationLevel()); if (!"".equals(this.username) && this.namedTag != null) { this.server.saveOfflinePlayerData(this.username, this.namedTag, async); } } } /** * プレイヤー名を取得します。 * @return String プレイヤー名 */ public String getName() { if (this.username == null) { return null; } synchronized(this.username){ return this.username; } } /** * プレイヤーを殺害します。 * @return void */ @Override public void kill() { if (!this.spawned) { return; } String message = "death.attack.generic"; List<String> params = new ArrayList<>(); params.add(this.getDisplayName()); EntityDamageEvent cause = this.getLastDamageCause(); switch (cause == null ? DamageCause.CUSTOM : cause.getCause()) { case ENTITY_ATTACK: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.player"; params.add(((Player) e).getDisplayName()); break; } else if (e instanceof EntityLiving) { message = "death.attack.mob"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { params.add("Unknown"); } } break; case PROJECTILE: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.arrow"; params.add(((Player) e).getDisplayName()); } else if (e instanceof EntityLiving) { message = "death.attack.arrow"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { params.add("Unknown"); } } break; case SUICIDE: message = "death.attack.generic"; break; case VOID: message = "death.attack.outOfWorld"; break; case FALL: if (cause != null) { if (cause.getFinalDamage() > 2) { message = "death.fell.accident.generic"; break; } } message = "death.attack.fall"; break; case SUFFOCATION: message = "death.attack.inWall"; break; case LAVA: message = "death.attack.lava"; break; case FIRE: message = "death.attack.onFire"; break; case FIRE_TICK: message = "death.attack.inFire"; break; case DROWNING: message = "death.attack.drown"; break; case CONTACT: if (cause instanceof EntityDamageByBlockEvent) { if (((EntityDamageByBlockEvent) cause).getDamager().getId() == Block.CACTUS) { message = "death.attack.cactus"; } } break; case BLOCK_EXPLOSION: case ENTITY_EXPLOSION: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.explosion.player"; params.add(((Player) e).getDisplayName()); } else if (e instanceof EntityLiving) { message = "death.attack.explosion.player"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } } else { message = "death.attack.explosion"; } break; case MAGIC: message = "death.attack.magic"; break; case CUSTOM: break; default: } this.health = 0; this.scheduleUpdate(); PlayerDeathEvent ev = new PlayerDeathEvent(this, this.getDrops(), new TranslationContainer(message, params.stream().toArray(String[]::new)), this.getExperienceLevel()); if (this.keepInventory){ ev.setKeepInventory(true); } if (this.keepExperience){ ev.setKeepExperience(true); } this.server.getPluginManager().callEvent(ev); if (!ev.getKeepInventory()) { for (Item item : ev.getDrops()) { this.level.dropItem(this, item, null, true, 40); } if (this.inventory != null) { this.inventory.clearAll(); } } if (this.keepExperience){ ev.setKeepExperience(true); } if (!ev.getKeepExperience()) { if (this.isSurvival() || this.isAdventure()) { int exp = ev.getExperience() * 7; if (exp > 100) exp = 100; int add = 1; for (int ii = 1; ii < exp; ii += add) { this.getLevel().dropExpOrb(this, add); add = new NukkitRandom().nextRange(1, 3); } } this.setExperience(0, 0); } if (!Objects.equals(ev.getDeathMessage().toString(), "")) { this.server.broadcast(ev.getDeathMessage(), Server.BROADCAST_CHANNEL_USERS); } RespawnPacket pk = new RespawnPacket(); Position pos = this.getSpawn(); pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; this.dataPacket(pk); } /** * プレイヤーの体力を設定します。 * @param health 設定する体力量 * @return void */ @Override public void setHealth(float health) { if (health < 1) { health = 0; } super.setHealth(health); Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getAbsorption() % 2 != 0 ? this.getMaxHealth() + 1 : this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0); if (this.spawned) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attr}; pk.entityRuntimeId = this.id; this.dataPacket(pk); } } /** * プレイヤーの経験値を取得します。 * @return int 経験値 */ public int getExperience() { return this.exp; } /** * プレイヤーの経験値レベルを取得します。 * @return int 経験値レベル */ public int getExperienceLevel() { return this.expLevel; } /** * プレイヤーの経験値を追加します。 * @param add 追加する経験値量 * @return void */ public void addExperience(int add) { if (add == 0) return; int now = this.getExperience(); int added = now + add; int level = this.getExperienceLevel(); int most = calculateRequireExperience(level); while (added >= most) { //Level Up! added = added - most; level++; most = calculateRequireExperience(level); } this.setExperience(added, level); } public static int calculateRequireExperience(int level) { if (level >= 30) { return 112 + (level - 30) * 9; } else if (level >= 15) { return 37 + (level - 15) * 5; } else { return 7 + level * 2; } } /** * プレイヤーの経験値を設定します。 * @param exp 設定する経験値量 * @return void */ public void setExperience(int exp) { setExperience(exp, this.getExperienceLevel()); } //todo something on performance, lots of exp orbs then lots of packets, could crash client /** * プレイヤーの経験値と経験値レベルを設定します。 * @param exp 設定する経験値量 * @param level 設定する経験値レベル * @return void */ public void setExperience(int exp, int level) { this.exp = exp; this.expLevel = level; this.sendExperienceLevel(level); this.sendExperience(exp); } public void sendExperience() { sendExperience(this.getExperience()); } public void sendExperience(int exp) { if (this.spawned) { float percent = ((float) exp) / calculateRequireExperience(this.getExperienceLevel()); this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE).setValue(percent)); } } public void sendExperienceLevel() { sendExperienceLevel(this.getExperienceLevel()); } public void sendExperienceLevel(int level) { if (this.spawned) { this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(level)); } } public void setAttribute(Attribute attribute) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attribute}; pk.entityRuntimeId = this.id; this.dataPacket(pk); } @Override public void setMovementSpeed(float speed) { super.setMovementSpeed(speed); if (this.spawned) { Attribute attribute = Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(speed); this.setAttribute(attribute); } } public Entity getKiller() { return killer; } @Override public boolean attack(EntityDamageEvent source) { if (!this.isAlive()) { return false; } if (this.isCreative() && source.getCause() != DamageCause.MAGIC && source.getCause() != DamageCause.SUICIDE && source.getCause() != DamageCause.VOID ) { //source.setCancelled(); return false; } else if (this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && source.getCause() == DamageCause.FALL) { //source.setCancelled(); return false; } else if (source.getCause() == DamageCause.FALL) { if (this.getLevel().getBlock(this.getPosition().floor().add(0.5, -1, 0.5)).getId() == Block.SLIME_BLOCK) { if (!this.isSneaking()) { //source.setCancelled(); return false; } } } if (source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); if (damager instanceof Player) { ((Player) damager).getFoodData().updateFoodExpLevel(0.3); } if (!damager.onGround) { NukkitRandom random = new NukkitRandom(); for (int i = 0; i < 5; i++) { CriticalParticle par = new CriticalParticle(new Vector3(this.x + random.nextRange(-15, 15) / 10, this.y + random.nextRange(0, 20) / 10, this.z + random.nextRange(-15, 15) / 10)); this.getLevel().addParticle(par); } source.setDamage((float) (source.getDamage() * 1.5)); } } if (super.attack(source)) { //!source.isCancelled() if (this.getLastDamageCause() == source && this.spawned) { this.getFoodData().updateFoodExpLevel(0.3); EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.id; pk.event = EntityEventPacket.HURT_ANIMATION; this.dataPacket(pk); } return true; } else { return false; } } public void sendPosition(Vector3 pos) { this.sendPosition(pos, this.yaw); } public void sendPosition(Vector3 pos, double yaw) { this.sendPosition(pos, yaw, this.pitch); } public void sendPosition(Vector3 pos, double yaw, double pitch) { this.sendPosition(pos, yaw, pitch, MovePlayerPacket.MODE_NORMAL); } public void sendPosition(Vector3 pos, double yaw, double pitch, int mode) { this.sendPosition(pos, yaw, pitch, mode, null); } public void sendPosition(Vector3 pos, double yaw, double pitch, int mode, Player[] targets) { MovePlayerPacket pk = new MovePlayerPacket(); pk.entityRuntimeId = this.getId(); pk.x = (float) pos.x; pk.y = (float) (pos.y + this.getEyeHeight()); pk.z = (float) pos.z; pk.headYaw = (float) yaw; pk.pitch = (float) pitch; pk.yaw = (float) yaw; pk.mode = mode; if (targets != null) { Server.broadcastPacket(targets, pk); } else { pk.entityRuntimeId = this.id; this.dataPacket(pk); } } @Override protected void checkChunks() { if (this.chunk == null || (this.chunk.getX() != ((int) this.x >> 4) || this.chunk.getZ() != ((int) this.z >> 4))) { if (this.chunk != null) { this.chunk.removeEntity(this); } this.chunk = this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, true); if (!this.justCreated) { Map<Integer, Player> newChunk = new HashMap<>(this.level.getChunkPlayers((int) this.x >> 4, (int) this.z >> 4)); newChunk.remove((int) this.getLoaderId()); //List<Player> reload = new ArrayList<>(); for (Player player : new ArrayList<>(this.hasSpawned.values())) { if (!newChunk.containsKey((int) player.getLoaderId())) { this.despawnFrom(player); } else { newChunk.remove((int) player.getLoaderId()); //reload.add(player); } } for (Player player : newChunk.values()) { this.spawnTo(player); } } if (this.chunk == null) { return; } this.chunk.addEntity(this); } } protected boolean checkTeleportPosition() { if (this.teleportPosition != null) { int chunkX = (int) this.teleportPosition.x >> 4; int chunkZ = (int) this.teleportPosition.z >> 4; for (int X = -1; X <= 1; ++X) { for (int Z = -1; Z <= 1; ++Z) { long index = Level.chunkHash(chunkX + X, chunkZ + Z); if (!this.usedChunks.containsKey(index) || !this.usedChunks.get(index)) { return false; } } } this.spawnToAll(); this.forceMovement = this.teleportPosition; this.teleportPosition = null; return true; } return false; } public Inventory getWindowById(int id) { return this.windowIndex.get(id); } protected void sendPlayStatus(int status) { sendPlayStatus(status, false); } protected void sendPlayStatus(int status, boolean immediate) { PlayStatusPacket pk = new PlayStatusPacket(); pk.status = status; if (immediate) { this.directDataPacket(pk); } else { this.dataPacket(pk); } } @Override public boolean teleport(Location location, TeleportCause cause) { if (!this.isOnline()) { return false; } Location from = this.getLocation(); Location to = location; if (cause != null) { PlayerTeleportEvent event = new PlayerTeleportEvent(this, from, to, cause); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) return false; to = event.getTo(); if (from.getLevel().getId() != to.getLevel().getId()) { SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; Position spawn = to.getLevel().getSpawnLocation(); pk.x = spawn.getFloorX(); pk.y = spawn.getFloorY(); pk.z = spawn.getFloorZ(); dataPacket(pk); } } this.getPosition(); if (super.teleport(to, null)) { // null to prevent fire of duplicate EntityTeleportEvent this.removeAllWindows(); this.teleportPosition = new Vector3(this.x, this.y, this.z); this.forceMovement = this.teleportPosition; this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_TELEPORT); this.checkTeleportPosition(); this.resetFallDistance(); this.nextChunkOrderRun = 0; this.newPosition = null; //Weather this.getLevel().sendWeather(this); //Update time this.getLevel().sendTime(this); return true; } return false; } public void teleportImmediate(Location location) { this.teleportImmediate(location, TeleportCause.PLUGIN); } public void teleportImmediate(Location location, TeleportCause cause) { Location from = this.getLocation(); if (super.teleport(location, cause)) { for (Inventory window : new ArrayList<>(this.windowIndex.values())) { if (window == this.inventory) { continue; } this.removeWindow(window); } if (from.getLevel().getId() != location.getLevel().getId()) { SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; Position spawn = location.getLevel().getSpawnLocation(); pk.x = spawn.getFloorX(); pk.y = spawn.getFloorY(); pk.z = spawn.getFloorZ(); dataPacket(pk); } this.forceMovement = new Vector3(this.x, this.y, this.z); this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); this.resetFallDistance(); this.orderChunks(); this.nextChunkOrderRun = 0; this.newPosition = null; //Weather this.getLevel().sendWeather(this); //Update time this.getLevel().sendTime(this); } } /** * Creates and sends a BossBar to the player * * @param text The BossBar message * @param length The BossBar percentage * @return bossBarId The BossBar ID, you should store it if you want to remove or update the BossBar later */ /* public long createBossBar(String text, int length) { // First we spawn a entity long bossBarId = 1095216660480L + ThreadLocalRandom.current().nextLong(0, 0x7fffffffL); AddEntityPacket pkAdd = new AddEntityPacket(); pkAdd.type = EntityCreeper.NETWORK_ID; pkAdd.entityUniqueId = bossBarId; pkAdd.entityRuntimeId = bossBarId; pkAdd.x = (float) this.x; pkAdd.y = (float) -10; // Below the bedrock pkAdd.z = (float) this.z; pkAdd.speedX = (float) this.motionX; pkAdd.speedY = (float) this.motionY; pkAdd.speedZ = (float) this.motionZ; EntityMetadata metadata = new EntityMetadata() // Default Metadata tags .putLong(DATA_FLAGS, 0) .putShort(DATA_AIR, 400) .putShort(DATA_MAX_AIR, 400) .putLong(DATA_LEAD_HOLDER_EID, -1) .putFloat(DATA_SCALE, 1f) .putString(Entity.DATA_NAMETAG, text) // Set the entity name .putInt(Entity.DATA_SCALE, 0); // And make it invisible pkAdd.metadata = metadata; this.dataPacket(pkAdd); // Now we send the entity attributes // TODO: Attributes should be sent on AddEntityPacket, however it doesn't work (client bug?) UpdateAttributesPacket pkAttributes = new UpdateAttributesPacket(); pkAttributes.entityRuntimeId = bossBarId; Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH); attr.setMaxValue(100); // Max value - We need to change the max value first, or else the "setValue" will return a IllegalArgumentException attr.setValue(length); // Entity health pkAttributes.entries = new Attribute[] { attr }; this.dataPacket(pkAttributes); // And now we send the bossbar packet BossEventPacket pkBoss = new BossEventPacket(); pkBoss.entityRuntimeId = bossBarId; pkBoss.type = BossEventPacket.ADD; this.dataPacket(pkBoss); return bossBarId; } */ /** * Updates a BossBar * * @param text The new BossBar message * @param length The new BossBar length * @param bossBarId The BossBar ID */ /* public void updateBossBar(String text, int length, long bossBarId) { // First we update the boss bar length UpdateAttributesPacket pkAttributes = new UpdateAttributesPacket(); pkAttributes.entityRuntimeId = bossBarId; Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH); attr.setMaxValue(100); // Max value - We need to change the max value first, or else the "setValue" will return a IllegalArgumentException attr.setValue(length); // Entity health pkAttributes.entries = new Attribute[] { attr }; this.dataPacket(pkAttributes); // And then the boss bar text SetEntityDataPacket pkMetadata = new SetEntityDataPacket(); pkMetadata.eid = bossBarId; pkMetadata.metadata = new EntityMetadata() // Default Metadata tags .putLong(DATA_FLAGS, 0) .putShort(DATA_AIR, 400) .putShort(DATA_MAX_AIR, 400) .putLong(DATA_LEAD_HOLDER_EID, -1) .putFloat(DATA_SCALE, 1f) .putString(Entity.DATA_NAMETAG, text) // Set the entity name .putInt(Entity.DATA_SCALE, 0); // And make it invisible this.dataPacket(pkMetadata); // And now we send the bossbar packet BossEventPacket pkBoss = new BossEventPacket(); pkBoss.entityRuntimeId = bossBarId; pkBoss.type = BossEventPacket.UPDATE; this.dataPacket(pkBoss); return; } */ /** * Removes a BossBar * * @param bossBarId The BossBar ID */ public void removeBossBar(long bossBarId) { RemoveEntityPacket pkRemove = new RemoveEntityPacket(); pkRemove.entityRuntimeId = bossBarId; this.dataPacket(pkRemove); } public int getWindowId(Inventory inventory) { if (this.windows.containsKey(inventory)) { return this.windows.get(inventory); } return -1; } public int addWindow(Inventory inventory){ return addWindow(inventory, null); } public int addWindow(Inventory inventory, Integer forceId) { return addWindow(inventory, forceId, false); } public int addWindow(Inventory inventory, Integer forceId, boolean isPermanent) { if (this.windows.containsKey(inventory)) { return this.windows.get(inventory); } int cnt; if (forceId == null) { this.windowCnt = cnt = Math.max(2, ++this.windowCnt % 99); } else { cnt = forceId; } this.windowIndex.put(cnt, inventory); this.windows.put(inventory, cnt); if (isPermanent) { this.permanentWindows.add(cnt); } if (inventory.open(this)) { return cnt; } else { this.removeWindow(inventory); return -1; } } public void removeWindow(Inventory inventory) { inventory.close(this); if (this.windows.containsKey(inventory)) { int id = this.windows.get(inventory); this.windows.remove(this.windowIndex.get(id)); this.windowIndex.remove(id); } } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { this.server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List<MetadataValue> getMetadata(String metadataKey) { return this.server.getPlayerMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { return this.server.getPlayerMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { this.server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); } @Override public void onChunkChanged(FullChunk chunk) { this.usedChunks.remove(Level.chunkHash(chunk.getX(), chunk.getZ())); } @Override public void onChunkLoaded(FullChunk chunk) { } @Override public void onChunkPopulated(FullChunk chunk) { } @Override public void onChunkUnloaded(FullChunk chunk) { } @Override public void onBlockChanged(Vector3 block) { } @Override public Integer getLoaderId() { return this.loaderId; } @Override public boolean isLoaderActive() { return this.isConnected(); } public static BatchPacket getChunkCacheFromData(int chunkX, int chunkZ, byte[] payload) { FullChunkDataPacket pk = new FullChunkDataPacket(); pk.chunkX = chunkX; pk.chunkZ = chunkZ; pk.data = payload; pk.encode(); BatchPacket batch = new BatchPacket(); byte[][] batchPayload = new byte[2][]; byte[] buf = pk.getBuffer(); batchPayload[0] = Binary.writeUnsignedVarInt(buf.length); batchPayload[1] = buf; byte[] data = Binary.appendBytes(batchPayload); try { batch.payload = Zlib.deflate(data, Server.getInstance().networkCompressionLevel); } catch (Exception e) { throw new RuntimeException(e); } return batch; } private boolean foodEnabled = true; private CraftingGrid craftingGrid; private PlayerCursorInventory cursorInventory; public boolean isFoodEnabled() { return !(this.isCreative() || this.isSpectator()) && this.foodEnabled; } public void setFood(int food){ this.foodData.setLevel(food); } public void setFoodEnabled(boolean foodEnabled) { this.foodEnabled = foodEnabled; } public PlayerFood getFoodData() { return this.foodData; } //todo a lot on dimension public void setDimension(int dimension) { ChangeDimensionPacket pk = new ChangeDimensionPacket(); pk.dimension = getLevel().getDimension(); this.dataPacket(pk); } public void setCheckMovement(boolean checkMovement) { this.checkMovement = checkMovement; } public synchronized void setLocale(Locale locale) { this.locale.set(locale); } public synchronized Locale getLocale() { return this.locale.get(); } public void setSprinting(boolean value, boolean setDefault) { super.setSprinting(value); if (setDefault) { this.movementSpeed = DEFAULT_SPEED; } else { float sprintSpeedChange = DEFAULT_SPEED * 0.3f; if (!value) sprintSpeedChange *= -1; this.movementSpeed += sprintSpeedChange; } this.setMovementSpeed(this.movementSpeed); } /** * プレイヤーをミュート状態にします。 * @param b trueで有効/falseで無効 * @return void * @author Itsu */ public void setMute(boolean b){ this.mute = b; } /** * プレイヤーがミュート状態かどうかを返します。 * @return boolean trueが有効/falseが無効 * @author Itsu */ public boolean isMuted(){ return this.mute; } /** * プレイヤー指定したサーバーに転送します。 * @param ip 転送先サーバーのIPアドレス * @param port 転送先サーバーのポート * @return void * @author Itsu */ public void transfer(String ip, int port){ TransferPacket pk = new TransferPacket(); pk.address = ip; pk.port = port; this.dataPacket(pk); String mes = FastAppender.get("IP: ", ip, " ポート: ", port, "のサーバーに移動しました。"); if(this.server.getJupiterConfigBoolean("transfer-server-message")){ this.server.broadcastMessage(this.getName() + "は別のサーバーへ移動しました。"); } this.close(mes, mes, false); } /** * @deprecated Nukkitとの互換性がないため削除されます。 */ @Deprecated public void transferServer(String ip, int port){ this.transfer(ip, port); } public boolean pickupEntity(Entity entity, boolean near) { if (!this.spawned || !this.isAlive() || !this.isOnline()) { return false; } entity.onCollideWithPlayer(this); int tick = this.getServer().getTick(); if (pickedXPOrb < tick && entity instanceof EntityXPOrb && this.boundingBox.isVectorInside(entity)) { EntityXPOrb xpOrb = (EntityXPOrb) entity; if (xpOrb.getPickupDelay() <= 0) { int exp = xpOrb.getExp(); this.addExperience(exp); entity.kill(); this.getLevel().addSound(new ExperienceOrbSound(this)); pickedXPOrb = tick; return true; } } return false; } @Override public int hashCode() { if ((this.hash == 0) || (this.hash == 485)) { this.hash = (485 + (getUniqueId() != null ? getUniqueId().hashCode() : 0)); } return this.hash; } @Override public boolean equals(Object obj) { if (!(obj instanceof Player)) { return false; } Player other = (Player) obj; return Objects.equals(this.getUniqueId(), other.getUniqueId()) && this.getId() == other.getId(); } /** * Notifies an ACK response from the client * * @param identification */ public void notifyACK(int identification) { needACK.put(identification, true); } public void excuteData() throws IOException{ JsonObject main = new JsonObject(); main.addProperty("Name: ", this.getName()); main.addProperty("X: ", this.getX()); main.addProperty("Y: ", this.getY()); main.addProperty("Z: ", this.getZ()); List<Item> item = new ArrayList<>(); for(int i=0;i < this.getInventory().getContents().size();i++){ item.add(this.getInventory().getContents().get(i)); } int count = 1; for(Item i : item){ main.addProperty("Inventory[" + count + "]: ", i.getName() + "[" + i.getCount() + "]"); count++; } String src = new Gson().toJson(main); Utils.writeFile("./players/JsonDatas/" + this.getName() + ".json", src); return; } protected void forceSendEmptyChunks() { int chunkPositionX = this.getFloorX() >> 4; int chunkPositionZ = this.getFloorZ() >> 4; for (int x = -3; x < 3; x++) { for (int z = -3; z < 3; z++) { FullChunkDataPacket chunk = new FullChunkDataPacket(); chunk.chunkX = chunkPositionX + x; chunk.chunkZ = chunkPositionZ + z; chunk.data = new byte[0]; this.dataPacket(chunk); } } } public boolean dropItem(Item item) { if (!this.spawned || !this.isAlive()) { return false; } if (item.isNull()) { this.server.getLogger().debug(this.getName() + " attempted to drop a null item (" + item + ")"); return true; } Vector3 motion = this.getDirectionVector().multiply(0.4); this.level.dropItem(this.add(0, 1.3, 0), item, motion, 40); this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); return true; } public void sendAllInventories() { for (Inventory inv : this.windowIndex.values()) { inv.sendContents(this); if (inv instanceof PlayerInventory) { ((PlayerInventory) inv).sendArmorContents(this); } } } protected void addDefaultWindows() { this.addWindow(this.getInventory(), ContainerIds.INVENTORY, true); this.cursorInventory = new PlayerCursorInventory(this); this.addWindow(this.cursorInventory, ContainerIds.CURSOR, true); this.addWindow(this.offhandInventory, ContainerIds.OFFHAND, true); this.craftingGrid = new CraftingGrid(this); //TODO: more windows } public PlayerCursorInventory getCursorInventory() { return this.cursorInventory; } public CraftingGrid getCraftingGrid() { return this.craftingGrid; } public void setCraftingGrid(CraftingGrid grid) { this.craftingGrid = grid; } public void resetCraftingGridType() { if (this.craftingGrid instanceof BigCraftingGrid) { Item[] drops = this.inventory.addItem(this.craftingGrid.getContents().values().stream().toArray(Item[]::new)); for (Item drop : drops) { this.dropItem(drop); } this.craftingGrid = new CraftingGrid(this); this.craftingType = 0; } } public void removeAllWindows() { removeAllWindows(false); } public void removeAllWindows(boolean permanent) { for (Entry<Integer, Inventory> entry : new ArrayList<>(this.windowIndex.entrySet())) { if (!permanent && this.permanentWindows.contains((int) entry.getKey())) { continue; } this.removeWindow(entry.getValue()); } } public boolean isUsingItem(){ return this.getDataFlag(DATA_FLAGS, DATA_FLAG_ACTION) && this.startAction > 1; } public void setUsingItem(boolean value) { this.startAction = value ? this.server.getTick() : -1; this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, value); } /** * フォームウィンドウをプレイヤーに送信します。 * @param window FormWindow * @return void */ public void sendWindow(FormWindow window){ ModalFormRequestPacket pk = new ModalFormRequestPacket(); pk.data = window.toJson(); pk.formId = window.getId(); this.activeWindow = window; this.dataPacket(pk); } public int addServerSettings(ServerSettingsWindow window) { this.serverSettings.put(window.getId(), window); return window.getId(); } public boolean isBreakingBlock() { return this.breakingBlock != null; } public void showXboxProfile() { ShowProfilePacket pk = new ShowProfilePacket(); pk.xuid = getLoginChainData().getXUID(); this.dataPacket(pk); } /** * プレイヤーのスポーン地点からの距離を取得します。 * @return double */ public double getPlaneDistanceFromSpawn(){ return this.distance(this.level.getSafeSpawn()); } public BeaconInventory getBeacoInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof BeaconInventory) { return (BeaconInventory) inventory; } } return null; } public EnchantInventory getEnchantInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof EnchantInventory) { return (EnchantInventory) inventory; } } return null; } public AnvilInventory getAnvilInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof AnvilInventory) { return (AnvilInventory) inventory; } } return null; } public TradingInventory getTradingInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof TradingInventory) { return (TradingInventory) inventory; } } return null; } }
JupiterDevelopmentTeam/JupiterDevelopmentTeam
src/main/java/cn/nukkit/Player.java
Java
gpl-3.0
218,517
# -*- coding: utf-8 -*- class Charset(object): common_name = 'NotoKufiArabic-Regular' native_name = '' def glyphs(self): glyphs = [] glyphs.append(0x0261) #uni0759.fina glyphs.append(0x007F) #uni0625 glyphs.append(0x00D4) #uni0624 glyphs.append(0x0005) #uni0627 glyphs.append(0x00E2) #uni0626 glyphs.append(0x0004) #uni0621 glyphs.append(0x007D) #uni0623 glyphs.append(0x0081) #uni0622 glyphs.append(0x009C) #uni0686.medi glyphs.append(0x0099) #uni0629 glyphs.append(0x0085) #uni0628 glyphs.append(0x0267) #uni075C.fina glyphs.append(0x0256) #uni0756.init glyphs.append(0x007E) #uni0623.fina glyphs.append(0x0173) #uni069A.init glyphs.append(0x01A9) #uni06AB.init glyphs.append(0x02B8) #wavyhamza_above glyphs.append(0x00C8) #veh.fina glyphs.append(0x0192) #uni06A3.init glyphs.append(0x02C3) #uni06C8.fina glyphs.append(0x01BC) #uni06B1.fina glyphs.append(0x020E) #uni06AD.finamorocco glyphs.append(0x0008) #uni062D.init glyphs.append(0x00DE) #uni06CC.medi glyphs.append(0x00A1) #uni062E glyphs.append(0x0007) #uni062D glyphs.append(0x000B) #uni062F glyphs.append(0x008D) #uni062A glyphs.append(0x0129) #uni067B.init glyphs.append(0x009D) #uni062C glyphs.append(0x0091) #uni062B glyphs.append(0x00E8) #uni06440625.isol glyphs.append(0x0279) #uni0760.medi glyphs.append(0x02A3) #uni076B.fina glyphs.append(0x01D0) #uni06B6.fina glyphs.append(0x01E7) #uni06BF glyphs.append(0x0072) #uni066E.init glyphs.append(0x00E5) #uni0626.fina glyphs.append(0x025C) #uni0758 glyphs.append(0x01E0) #uni06BB.fina glyphs.append(0x0284) #uni0763.init glyphs.append(0x01C5) #uni06B3.init glyphs.append(0x00DB) #uni064A.fina glyphs.append(0x0033) #uni06440627.fina glyphs.append(0x0189) #uni06A0.init glyphs.append(0x017A) #uni069C.fina glyphs.append(0x0134) #uni067F.fina glyphs.append(0x0101) #dammatan_01 glyphs.append(0x0216) #uni06B50627.fina glyphs.append(0x0036) #uni066E.fina glyphs.append(0x02CC) #uni06CE.init glyphs.append(0x0075) #beh_dotless_alt.medi glyphs.append(0x02A0) #uni076A.init glyphs.append(0x0108) #Ghunna_above glyphs.append(0x0027) #uni0645.init glyphs.append(0x0031) #uni0649.fina glyphs.append(0x02C6) #uni06CA glyphs.append(0x0073) #uni066E.medi glyphs.append(0x026D) #uni075D.medi glyphs.append(0x02E1) #uni060D glyphs.append(0x01BD) #uni06B1.init glyphs.append(0x02DD) #uni06DD glyphs.append(0x0257) #uni0756.medi glyphs.append(0x0281) #uni0762.medi glyphs.append(0x017F) #uni069D.init glyphs.append(0x023E) #uni0750.init glyphs.append(0x015A) #uni068C.fina glyphs.append(0x005A) #uni06BA.fina glyphs.append(0x018A) #uni06A0.medi glyphs.append(0x01AC) #uni06AC.fina glyphs.append(0x018E) #uni06A2.init glyphs.append(0x0088) #uni0628.fina glyphs.append(0x00F0) #uni06C2.fina glyphs.append(0x0196) #uni06A4.medi glyphs.append(0x0295) #uni0767.medi glyphs.append(0x0141) #uni0682.init glyphs.append(0x0062) #uni064B glyphs.append(0x0265) #uni075B.fina glyphs.append(0x02E5) #threedots_alt1.below glyphs.append(0x02CD) #uni06CE.medi glyphs.append(0x02D5) #uni06D1.fina glyphs.append(0x01F5) #uni06DB glyphs.append(0x0138) #uni0680.fina glyphs.append(0x0277) #uni0760.fina glyphs.append(0x0133) #uni067F glyphs.append(0x0260) #uni0759 glyphs.append(0x012F) #uni067D glyphs.append(0x0089) #uni067E glyphs.append(0x0127) #uni067B glyphs.append(0x012B) #uni067C glyphs.append(0x0123) #uni067A glyphs.append(0x00EE) #heh_ae.fina glyphs.append(0x019A) #uni06A5.medi glyphs.append(0x00D5) #uni0624.fina glyphs.append(0x02AD) #twodots.vert.below glyphs.append(0x01D9) #uni06B8.init glyphs.append(0x02EF) #threedots_alt2.above glyphs.append(0x008B) #uni067E.init glyphs.append(0x01FC) #uni06E5 glyphs.append(0x01FD) #uni06E6 glyphs.append(0x00A4) #uni062E.fina glyphs.append(0x02DF) #uni06E0 glyphs.append(0x01F8) #uni06E1 glyphs.append(0x0098) #uni0679.fina glyphs.append(0x01FA) #uni06E3 glyphs.append(0x026B) #uni075D.fina glyphs.append(0x01FF) #uni06E8 glyphs.append(0x02E0) #uni06E9 glyphs.append(0x0202) #uni06ED glyphs.append(0x022A) #uni06EE glyphs.append(0x000D) #uni0631.fina glyphs.append(0x0125) #uni067A.init glyphs.append(0x0200) #uni06EA glyphs.append(0x003C) #uni066F.fina glyphs.append(0x01A6) #uni06AA.medi glyphs.append(0x0275) #uni075F.medi glyphs.append(0x000F) #uni0633.init glyphs.append(0x02F0) #twodots_alt1.above glyphs.append(0x01C8) #uni06B4.fina glyphs.append(0x019E) #uni06A6.medi glyphs.append(0x0121) #uni0678 glyphs.append(0x0095) #uni0679 glyphs.append(0x011D) #uni0676 glyphs.append(0x011F) #uni0677 glyphs.append(0x011B) #uni0675 glyphs.append(0x0117) #uni0672 glyphs.append(0x0119) #uni0673 glyphs.append(0x006D) #uni0670 glyphs.append(0x0083) #uni0671 glyphs.append(0x02A9) #uni076D.medi glyphs.append(0x01D1) #uni06B6.init glyphs.append(0x026E) #uni075E glyphs.append(0x02AE) #twodots.vert.small.above glyphs.append(0x00B4) #uni0636.init glyphs.append(0x0268) #uni075C.init glyphs.append(0x02C5) #uni06C9.fina glyphs.append(0x00B8) #uni0638.init glyphs.append(0x0160) #uni068F.fina glyphs.append(0x0204) #uni06FB.fina glyphs.append(0x00FE) #uni06F4.urdu glyphs.append(0x012D) #uni067C.init glyphs.append(0x025F) #uni0758.medi glyphs.append(0x0037) #uni066F.init glyphs.append(0x020F) #uni06440672.isol glyphs.append(0x01A2) #uni06A8.fina glyphs.append(0x00B6) #uni0636.fina glyphs.append(0x00B1) #uni0634.medi glyphs.append(0x008F) #uni062A.medi glyphs.append(0x02F3) #uni069F.init glyphs.append(0x00BE) #uni063A.fina glyphs.append(0x0241) #uni0751.fina glyphs.append(0x0213) #uni06440675.isol glyphs.append(0x0285) #uni0763.medi glyphs.append(0x00B5) #uni0636.medi glyphs.append(0x02E4) #threedots.rev_alt1.below glyphs.append(0x02A7) #uni076D.fina glyphs.append(0x0176) #uni069B.fina glyphs.append(0x027F) #uni0762.fina glyphs.append(0x0148) #uni0684.fina glyphs.append(0x02EE) #threedots_alt1.above glyphs.append(0x00EC) #uni06440671.isol glyphs.append(0x02A8) #uni076D.init glyphs.append(0x01F2) #uni06D8 glyphs.append(0x004F) #uni06C1.medi glyphs.append(0x0128) #uni067B.fina glyphs.append(0x0126) #uni067A.medi glyphs.append(0x009B) #uni0686.init glyphs.append(0x012E) #uni067C.medi glyphs.append(0x02F4) #uni069F.medi glyphs.append(0x0198) #uni06A5.fina glyphs.append(0x0263) #uni075A.fina glyphs.append(0x028B) #uni0765.fina glyphs.append(0x02B2) #fourdots.above glyphs.append(0x0249) #uni0753.fina glyphs.append(0x009F) #uni062C.medi glyphs.append(0x025A) #uni0757.init glyphs.append(0x0291) #uni0766.medi glyphs.append(0x00A3) #uni062E.medi glyphs.append(0x00C9) #uni0642.init glyphs.append(0x00BB) #uni063A glyphs.append(0x0145) #uni0683.init glyphs.append(0x017E) #uni069D.fina glyphs.append(0x0253) #uni0755.medi glyphs.append(0x0142) #uni0682.medi glyphs.append(0x01A1) #uni06A8 glyphs.append(0x0053) #uni06A9 glyphs.append(0x00D7) #uni0649.medi glyphs.append(0x01D6) #uni06B7.medi glyphs.append(0x01C0) #uni06B2.fina glyphs.append(0x0187) #uni06A0 glyphs.append(0x018B) #uni06A1 glyphs.append(0x018C) #uni06A2 glyphs.append(0x0190) #uni06A3 glyphs.append(0x02BC) #uni06A4 glyphs.append(0x0197) #uni06A5 glyphs.append(0x019B) #uni06A6 glyphs.append(0x019F) #uni06A7 glyphs.append(0x0015) #uni0635.fina glyphs.append(0x01A3) #uni06AA glyphs.append(0x01A7) #uni06AB glyphs.append(0x01AB) #uni06AC glyphs.append(0x0002) #nonmarkingreturn glyphs.append(0x01B3) #uni06AE glyphs.append(0x0055) #uni06AF glyphs.append(0x00CE) #uni0646.medi glyphs.append(0x00A9) #uni0632 glyphs.append(0x000E) #uni0633 glyphs.append(0x00A5) #uni0630 glyphs.append(0x000C) #uni0631 glyphs.append(0x00B3) #uni0636 glyphs.append(0x0016) #uni0637 glyphs.append(0x00AF) #uni0634 glyphs.append(0x0012) #uni0635 glyphs.append(0x0029) #uni0645.fina glyphs.append(0x00B7) #uni0638 glyphs.append(0x001A) #uni0639 glyphs.append(0x0001) #.null glyphs.append(0x019C) #uni06A6.fina glyphs.append(0x00AE) #uni0698.fina glyphs.append(0x0219) #uni06B70627.isol glyphs.append(0x0297) #uni0768.fina glyphs.append(0x024D) #uni0754.fina glyphs.append(0x02CF) #uni06CE.fina glyphs.append(0x022D) #uni06EF.fina glyphs.append(0x0146) #uni0683.medi glyphs.append(0x0080) #uni0625.fina glyphs.append(0x0158) #uni068B.fina glyphs.append(0x0038) #uni066F.medi glyphs.append(0x0032) #uni06440627.isol glyphs.append(0x011E) #uni0676.fina glyphs.append(0x025D) #uni0758.fina glyphs.append(0x0278) #uni0760.init glyphs.append(0x01CA) #uni06B4.medi glyphs.append(0x001D) #uni0639.fina glyphs.append(0x0013) #uni0635.init glyphs.append(0x002A) #uni0647 glyphs.append(0x00CF) #uni0646 glyphs.append(0x0026) #uni0645 glyphs.append(0x0022) #uni0644 glyphs.append(0x0020) #uni0643 glyphs.append(0x00CB) #uni0642 glyphs.append(0x00C1) #uni0641 glyphs.append(0x0003) #space glyphs.append(0x00CC) #uni0642.fina glyphs.append(0x02D3) #uni06D0.medi glyphs.append(0x0096) #uni0679.init glyphs.append(0x0030) #uni0649 glyphs.append(0x002E) #uni0648 glyphs.append(0x0282) #uni0763 glyphs.append(0x02EA) #uniFD3F glyphs.append(0x00F5) #uni06BE.init glyphs.append(0x0194) #uni06A4.fina glyphs.append(0x02C9) #uni06CB.fina glyphs.append(0x0130) #uni067D.fina glyphs.append(0x0136) #uni067F.medi glyphs.append(0x0131) #uni067D.init glyphs.append(0x0230) #uni06FF.init glyphs.append(0x02ED) #diagonal glyphs.append(0x02B0) #threedots.small.above glyphs.append(0x02B7) #hamza_medial glyphs.append(0x0065) #uni064F glyphs.append(0x0064) #uni064E glyphs.append(0x0063) #uni064D glyphs.append(0x0066) #uni064C glyphs.append(0x0039) #feh_dotless.isol glyphs.append(0x00DA) #uni064A glyphs.append(0x0182) #uni069E.fina glyphs.append(0x00C4) #uni0641.fina glyphs.append(0x0010) #uni0633.medi glyphs.append(0x0106) #shadda_01 glyphs.append(0x0193) #uni06A3.medi glyphs.append(0x025E) #uni0758.init glyphs.append(0x00E3) #uni0626.init glyphs.append(0x02CB) #uni06CF.fina glyphs.append(0x02A1) #uni076A.medi glyphs.append(0x00C6) #veh.init glyphs.append(0x00EB) #uni06440622.fina glyphs.append(0x01D5) #uni06B7.init glyphs.append(0x0000) #.notdef glyphs.append(0x029F) #uni076A.fina glyphs.append(0x0105) #kasra_01 glyphs.append(0x02D7) #uni06FA glyphs.append(0x0207) #uni06FC glyphs.append(0x0203) #uni06FB glyphs.append(0x020C) #uni06FE glyphs.append(0x020B) #uni06FD glyphs.append(0x018F) #uni06A2.medi glyphs.append(0x022E) #uni06FF glyphs.append(0x02E2) #patah.wide glyphs.append(0x02F1) #threedots.rev_alt2.below glyphs.append(0x00F3) #uni06C3.fina glyphs.append(0x02E9) #uniFD3E glyphs.append(0x00A0) #uni062C.fina glyphs.append(0x00CD) #uni0646.init glyphs.append(0x0210) #uni06440672.fina glyphs.append(0x0115) #uni0655064D glyphs.append(0x00D9) #uni064A.medi glyphs.append(0x0269) #uni075C.medi glyphs.append(0x01FB) #uni06E4 glyphs.append(0x00F6) #uni06BE.medi glyphs.append(0x0025) #uni0644.fina glyphs.append(0x004E) #uni06C1.init glyphs.append(0x0103) #fatha_01 glyphs.append(0x00CA) #uni0642.medi glyphs.append(0x0054) #uni06A9.fina glyphs.append(0x0186) #uni069F.fina glyphs.append(0x0084) #uni0671.fina glyphs.append(0x0195) #uni06A4.init glyphs.append(0x003E) #twodots.above glyphs.append(0x02E6) #twodots.vert_alt1.below glyphs.append(0x023A) #uni065D glyphs.append(0x0258) #uni0757 glyphs.append(0x015C) #uni068D.fina glyphs.append(0x021C) #uni06B80627.fina glyphs.append(0x0254) #uni0756 glyphs.append(0x0233) #riyal glyphs.append(0x00F8) #uni06F1 glyphs.append(0x00F7) #uni06F0 glyphs.append(0x00FA) #uni06F3 glyphs.append(0x00F9) #uni06F2 glyphs.append(0x004C) #uni06F5 glyphs.append(0x004B) #uni06F4 glyphs.append(0x00FC) #uni06F7 glyphs.append(0x004D) #uni06F6 glyphs.append(0x00FB) #uni06F9 glyphs.append(0x00FD) #uni06F8 glyphs.append(0x02EC) #hah_alt.fina glyphs.append(0x0237) #uni065A glyphs.append(0x0238) #uni065B glyphs.append(0x01E3) #uni06BC.init glyphs.append(0x0014) #uni0635.medi glyphs.append(0x0239) #uni065C glyphs.append(0x00E4) #uni0626.medi glyphs.append(0x0205) #uni06FB.init glyphs.append(0x026C) #uni075D.init glyphs.append(0x0259) #uni0757.fina glyphs.append(0x0286) #uni0764 glyphs.append(0x028A) #uni0765 glyphs.append(0x028E) #uni0766 glyphs.append(0x0292) #uni0767 glyphs.append(0x0276) #uni0760 glyphs.append(0x027A) #uni0761 glyphs.append(0x027E) #uni0762 glyphs.append(0x01A8) #uni06AB.fina glyphs.append(0x0220) #uni0603 glyphs.append(0x021F) #uni0602 glyphs.append(0x021E) #uni0601 glyphs.append(0x021D) #uni0600 glyphs.append(0x01C1) #uni06B2.init glyphs.append(0x017C) #uni069C.medi glyphs.append(0x0118) #uni0672.fina glyphs.append(0x0074) #beh_dotless_alt.init glyphs.append(0x0290) #uni0766.init glyphs.append(0x012A) #uni067B.medi glyphs.append(0x01DD) #uni06B9.init glyphs.append(0x0172) #uni069A.fina glyphs.append(0x02BD) #uni06C5.fina glyphs.append(0x02A6) #uni076D glyphs.append(0x029E) #uni076A glyphs.append(0x02A2) #uni076B glyphs.append(0x02A4) #uni076C glyphs.append(0x005D) #uni060C glyphs.append(0x0234) #uni060B glyphs.append(0x008A) #uni067E.fina glyphs.append(0x0222) #uni060F glyphs.append(0x0221) #uni060E glyphs.append(0x0211) #uni06440673.isol glyphs.append(0x024E) #uni0754.init glyphs.append(0x024F) #uni0754.medi glyphs.append(0x0299) #uni0768.medi glyphs.append(0x01B8) #uni06B0.fina glyphs.append(0x02B3) #fourdots.below glyphs.append(0x01E4) #uni06BC.medi glyphs.append(0x00B2) #uni0634.fina glyphs.append(0x012C) #uni067C.fina glyphs.append(0x010B) #uni0651064B glyphs.append(0x010D) #uni0651064F glyphs.append(0x010C) #uni0651064E glyphs.append(0x0150) #uni0687.fina glyphs.append(0x0050) #uni06BE glyphs.append(0x01E5) #uni06BD glyphs.append(0x01B6) #uni06AE.medi glyphs.append(0x0059) #uni06BA glyphs.append(0x01E1) #uni06BC glyphs.append(0x009E) #uni062C.init glyphs.append(0x0139) #uni0680.init glyphs.append(0x02DB) #uni076A0627.isol glyphs.append(0x0114) #uni06540652 glyphs.append(0x01E2) #uni06BC.fina glyphs.append(0x027B) #uni0761.fina glyphs.append(0x022B) #uni06EE.fina glyphs.append(0x01A0) #uni06A7.fina glyphs.append(0x002B) #uni0647.init glyphs.append(0x01B1) #uni06AD.init glyphs.append(0x0090) #uni062A.fina glyphs.append(0x01C9) #uni06B4.init glyphs.append(0x01CB) #uni06B5 glyphs.append(0x01C7) #uni06B4 glyphs.append(0x01D3) #uni06B7 glyphs.append(0x01CF) #uni06B6 glyphs.append(0x01BB) #uni06B1 glyphs.append(0x01B7) #uni06B0 glyphs.append(0x01C3) #uni06B3 glyphs.append(0x01BF) #uni06B2 glyphs.append(0x02D2) #uni06D0.init glyphs.append(0x01DB) #uni06B9 glyphs.append(0x01D7) #uni06B8 glyphs.append(0x0070) #uni062F.fina glyphs.append(0x00BD) #uni063A.medi glyphs.append(0x01E8) #uni06BF.fina glyphs.append(0x01B2) #uni06AD.medi glyphs.append(0x0082) #uni0622.fina glyphs.append(0x02BF) #uni06C6.fina glyphs.append(0x021A) #uni06B70627.fina glyphs.append(0x023B) #uni065E glyphs.append(0x0162) #uni0690.fina glyphs.append(0x01AE) #uni06AC.medi glyphs.append(0x016E) #uni0697.fina glyphs.append(0x01EF) #uni06CD.fina glyphs.append(0x0052) #uni06D2.fina glyphs.append(0x010F) #uniFC63 glyphs.append(0x007A) #twodots.below glyphs.append(0x00B9) #uni0638.medi glyphs.append(0x01DC) #uni06B9.fina glyphs.append(0x014D) #uni0685.init glyphs.append(0x0199) #uni06A5.init glyphs.append(0x00E6) #uni06440623.isol glyphs.append(0x01AF) #uni06AD glyphs.append(0x01AA) #uni06AB.medi glyphs.append(0x008E) #uni062A.init glyphs.append(0x0178) #uni069B.medi glyphs.append(0x0144) #uni0683.fina glyphs.append(0x00C2) #uni0641.init glyphs.append(0x0243) #uni0751.medi glyphs.append(0x024B) #uni0753.medi glyphs.append(0x002C) #uni0647.medi glyphs.append(0x006C) #uni0655 glyphs.append(0x006E) #uni0656 glyphs.append(0x0228) #uni0657 glyphs.append(0x0067) #uni0650 glyphs.append(0x0068) #uni0651 glyphs.append(0x0069) #uni0652 glyphs.append(0x006A) #uni0653 glyphs.append(0x0271) #uni075E.medi glyphs.append(0x0229) #uni0658 glyphs.append(0x0236) #uni0659 glyphs.append(0x001B) #uni0639.init glyphs.append(0x0245) #uni0752.fina glyphs.append(0x002D) #uni0647.fina glyphs.append(0x0283) #uni0763.fina glyphs.append(0x0093) #uni062B.medi glyphs.append(0x0107) #sukun_01 glyphs.append(0x013E) #uni0681.medi glyphs.append(0x00C7) #veh.medi glyphs.append(0x0177) #uni069B.init glyphs.append(0x0273) #uni075F.fina glyphs.append(0x007B) #alef_alt.isol glyphs.append(0x0251) #uni0755.fina glyphs.append(0x0120) #uni0677.fina glyphs.append(0x01B0) #uni06AD.fina glyphs.append(0x00ED) #uni06440671.fina glyphs.append(0x0102) #kasratan_01 glyphs.append(0x029B) #uni0769.fina glyphs.append(0x027C) #uni0761.init glyphs.append(0x02AB) #twodots.small.below glyphs.append(0x01E6) #uni06BD.fina glyphs.append(0x0293) #uni0767.fina glyphs.append(0x01CC) #uni06B5.fina glyphs.append(0x020D) #uni06AD.morocco glyphs.append(0x01B4) #uni06AE.fina glyphs.append(0x006B) #uni0654 glyphs.append(0x00AA) #uni0632.fina glyphs.append(0x00B0) #uni0634.init glyphs.append(0x01DF) #uni06BB glyphs.append(0x022C) #uni06EF glyphs.append(0x0252) #uni0755.init glyphs.append(0x01EA) #uni06BF.medi glyphs.append(0x0294) #uni0767.init glyphs.append(0x0057) #uni06AF.medi glyphs.append(0x02D8) #uni06FA.fina glyphs.append(0x000A) #uni062D.fina glyphs.append(0x028F) #uni0766.fina glyphs.append(0x0274) #uni075F.init glyphs.append(0x00DF) #uni06CC.fina glyphs.append(0x026F) #uni075E.fina glyphs.append(0x0214) #uni06440675.fina glyphs.append(0x0184) #uni069E.medi glyphs.append(0x001F) #uni0643.medi glyphs.append(0x0151) #uni0687.init glyphs.append(0x01D2) #uni06B6.medi glyphs.append(0x00E7) #uni06440623.fina glyphs.append(0x01AD) #uni06AC.init glyphs.append(0x01BA) #uni06B0.medi glyphs.append(0x029C) #uni0769.init glyphs.append(0x020A) #uni06FC.medi glyphs.append(0x02AF) #twodots.vert.small.below glyphs.append(0x0143) #uni0683 glyphs.append(0x013F) #uni0682 glyphs.append(0x013B) #uni0681 glyphs.append(0x0137) #uni0680 glyphs.append(0x014F) #uni0687 glyphs.append(0x0077) #uni0686 glyphs.append(0x014B) #uni0685 glyphs.append(0x0147) #uni0684 glyphs.append(0x0156) #uni068A.fina glyphs.append(0x0153) #uni0689 glyphs.append(0x00A7) #uni0688 glyphs.append(0x02DC) #uni076A0627.fina glyphs.append(0x0262) #uni075A glyphs.append(0x0266) #uni075C glyphs.append(0x0264) #uni075B glyphs.append(0x0116) #uni06550650 glyphs.append(0x026A) #uni075D glyphs.append(0x0272) #uni075F glyphs.append(0x01D4) #uni06B7.fina glyphs.append(0x005E) #uni061B glyphs.append(0x02F5) #ZWSP glyphs.append(0x0235) #uni061E glyphs.append(0x005C) #uni061F glyphs.append(0x003D) #onedot.above glyphs.append(0x0079) #onedot.below glyphs.append(0x00A8) #uni0688.fina glyphs.append(0x01BE) #uni06B1.medi glyphs.append(0x00BC) #uni063A.init glyphs.append(0x014E) #uni0685.medi glyphs.append(0x014C) #uni0685.fina glyphs.append(0x010E) #uni06510650 glyphs.append(0x021B) #uni06B80627.isol glyphs.append(0x00E1) #uni06D3.fina glyphs.append(0x0152) #uni0687.medi glyphs.append(0x02B4) #threedots.horz.below glyphs.append(0x0017) #uni0637.init glyphs.append(0x023D) #uni0750.fina glyphs.append(0x01C2) #uni06B2.medi glyphs.append(0x00C3) #uni0641.medi glyphs.append(0x013A) #uni0680.medi glyphs.append(0x0240) #uni0751 glyphs.append(0x023C) #uni0750 glyphs.append(0x0248) #uni0753 glyphs.append(0x0244) #uni0752 glyphs.append(0x0250) #uni0755 glyphs.append(0x024C) #uni0754 glyphs.append(0x0132) #uni067D.medi glyphs.append(0x00FF) #uni06F7.urdu glyphs.append(0x0223) #uni0610 glyphs.append(0x0224) #uni0611 glyphs.append(0x0225) #uni0612 glyphs.append(0x0226) #uni0613 glyphs.append(0x0227) #uni0614 glyphs.append(0x006F) #uni0615 glyphs.append(0x02B1) #threedots.small.below glyphs.append(0x0159) #uni068C glyphs.append(0x0157) #uni068B glyphs.append(0x0155) #uni068A glyphs.append(0x029D) #uni0769.medi glyphs.append(0x015F) #uni068F glyphs.append(0x015D) #uni068E glyphs.append(0x015B) #uni068D glyphs.append(0x0246) #uni0752.init glyphs.append(0x0164) #uni0692.fina glyphs.append(0x0024) #uni0644.medi glyphs.append(0x0149) #uni0684.init glyphs.append(0x022F) #uni06FF.fina glyphs.append(0x0296) #uni0768 glyphs.append(0x015E) #uni068E.fina glyphs.append(0x002F) #uni0648.fina glyphs.append(0x029A) #uni0769 glyphs.append(0x0113) #uni0654064F glyphs.append(0x0111) #uni0654064E glyphs.append(0x0110) #uni0654064B glyphs.append(0x0112) #uni0654064C glyphs.append(0x0021) #uni0643.fina glyphs.append(0x01C6) #uni06B3.medi glyphs.append(0x0180) #uni069D.medi glyphs.append(0x0122) #uni0678.fina glyphs.append(0x028C) #uni0765.init glyphs.append(0x01CE) #uni06B5.medi glyphs.append(0x01DE) #uni06B9.medi glyphs.append(0x017B) #uni069C.init glyphs.append(0x0183) #uni069E.init glyphs.append(0x01DA) #uni06B8.medi glyphs.append(0x0094) #uni062B.fina glyphs.append(0x017D) #uni069D glyphs.append(0x027D) #uni0761.medi glyphs.append(0x02AC) #twodots.vert.above glyphs.append(0x0298) #uni0768.init glyphs.append(0x02DA) #uni06FA.medi glyphs.append(0x018D) #uni06A2.fina glyphs.append(0x0100) #fathatan_01 glyphs.append(0x02B5) #smallv.arabic glyphs.append(0x016A) #uni0695.fina glyphs.append(0x00E9) #uni06440625.fina glyphs.append(0x0215) #uni06B50627.isol glyphs.append(0x02F6) #uni200C glyphs.append(0x00C5) #veh.isol glyphs.append(0x02F9) #uni200F glyphs.append(0x02F8) #uni200E glyphs.append(0x02F7) #uni200D glyphs.append(0x00D3) #uni06C0.fina glyphs.append(0x0206) #uni06FB.medi glyphs.append(0x011A) #uni0673.fina glyphs.append(0x02D1) #uni06D0.fina glyphs.append(0x02AA) #twodots.small.above glyphs.append(0x01A5) #uni06AA.init glyphs.append(0x0019) #uni0637.fina glyphs.append(0x016C) #uni0696.fina glyphs.append(0x02E3) #twodots_alt1.below glyphs.append(0x01F7) #uni06DF glyphs.append(0x02DE) #uni06DE glyphs.append(0x00F4) #uni06BE.fina glyphs.append(0x01F6) #uni06DC glyphs.append(0x001C) #uni0639.medi glyphs.append(0x01F4) #uni06DA glyphs.append(0x00A2) #uni062E.init glyphs.append(0x011C) #uni0675.fina glyphs.append(0x02BA) #threedots.rev.above glyphs.append(0x0009) #uni062D.medi glyphs.append(0x013D) #uni0681.init glyphs.append(0x014A) #uni0684.medi glyphs.append(0x0086) #uni0628.init glyphs.append(0x00EF) #uni06C2 glyphs.append(0x00F2) #uni06C3 glyphs.append(0x00D2) #uni06C0 glyphs.append(0x00F1) #uni06C1 glyphs.append(0x02BE) #uni06C6 glyphs.append(0x02C0) #uni06C7 glyphs.append(0x01EB) #uni06C4 glyphs.append(0x01ED) #uni06C5 glyphs.append(0x02C1) #uni06C7.fina glyphs.append(0x02C2) #uni06C8 glyphs.append(0x02C4) #uni06C9 glyphs.append(0x0154) #uni0689.fina glyphs.append(0x0124) #uni067A.fina glyphs.append(0x0255) #uni0756.fina glyphs.append(0x0168) #uni0694.fina glyphs.append(0x0247) #uni0752.medi glyphs.append(0x02C7) #uni06CA.fina glyphs.append(0x008C) #uni067E.medi glyphs.append(0x0104) #damma_01 glyphs.append(0x00D8) #uni064A.init glyphs.append(0x00DD) #uni06CC.init glyphs.append(0x02C8) #uni06CB glyphs.append(0x00DC) #uni06CC glyphs.append(0x0166) #uni0693.fina glyphs.append(0x0218) #uni06B60627.fina glyphs.append(0x02CA) #uni06CF glyphs.append(0x007C) #alef_alt.fina glyphs.append(0x01EE) #uni06CD glyphs.append(0x02CE) #uni06CE glyphs.append(0x003F) #threedots.above glyphs.append(0x01EC) #uni06C4.fina glyphs.append(0x02EB) #hah_alt.isol glyphs.append(0x01E9) #uni06BF.init glyphs.append(0x01F1) #uni06D7 glyphs.append(0x01F0) #uni06D6 glyphs.append(0x00D1) #uni06D5 glyphs.append(0x02D6) #uni06D4 glyphs.append(0x00E0) #uni06D3 glyphs.append(0x0051) #uni06D2 glyphs.append(0x02D4) #uni06D1 glyphs.append(0x02D0) #uni06D0 glyphs.append(0x0191) #uni06A3.fina glyphs.append(0x02BB) #threedots.rev.below glyphs.append(0x01F3) #uni06D9 glyphs.append(0x009A) #uni0629.fina glyphs.append(0x0087) #uni0628.medi glyphs.append(0x0135) #uni067F.init glyphs.append(0x0242) #uni0751.init glyphs.append(0x01B5) #uni06AE.init glyphs.append(0x0018) #uni0637.medi glyphs.append(0x02E8) #threedots.horz_alt1.below glyphs.append(0x023F) #uni0750.medi glyphs.append(0x0209) #uni06FC.init glyphs.append(0x00D0) #uni0646.fina glyphs.append(0x0071) #wasla glyphs.append(0x0231) #uni06FF.medi glyphs.append(0x01C4) #uni06B3.fina glyphs.append(0x0028) #uni0645.medi glyphs.append(0x0056) #uni06AF.init glyphs.append(0x0042) #uni0661 glyphs.append(0x0041) #uni0660 glyphs.append(0x0044) #uni0663 glyphs.append(0x0043) #uni0662 glyphs.append(0x0046) #uni0665 glyphs.append(0x0045) #uni0664 glyphs.append(0x0048) #uni0667 glyphs.append(0x0047) #uni0666 glyphs.append(0x004A) #uni0669 glyphs.append(0x0049) #uni0668 glyphs.append(0x0076) #uni06C1.fina glyphs.append(0x01FE) #uni06E7 glyphs.append(0x01CD) #uni06B5.init glyphs.append(0x0023) #uni0644.init glyphs.append(0x013C) #uni0681.fina glyphs.append(0x0188) #uni06A0.fina glyphs.append(0x0270) #uni075E.init glyphs.append(0x00C0) #uni06A9.medi glyphs.append(0x0232) #allah glyphs.append(0x01F9) #uni06E2 glyphs.append(0x0288) #uni0764.init glyphs.append(0x0212) #uni06440673.fina glyphs.append(0x005B) #uni066A glyphs.append(0x0060) #uni066C glyphs.append(0x005F) #uni066B glyphs.append(0x0035) #uni066E glyphs.append(0x0061) #uni066D glyphs.append(0x003B) #uni066F glyphs.append(0x02F2) #uni25CC glyphs.append(0x01D8) #uni06B8.fina glyphs.append(0x01B9) #uni06B0.init glyphs.append(0x00A6) #uni0630.fina glyphs.append(0x01A4) #uni06AA.fina glyphs.append(0x02A5) #uni076C.fina glyphs.append(0x024A) #uni0753.init glyphs.append(0x003A) #uni06A1.fina glyphs.append(0x0078) #uni0686.fina glyphs.append(0x001E) #uni0643.init glyphs.append(0x02B6) #circumflex.arabic glyphs.append(0x02E7) #threedots_alt2.below glyphs.append(0x025B) #uni0757.medi glyphs.append(0x0109) #uni0651064C glyphs.append(0x0201) #uni06EB glyphs.append(0x0006) #uni0627.fina glyphs.append(0x0092) #uni062B.init glyphs.append(0x00BF) #uni06A9.init glyphs.append(0x0171) #uni069A glyphs.append(0x0175) #uni069B glyphs.append(0x0179) #uni069C glyphs.append(0x00AC) #uni0691.fina glyphs.append(0x0181) #uni069E glyphs.append(0x0185) #uni069F glyphs.append(0x0208) #uni06FC.fina glyphs.append(0x0174) #uni069A.medi glyphs.append(0x0161) #uni0690 glyphs.append(0x00AB) #uni0691 glyphs.append(0x0163) #uni0692 glyphs.append(0x0165) #uni0693 glyphs.append(0x0167) #uni0694 glyphs.append(0x0169) #uni0695 glyphs.append(0x016B) #uni0696 glyphs.append(0x016D) #uni0697 glyphs.append(0x00AD) #uni0698 glyphs.append(0x016F) #uni0699 glyphs.append(0x0217) #uni06B60627.isol glyphs.append(0x010A) #uni0651064D glyphs.append(0x00EA) #uni06440622.isol glyphs.append(0x019D) #uni06A6.init glyphs.append(0x0058) #uni06AF.fina glyphs.append(0x02B9) #wavyhamza_below glyphs.append(0x0280) #uni0762.init glyphs.append(0x028D) #uni0765.medi glyphs.append(0x0289) #uni0764.medi glyphs.append(0x00BA) #uni0638.fina glyphs.append(0x0011) #uni0633.fina glyphs.append(0x0034) #uni0640 glyphs.append(0x0170) #uni0699.fina glyphs.append(0x0287) #uni0764.fina glyphs.append(0x0140) #uni0682.fina glyphs.append(0x02D9) #uni06FA.init glyphs.append(0x0097) #uni0679.medi glyphs.append(0x0040) #threedots.below glyphs.append(0x00D6) #uni0649.init return glyphs
davelab6/pyfontaine
fontaine/charsets/noto_glyphs/notokufiarabic_regular.py
Python
gpl-3.0
33,355
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.DirectoryServices; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using GitCommands; using GitCommands.Config; using GitCommands.Git; using GitUI.BuildServerIntegration; using GitUI.CommandsDialogs; using GitUI.HelperDialogs; using GitUI.Hotkey; using GitUI.RevisionGridClasses; using GitUI.Script; using Gravatar; using ResourceManager; using GitUI.UserControls.RevisionGridClasses; using GitUI.CommandsDialogs.BrowseDialog; using GitUI.UserControls; namespace GitUI { public enum RevisionGridLayout { FilledBranchesSmall = 1, FilledBranchesSmallWithGraph = 2, Small = 3, SmallWithGraph = 4, Card = 5, CardWithGraph = 6, LargeCard = 7, LargeCardWithGraph = 8 } public enum RevisionGraphDrawStyleEnum { Normal, DrawNonRelativesGray, HighlightSelected } [DefaultEvent("DoubleClick")] public sealed partial class RevisionGrid : GitModuleControl { private readonly TranslationString _droppingFilesBlocked = new TranslationString("For you own protection dropping more than 10 patch files at once is blocked!"); private readonly TranslationString _cannotHighlightSelectedBranch = new TranslationString("Cannot highlight selected branch when revision graph is loading."); private readonly TranslationString _noRevisionFoundError = new TranslationString("No revision found."); private const int NodeDimension = 8; private const int LaneWidth = 13; private const int LaneLineWidth = 2; private const int MaxSuperprojectRefs = 4; private Brush _selectedItemBrush; private SolidBrush _authoredRevisionsBrush; private Brush _filledItemBrush; // disposable brush private readonly FormRevisionFilter _revisionFilter = new FormRevisionFilter(); private RefsFiltringOptions _refsOptions = RefsFiltringOptions.All | RefsFiltringOptions.Boundary; private bool _initialLoad = true; private string _initialSelectedRevision; private string _lastQuickSearchString = string.Empty; private Label _quickSearchLabel; private string _quickSearchString; private RevisionGraph _revisionGraphCommand; public BuildServerWatcher BuildServerWatcher { get; private set; } private RevisionGridLayout _layout; private int _rowHeigth; public event EventHandler<GitModuleEventArgs> GitModuleChanged; public event EventHandler<DoubleClickRevisionEventArgs> DoubleClickRevision; public event EventHandler<EventArgs> ShowFirstParentsToggled; private readonly RevisionGridMenuCommands _revisionGridMenuCommands; bool _showCurrentBranchOnlyToolStripMenuItemChecked; // refactoring bool _showAllBranchesToolStripMenuItemChecked; // refactoring bool _showFilteredBranchesToolStripMenuItemChecked; // refactoring private readonly ParentChildNavigationHistory _parentChildNavigationHistory; private readonly NavigationHistory _navigationHistory = new NavigationHistory(); private AuthorEmailBasedRevisionHighlighting _revisionHighlighting; private GitRevision _baseCommitToCompare = null; public RevisionGrid() { InitLayout(); InitializeComponent(); // Parent-child navigation can expect that SetSelectedRevision is always successfull since it always uses first-parents _parentChildNavigationHistory = new ParentChildNavigationHistory(revision => SetSelectedRevision(revision)); _revisionHighlighting = new AuthorEmailBasedRevisionHighlighting(); this.Loading.Image = global::GitUI.Properties.Resources.loadingpanel; Translate(); _revisionGridMenuCommands = new RevisionGridMenuCommands(this); _revisionGridMenuCommands.CreateOrUpdateMenuCommands(); // fill View context menu from MenuCommands var viewMenuCommands = _revisionGridMenuCommands.GetViewMenuCommands(); FillMenuFromMenuCommands(viewMenuCommands, viewToolStripMenuItem); // fill Navigate context menu from MenuCommands var navigateMenuCommands = _revisionGridMenuCommands.GetNavigateMenuCommands(); FillMenuFromMenuCommands(navigateMenuCommands, navigateToolStripMenuItem); NormalFont = AppSettings.Font; Loading.Paint += Loading_Paint; Revisions.CellPainting += RevisionsCellPainting; Revisions.CellFormatting += RevisionsCellFormatting; Revisions.KeyPress += RevisionsKeyPress; Revisions.KeyDown += RevisionsKeyDown; Revisions.MouseDown += RevisionsMouseDown; showMergeCommitsToolStripMenuItem.Checked = AppSettings.ShowMergeCommits; BranchFilter = String.Empty; SetShowBranches(); QuickRevisionFilter = ""; FixedRevisionFilter = ""; FixedPathFilter = ""; InMemFilterIgnoreCase = true; InMemAuthorFilter = ""; InMemCommitterFilter = ""; InMemMessageFilter = ""; AllowGraphWithFilter = false; _quickSearchString = ""; quickSearchTimer.Tick += QuickSearchTimerTick; Revisions.Loading += RevisionsLoading; //Allow to drop patch file on revisiongrid Revisions.DragEnter += Revisions_DragEnter; Revisions.DragDrop += Revisions_DragDrop; Revisions.AllowDrop = true; Revisions.ColumnHeadersVisible = false; Revisions.IdColumn.Visible = AppSettings.ShowIds; IsMessageMultilineDataGridViewColumn.Width = 25; IsMessageMultilineDataGridViewColumn.DisplayIndex = 2; IsMessageMultilineDataGridViewColumn.Resizable = DataGridViewTriState.False; this.HotkeysEnabled = true; try { SetRevisionsLayout((RevisionGridLayout)AppSettings.RevisionGraphLayout); } catch { SetRevisionsLayout(RevisionGridLayout.SmallWithGraph); } compareToBaseToolStripMenuItem.Enabled = false; } private void FillMenuFromMenuCommands(IEnumerable<MenuCommand> menuCommands, ToolStripMenuItem targetMenuItem) { foreach (var menuCommand in menuCommands) { var toolStripItem = (ToolStripItem)MenuCommand.CreateToolStripItem(menuCommand); var toolStripMenuItem = toolStripItem as ToolStripMenuItem; if (toolStripMenuItem != null) { menuCommand.RegisterMenuItem(toolStripMenuItem); } targetMenuItem.DropDownItems.Add(toolStripItem); } } void Loading_Paint(object sender, PaintEventArgs e) { // If our loading state has changed since the last paint, update it. if (Loading != null) { if (Loading.Visible != _isLoading) { Loading.Visible = _isLoading; } } } [Browsable(false)] public Font HeadFont { get; private set; } [Browsable(false)] public Font SuperprojectFont { get; private set; } [Browsable(false)] public int LastScrollPos { get; private set; } [Browsable(false)] public string[] LastSelectedRows { get; private set; } [Browsable(false)] public Font RefsFont { get; private set; } private Font _normalFont; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Font NormalFont { get { return _normalFont; } set { _normalFont = value; MessageDataGridViewColumn.DefaultCellStyle.Font = _normalFont; DateDataGridViewColumn.DefaultCellStyle.Font = _normalFont; IdDataGridViewColumn.DefaultCellStyle.Font = new Font("Consolas", _normalFont.SizeInPoints); IsMessageMultilineDataGridViewColumn.DefaultCellStyle.Font = _normalFont; RefsFont = IsFilledBranchesLayout() ? _normalFont : new Font(_normalFont, FontStyle.Bold); HeadFont = new Font(_normalFont, FontStyle.Bold); SuperprojectFont = new Font(_normalFont, FontStyle.Underline); } } [Category("Filter")] [DefaultValue("")] public string QuickRevisionFilter { get; set; } [Category("Filter")] [DefaultValue("")] public string FixedRevisionFilter { get; set; } [Category("Filter")] [DefaultValue("")] public string FixedPathFilter { get; set; } [Category("Filter")] [DefaultValue(true)] public bool InMemFilterIgnoreCase { get; set; } [Category("Filter")] [DefaultValue("")] public string InMemAuthorFilter { get; set; } [Category("Filter")] [DefaultValue("")] public string InMemCommitterFilter { get; set; } [Category("Filter")] [DefaultValue("")] public string InMemMessageFilter { get; set; } [Category("Filter")] [DefaultValue("")] public string BranchFilter { get; set; } [Category("Filter")] [DefaultValue(false)] public bool AllowGraphWithFilter { get; set; } [Browsable(false)] public string CurrentCheckout { get; private set; } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string FiltredFileName { get; set; } [Browsable(false)] public Task<SuperProjectInfo> SuperprojectCurrentCheckout { get; private set; } [Browsable(false)] public int LastRowIndex { get; private set; } [Description("Indicates whether the user is allowed to select more than one commit at a time.")] [Category("Behavior")] [DefaultValue(true)] public bool MultiSelect { get { return Revisions.MultiSelect; } set { Revisions.MultiSelect = value; } } [Description("Show uncommited changes in revision grid if enabled in settings.")] [Category("Behavior")] [DefaultValue(false)] public bool ShowUncommitedChangesIfPossible { get; set; } [Description("Show build server information in revision grid if enabled in settings.")] [Category("Behavior")] [DefaultValue(false)] public bool ShowBuildServerInfo { get; set; } [Description("Do not open the commit info dialog on double click. This is used if the double click event is handled elseswhere.")] [Category("Behavior")] [DefaultValue(false)] public bool DoubleClickDoesNotOpenCommitInfo { get; set; } private IndexWatcher _indexWatcher; [Browsable(false)] public IndexWatcher IndexWatcher { get { if (_indexWatcher == null) _indexWatcher = new IndexWatcher(UICommandsSource); return _indexWatcher; } } [Browsable(false)] [Description("Object calculating in memory history rewrites")] public FollowParentRewriter Rewriter { get; set; } public void SetInitialRevision(GitRevision initialSelectedRevision) { _initialSelectedRevision = initialSelectedRevision != null ? initialSelectedRevision.Guid : null; } private bool _isLoading; private void RevisionsLoading(object sender, DvcsGraph.LoadingEventArgs e) { // Since this can happen on a background thread, we'll just set a // flag and deal with it next time we paint (a bit of a hack, but // it works) _isLoading = e.IsLoading; } private void ShowQuickSearchString() { if (_quickSearchLabel == null) { _quickSearchLabel = new Label { Location = new Point(10, 10), BorderStyle = BorderStyle.FixedSingle, ForeColor = SystemColors.InfoText, BackColor = SystemColors.Info }; Controls.Add(_quickSearchLabel); } _quickSearchLabel.Visible = true; _quickSearchLabel.BringToFront(); _quickSearchLabel.Text = _quickSearchString; _quickSearchLabel.AutoSize = true; } private void HideQuickSearchString() { if (_quickSearchLabel != null) _quickSearchLabel.Visible = false; } private void QuickSearchTimerTick(object sender, EventArgs e) { quickSearchTimer.Stop(); _quickSearchString = ""; HideQuickSearchString(); } private void RestartQuickSearchTimer() { quickSearchTimer.Stop(); quickSearchTimer.Interval = AppSettings.RevisionGridQuickSearchTimeout; quickSearchTimer.Start(); } private void RevisionsKeyPress(object sender, KeyPressEventArgs e) { var curIndex = -1; if (Revisions.SelectedRows.Count > 0) curIndex = Revisions.SelectedRows[0].Index; curIndex = curIndex >= 0 ? curIndex : 0; if (e.KeyChar == 8 && _quickSearchString.Length > 1) //backspace { RestartQuickSearchTimer(); _quickSearchString = _quickSearchString.Substring(0, _quickSearchString.Length - 1); FindNextMatch(curIndex, _quickSearchString, false); _lastQuickSearchString = _quickSearchString; e.Handled = true; ShowQuickSearchString(); } else if (!char.IsControl(e.KeyChar)) { RestartQuickSearchTimer(); //The code below is meant to fix the weird keyvalues when pressing keys e.g. ".". _quickSearchString = string.Concat(_quickSearchString, char.ToLower(e.KeyChar)); FindNextMatch(curIndex, _quickSearchString, false); _lastQuickSearchString = _quickSearchString; e.Handled = true; ShowQuickSearchString(); } else { _quickSearchString = ""; HideQuickSearchString(); e.Handled = false; } } private void RevisionsKeyDown(object sender, KeyEventArgs e) { // BrowserBack/BrowserForward keys and additional handling for Alt+Right/Left sent by some keyboards if ((e.KeyCode == Keys.BrowserBack) || ((e.KeyCode == Keys.Left) && (e.Modifiers.HasFlag(Keys.Alt)))) { NavigateBackward(); } else if ((e.KeyCode == Keys.BrowserForward) || ((e.KeyCode == Keys.Right) && (e.Modifiers.HasFlag(Keys.Alt)))) { NavigateForward(); } } private void RevisionsMouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.XButton1) { NavigateBackward(); } else if (e.Button == MouseButtons.XButton2) { NavigateForward(); } } public void ResetNavigationHistory() { var selectedRevisions = GetSelectedRevisions(); if (selectedRevisions.Count == 1) { _navigationHistory.Push(selectedRevisions[0].Guid); } else { _navigationHistory.Clear(); } } public void NavigateBackward() { if (_navigationHistory.CanNavigateBackward) { InternalSetSelectedRevision(_navigationHistory.NavigateBackward()); } } public void NavigateForward() { if (_navigationHistory.CanNavigateForward) { InternalSetSelectedRevision(_navigationHistory.NavigateForward()); } } private void FindNextMatch(int startIndex, string searchString, bool reverse) { if (Revisions.RowCount == 0) return; int? searchResult; if (reverse) searchResult = SearchInReverseOrder(startIndex, searchString); else searchResult = SearchForward(startIndex, searchString); if (!searchResult.HasValue) return; Revisions.ClearSelection(); Revisions.Rows[searchResult.Value].Selected = true; Revisions.CurrentCell = Revisions.Rows[searchResult.Value].Cells[1]; } private int? SearchForward(int startIndex, string searchString) { // Check for out of bounds roll over if required int index; if (startIndex < 0 || startIndex >= Revisions.RowCount) startIndex = 0; for (index = startIndex; index < Revisions.RowCount; ++index) { if (GetRevision(index).MatchesSearchString(searchString)) return index; } // We didn't find it so start searching from the top for (index = 0; index < startIndex; ++index) { if (GetRevision(index).MatchesSearchString(searchString)) return index; } return null; } private int? SearchInReverseOrder(int startIndex, string searchString) { // Check for out of bounds roll over if required int index; if (startIndex < 0 || startIndex >= Revisions.RowCount) startIndex = Revisions.RowCount - 1; for (index = startIndex; index >= 0; --index) { if (GetRevision(index).MatchesSearchString(searchString)) return index; } // We didn't find it so start searching from the bottom for (index = Revisions.RowCount - 1; index > startIndex; --index) { if (GetRevision(index).MatchesSearchString(searchString)) return index; } return null; } public void DisableContextMenu() { Revisions.ContextMenuStrip = null; } public void FormatQuickFilter(string filter, bool[] parameters, out string revListArgs, out string inMemMessageFilter, out string inMemCommitterFilter, out string inMemAuthorFilter) { revListArgs = string.Empty; inMemMessageFilter = string.Empty; inMemCommitterFilter = string.Empty; inMemAuthorFilter = string.Empty; if (!string.IsNullOrEmpty(filter)) { // hash filtering only possible in memory var cmdLineSafe = GitCommandHelpers.VersionInUse.IsRegExStringCmdPassable(filter); revListArgs = " --regexp-ignore-case "; if (parameters[0]) if (cmdLineSafe && !MessageFilterCouldBeSHA(filter)) revListArgs += "--grep=\"" + filter + "\" "; else inMemMessageFilter = filter; if (parameters[1] && !filter.IsNullOrWhiteSpace()) if (cmdLineSafe) revListArgs += "--committer=\"" + filter + "\" "; else inMemCommitterFilter = filter; if (parameters[2] && !filter.IsNullOrWhiteSpace()) if (cmdLineSafe) revListArgs += "--author=\"" + filter + "\" "; else inMemAuthorFilter = filter; if (parameters[3]) if (cmdLineSafe) revListArgs += "\"-S" + filter + "\" "; else throw new InvalidOperationException("Filter text not valid for \"Diff contains\" filter."); } } public bool SetAndApplyBranchFilter(string filter) { if (filter.Equals(_revisionFilter.GetBranchFilter())) return false; if (filter.Equals("")) { AppSettings.BranchFilterEnabled = false; AppSettings.ShowCurrentBranchOnly = true; } else { AppSettings.BranchFilterEnabled = true; AppSettings.ShowCurrentBranchOnly = false; _revisionFilter.SetBranchFilter(filter); } SetShowBranches(); return true; } public void SetLimit(int limit) { _revisionFilter.SetLimit(limit); } public override void Refresh() { if (IsDisposed) return; SetRevisionsLayout(); base.Refresh(); Revisions.Refresh(); } protected override void OnCreateControl() { base.OnCreateControl(); _isLoading = true; Error.Visible = false; NoCommits.Visible = false; NoGit.Visible = false; Revisions.Visible = false; Loading.Visible = true; Loading.BringToFront(); BuildServerWatcher = new BuildServerWatcher(this, Revisions); } public new void Load() { if (!DesignMode) ReloadHotkeys(); ForceRefreshRevisions(); } public event EventHandler SelectionChanged; public void SetSelectedIndex(int index) { if (Revisions.Rows[index].Selected) return; Revisions.ClearSelection(); Revisions.Rows[index].Selected = true; Revisions.CurrentCell = Revisions.Rows[index].Cells[1]; Revisions.Select(); } // Selects row cotaining revision given its revisionId // Returns whether the required revision was found and selected private bool InternalSetSelectedRevision(string revision) { int index = FindRevisionIndex(revision); if( index >= 0 ) { SetSelectedIndex(index); return true; } else { Revisions.ClearSelection(); Revisions.Select(); return false; } } /// <summary> /// Find specified revision in known to the grid revisions /// </summary> /// <param name="revision">Revision to lookup</param> /// <returns>Index of the found revision or -1 if nothing was found</returns> private int FindRevisionIndex(string revision) { if (string.IsNullOrWhiteSpace(revision)) { return -1; } for (int i = 0; i < Revisions.RowCount; i++) { if (GetRevision(i).Guid == revision) { return i; } } return -1; } public bool SetSelectedRevision(string revision) { var found = InternalSetSelectedRevision(revision); if (found) { _navigationHistory.Push(revision); } return found; } public GitRevision GetRevision(string guid) { return Revisions.GetRevision(guid); } public bool SetSelectedRevision(GitRevision revision) { return SetSelectedRevision(revision != null ? revision.Guid : null); } public void HighlightBranch(string aId) { RevisionGraphDrawStyle = RevisionGraphDrawStyleEnum.HighlightSelected; Revisions.HighlightBranch(aId); } private void RevisionsSelectionChanged(object sender, EventArgs e) { _parentChildNavigationHistory.RevisionsSelectionChanged(); if (Revisions.SelectedRows.Count > 0) LastRowIndex = Revisions.SelectedRows[0].Index; SelectionTimer.Enabled = false; SelectionTimer.Stop(); SelectionTimer.Enabled = true; SelectionTimer.Start(); var selectedRevisions = GetSelectedRevisions(); var firstSelectedRevision = selectedRevisions.FirstOrDefault(); if (selectedRevisions.Count == 1 && firstSelectedRevision != null) _navigationHistory.Push(firstSelectedRevision.Guid); if (this.Parent != null && !Revisions.UpdatingVisibleRows && _revisionHighlighting.ProcessRevisionSelectionChange(Module, selectedRevisions) == AuthorEmailBasedRevisionHighlighting.SelectionChangeAction.RefreshUserInterface) { Refresh(); } } public RevisionGraphDrawStyleEnum RevisionGraphDrawStyle { get { return Revisions.RevisionGraphDrawStyle; } set { Revisions.RevisionGraphDrawStyle = value; } } public List<GitRevision> GetSelectedRevisions() { return GetSelectedRevisions(null); } public List<GitRevision> GetSelectedRevisions(SortDirection? direction) { var rows = Revisions .SelectedRows .Cast<DataGridViewRow>() .Where(row => Revisions.RowCount > row.Index); if (direction.HasValue) { int d = direction.Value == SortDirection.Ascending ? 1 : -1; rows = rows.OrderBy((row) => row.Index, (r1, r2) => d * (r1 - r2)); } return rows .Select(row => GetRevision(row.Index)) .ToList(); } public List<string> GetRevisionChildren(string revision) { return Revisions.GetRevisionChildren(revision); } public GitRevision GetRevision(int aRow) { return Revisions.GetRowData(aRow); } public GitRevision GetCurrentRevision() { var revision = Module.GetRevision(CurrentCheckout, true); var refs = Module.GetRefs(true, true); foreach (var gitRef in refs) { if (gitRef.Guid.Equals(revision.Guid)) { revision.Refs.Add(gitRef); } } return revision; } public void RefreshRevisions() { if (IndexWatcher.IndexChanged) ForceRefreshRevisions(); } private class RevisionGraphInMemFilterOr : RevisionGraphInMemFilter { private RevisionGraphInMemFilter fFilter1; private RevisionGraphInMemFilter fFilter2; public RevisionGraphInMemFilterOr(RevisionGraphInMemFilter aFilter1, RevisionGraphInMemFilter aFilter2) { fFilter1 = aFilter1; fFilter2 = aFilter2; } public override bool PassThru(GitRevision rev) { return fFilter1.PassThru(rev) || fFilter2.PassThru(rev); } } private class RevisionGridInMemFilter : RevisionGraphInMemFilter { private readonly string _AuthorFilter; private readonly Regex _AuthorFilterRegex; private readonly string _CommitterFilter; private readonly Regex _CommitterFilterRegex; private readonly string _MessageFilter; private readonly Regex _MessageFilterRegex; private readonly string _ShaFilter; private readonly Regex _ShaFilterRegex; public RevisionGridInMemFilter(string authorFilter, string committerFilter, string messageFilter, bool ignoreCase) { SetUpVars(authorFilter, ref _AuthorFilter, ref _AuthorFilterRegex, ignoreCase); SetUpVars(committerFilter, ref _CommitterFilter, ref _CommitterFilterRegex, ignoreCase); SetUpVars(messageFilter, ref _MessageFilter, ref _MessageFilterRegex, ignoreCase); if (!string.IsNullOrEmpty(_MessageFilter) && MessageFilterCouldBeSHA(_MessageFilter)) { SetUpVars(messageFilter, ref _ShaFilter, ref _ShaFilterRegex, false); } } private static void SetUpVars(string filterValue, ref string filterStr, ref Regex filterRegEx, bool ignoreCase) { RegexOptions opts = RegexOptions.None; if (ignoreCase) opts = opts | RegexOptions.IgnoreCase; filterStr = filterValue != null ? filterValue.Trim() : string.Empty; try { filterRegEx = new Regex(filterStr, opts); } catch (ArgumentException) { filterRegEx = null; } } private static bool CheckCondition(string filter, Regex regex, string value) { return string.IsNullOrEmpty(filter) || ((regex != null) && (value != null) && regex.Match(value).Success); } public override bool PassThru(GitRevision rev) { return CheckCondition(_AuthorFilter, _AuthorFilterRegex, rev.Author) && CheckCondition(_CommitterFilter, _CommitterFilterRegex, rev.Committer) && (CheckCondition(_MessageFilter, _MessageFilterRegex, rev.Body) || CheckCondition(_ShaFilter, _ShaFilterRegex, rev.Guid)); } public static RevisionGridInMemFilter CreateIfNeeded(string authorFilter, string committerFilter, string messageFilter, bool ignoreCase) { if (!(string.IsNullOrEmpty(authorFilter) && string.IsNullOrEmpty(committerFilter) && string.IsNullOrEmpty(messageFilter) && !MessageFilterCouldBeSHA(messageFilter))) return new RevisionGridInMemFilter(authorFilter, committerFilter, messageFilter, ignoreCase); else return null; } } public void ReloadHotkeys() { this.Hotkeys = HotkeySettingsManager.LoadHotkeys(HotkeySettingsName); _revisionGridMenuCommands.CreateOrUpdateMenuCommands(); } public void ReloadTranslation() { Translate(); } public bool ShowRemoteRef(GitRef r) { if (r.IsTag) return AppSettings.ShowSuperprojectTags; if (r.IsHead) return AppSettings.ShowSuperprojectBranches; if (r.IsRemote) return AppSettings.ShowSuperprojectRemoteBranches; return false; } [Browsable(false)] public Task<bool> UnstagedChanges { get; private set; } [Browsable(false)] public Task<bool> StagedChanges { get; private set; } private string _filtredCurrentCheckout; public void ForceRefreshRevisions() { try { RevisionGraphDrawStyle = RevisionGraphDrawStyleEnum.DrawNonRelativesGray; IsMessageMultilineDataGridViewColumn.Visible = AppSettings.ShowIndicatorForMultilineMessage; ApplyFilterFromRevisionFilterDialog(); _initialLoad = true; BuildServerWatcher.CancelBuildStatusFetchOperation(); DisposeRevisionGraphCommand(); var newCurrentCheckout = Module.GetCurrentCheckout(); Task<SuperProjectInfo> newSuperPrjectInfo = Task.Factory.StartNew(() => GetSuperprojectCheckout(ShowRemoteRef)); newSuperPrjectInfo.ContinueWith((task) => Refresh(), TaskScheduler.FromCurrentSynchronizationContext()); //Only check for tracked files. This usually makes more sense and it performs a lot //better then checking for untracked files. // TODO: Check FiltredFileName Task<bool> unstagedChanges = Task.Factory.StartNew(() => Module.GetUnstagedFiles().Any()); Task<bool> stagedChanges = Task.Factory.StartNew(() => Module.GetStagedFiles().Any()); // If the current checkout changed, don't get the currently selected rows, select the // new current checkout instead. if (newCurrentCheckout == CurrentCheckout) { LastSelectedRows = Revisions.SelectedIds; } else { // This is a new checkout, so ensure the variable is cleared out. LastSelectedRows = null; } Revisions.ClearSelection(); CurrentCheckout = newCurrentCheckout; _filtredCurrentCheckout = null; _currentCheckoutParents = null; SuperprojectCurrentCheckout = newSuperPrjectInfo; UnstagedChanges = unstagedChanges; StagedChanges = stagedChanges; Revisions.Clear(); Error.Visible = false; if (!Module.IsValidGitWorkingDir()) { Revisions.Visible = false; NoCommits.Visible = true; Loading.Visible = false; NoGit.Visible = true; string dir = Module.WorkingDir; if (String.IsNullOrEmpty(dir) || !Directory.Exists(dir) || Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length == 0) CloneRepository.Show(); else CloneRepository.Hide(); NoGit.BringToFront(); return; } NoCommits.Visible = false; NoGit.Visible = false; Revisions.Visible = true; Revisions.BringToFront(); Revisions.Enabled = false; Loading.Visible = true; Loading.BringToFront(); _isLoading = true; base.Refresh(); IndexWatcher.Reset(); if (!AppSettings.ShowGitNotes && (_refsOptions & (RefsFiltringOptions.All | RefsFiltringOptions.Boundary)) == (RefsFiltringOptions.All | RefsFiltringOptions.Boundary)) _refsOptions |= RefsFiltringOptions.ShowGitNotes; if (AppSettings.ShowGitNotes) _refsOptions &= ~RefsFiltringOptions.ShowGitNotes; if (!AppSettings.ShowMergeCommits) _refsOptions |= RefsFiltringOptions.NoMerges; if (AppSettings.ShowFirstParent) _refsOptions |= RefsFiltringOptions.FirstParent; if (AppSettings.ShowSimplifyByDecoration) _refsOptions |= RefsFiltringOptions.SimplifyByDecoration; RevisionGridInMemFilter revisionFilterIMF = RevisionGridInMemFilter.CreateIfNeeded(_revisionFilter.GetInMemAuthorFilter(), _revisionFilter.GetInMemCommitterFilter(), _revisionFilter.GetInMemMessageFilter(), _revisionFilter.GetIgnoreCase()); RevisionGridInMemFilter filterBarIMF = RevisionGridInMemFilter.CreateIfNeeded(InMemAuthorFilter, InMemCommitterFilter, InMemMessageFilter, InMemFilterIgnoreCase); RevisionGraphInMemFilter revGraphIMF; if (revisionFilterIMF != null && filterBarIMF != null) revGraphIMF = new RevisionGraphInMemFilterOr(revisionFilterIMF, filterBarIMF); else if (revisionFilterIMF != null) revGraphIMF = revisionFilterIMF; else revGraphIMF = filterBarIMF; _revisionGraphCommand = new RevisionGraph(Module) { BranchFilter = BranchFilter, RefsOptions = _refsOptions, RevisionFilter = _revisionFilter.GetRevisionFilter() + QuickRevisionFilter + FixedRevisionFilter, PathFilter = _revisionFilter.GetPathFilter() + FixedPathFilter, }; _revisionGraphCommand.Updated += GitGetCommitsCommandUpdated; _revisionGraphCommand.Exited += GitGetCommitsCommandExited; _revisionGraphCommand.Error += _revisionGraphCommand_Error; _revisionGraphCommand.InMemFilter = revGraphIMF; _revisionGraphCommand.Execute(); LoadRevisions(); SetRevisionsLayout(); ResetNavigationHistory(); } catch (Exception) { Error.Visible = true; Error.BringToFront(); throw; } } public class SuperProjectInfo { public string CurrentBranch; public string Conflict_Base; public string Conflict_Remote; public string Conflict_Local; public Dictionary<string, List<GitRef>> Refs; } private SuperProjectInfo GetSuperprojectCheckout(Func<GitRef, bool> showRemoteRef) { if (Module.SuperprojectModule == null) return null; SuperProjectInfo spi = new SuperProjectInfo(); var currentCheckout = Module.GetSuperprojectCurrentCheckout(); if (currentCheckout.Key == 'U') { // return local and remote hashes var array = Module.SuperprojectModule.GetConflict(Module.SubmodulePath); spi.Conflict_Base = array.Base.Hash; spi.Conflict_Local = array.Local.Hash; spi.Conflict_Remote = array.Remote.Hash; } else { spi.CurrentBranch = currentCheckout.Value; } var refs = Module.SuperprojectModule.GetSubmoduleItemsForEachRef(Module.SubmodulePath, showRemoteRef); if (refs != null) { spi.Refs = refs.Where(a => a.Value != null).GroupBy(a => a.Value.Guid).ToDictionary(gr => gr.Key, gr => gr.Select(a => a.Key).ToList()); } return spi; } private static readonly Regex PotentialShaPattern = new Regex(@"^[a-f0-9]{5,}", RegexOptions.Compiled); public static bool MessageFilterCouldBeSHA(string filter) { bool result = PotentialShaPattern.IsMatch(filter); return result; } private void _revisionGraphCommand_Error(object sender, AsyncErrorEventArgs e) { // This has to happen on the UI thread this.InvokeSync(o => { Error.Visible = true; //Error.BringToFront(); NoGit.Visible = false; NoCommits.Visible = false; Revisions.Visible = false; Loading.Visible = false; }, this); DisposeRevisionGraphCommand(); this.InvokeAsync(() => { throw e.Exception; } ); e.Handled = true; } private void GitGetCommitsCommandUpdated(object sender, EventArgs e) { var updatedEvent = (RevisionGraph.RevisionGraphUpdatedEventArgs)e; if (Rewriter != null) { Rewriter.PushRevision(updatedEvent.Revision); Rewriter.Flush(false, UpdateGraph); } else { UpdateGraph(updatedEvent.Revision); } } internal bool FilterIsApplied(bool inclBranchFilter) { return (inclBranchFilter && !string.IsNullOrEmpty(BranchFilter)) || !(string.IsNullOrEmpty(QuickRevisionFilter) && !_revisionFilter.FilterEnabled() && string.IsNullOrEmpty(InMemAuthorFilter) && string.IsNullOrEmpty(InMemCommitterFilter) && string.IsNullOrEmpty(InMemMessageFilter)); } private bool ShouldHideGraph(bool inclBranchFilter) { return (inclBranchFilter && !string.IsNullOrEmpty(BranchFilter)) || !(!_revisionFilter.ShouldHideGraph() && string.IsNullOrEmpty(InMemAuthorFilter) && string.IsNullOrEmpty(InMemCommitterFilter) && string.IsNullOrEmpty(InMemMessageFilter)); } private void DisposeRevisionGraphCommand() { if (_revisionGraphCommand != null) { //Dispose command, it is not needed anymore _revisionGraphCommand.Updated -= GitGetCommitsCommandUpdated; _revisionGraphCommand.Exited -= GitGetCommitsCommandExited; _revisionGraphCommand.Error -= _revisionGraphCommand_Error; _revisionGraphCommand.Dispose(); _revisionGraphCommand = null; } } private void GitGetCommitsCommandExited(object sender, EventArgs e) { if (Rewriter != null) { Rewriter.Flush(true, UpdateGraph); } _isLoading = false; if (_revisionGraphCommand.RevisionCount == 0 && !FilterIsApplied(true)) { // This has to happen on the UI thread this.InvokeSync(o => { NoGit.Visible = false; NoCommits.Visible = true; //NoCommits.BringToFront(); Revisions.Visible = false; Loading.Visible = false; }, this); } else { // This has to happen on the UI thread this.InvokeSync(o => { UpdateGraph(null); Loading.Visible = false; SelectInitialRevision(); _isLoading = false; if (ShowBuildServerInfo) BuildServerWatcher.LaunchBuildServerInfoFetchOperation(); }, this); } DisposeRevisionGraphCommand(); } private void SelectInitialRevision() { string filtredCurrentCheckout = _filtredCurrentCheckout; string[] lastSelectedRows = LastSelectedRows ?? new string[0]; // When 'git log --first-parent' filtration is applied we can have the following situation: // - user via CommitInfo traverses to a not first parent commit // - branch filter is applied to be able to traverse to this commit // - then user resets this branch filter with ShowFirstParent filter still on // // In such situation selected commits likelly are absent from availabe Revisions and // thus it is not possible to make them selectable. To prevent jumping around to a random commit // in UI we first filter out all unavailable commits from LastSelectedRows. if (AppSettings.ShowFirstParent) { lastSelectedRows = lastSelectedRows.Where(revision => FindRevisionIndex(revision) >= 0).ToArray(); } if (lastSelectedRows.Any()) { Revisions.SelectedIds = lastSelectedRows; LastSelectedRows = null; } else { if (!string.IsNullOrEmpty(_initialSelectedRevision)) { int index = SearchRevision(_initialSelectedRevision); if (index >= 0) SetSelectedIndex(index); } else { SetSelectedRevision(filtredCurrentCheckout); } } if (string.IsNullOrEmpty(filtredCurrentCheckout)) return; if (!Revisions.IsRevisionRelative(filtredCurrentCheckout)) { HighlightBranch(filtredCurrentCheckout); } } private string[] GetAllParents(string initRevision) { var revListParams = "rev-list "; if (AppSettings.OrderRevisionByDate) revListParams += "--date-order "; else revListParams += "--topo-order "; if (AppSettings.MaxRevisionGraphCommits > 0) revListParams += string.Format("--max-count=\"{0}\" ", (int)AppSettings.MaxRevisionGraphCommits); return Module.ReadGitOutputLines(revListParams + initRevision).ToArray(); } private int SearchRevision(string initRevision) { var exactIndex = Revisions.TryGetRevisionIndex(initRevision); if (exactIndex.HasValue) return exactIndex.Value; foreach (var parentHash in GetAllParents(initRevision)) { var parentIndex = Revisions.TryGetRevisionIndex(parentHash); if (parentIndex.HasValue) return parentIndex.Value; } return -1; } private static string GetDateHeaderText() { return AppSettings.ShowAuthorDate ? Strings.GetAuthorDateText() : Strings.GetCommitDateText(); } private void LoadRevisions() { if (_revisionGraphCommand == null) { return; } Revisions.SuspendLayout(); Revisions.MessageColumn.HeaderText = Strings.GetMessageText(); Revisions.AuthorColumn.HeaderText = Strings.GetAuthorText(); Revisions.DateColumn.HeaderText = GetDateHeaderText(); Revisions.SelectionChanged -= RevisionsSelectionChanged; Revisions.Enabled = true; Revisions.Focus(); Revisions.SelectionChanged += RevisionsSelectionChanged; Revisions.ResumeLayout(); if (!_initialLoad) return; _initialLoad = false; SelectionTimer.Enabled = false; SelectionTimer.Stop(); SelectionTimer.Enabled = true; SelectionTimer.Start(); } public struct DrawRefArgs { public Graphics Graphics; public Rectangle CellBounds; public bool IsRowSelected; public Font RefsFont; } private void RevisionsCellPainting(object sender, DataGridViewCellPaintingEventArgs e) { // If our loading state has changed since the last paint, update it. if (Loading != null) { if (Loading.Visible != _isLoading) { Loading.Visible = _isLoading; } } var columnIndex = e.ColumnIndex; int graphColIndex = GraphDataGridViewColumn.Index; int messageColIndex = MessageDataGridViewColumn.Index; int authorColIndex = AuthorDataGridViewColumn.Index; int dateColIndex = DateDataGridViewColumn.Index; int idColIndex = IdDataGridViewColumn.Index; int isMsgMultilineColIndex = IsMessageMultilineDataGridViewColumn.Index; // The graph column is handled by the DvcsGraph if (e.ColumnIndex == graphColIndex) { return; } if (e.RowIndex < 0 || (e.State & DataGridViewElementStates.Visible) == 0) return; if (Revisions.RowCount <= e.RowIndex) return; var revision = GetRevision(e.RowIndex); if (revision == null) return; var spi = SuperprojectCurrentCheckout.IsCompleted ? SuperprojectCurrentCheckout.Result : null; var superprojectRefs = new List<GitRef>(); if (spi != null && spi.Refs != null && spi.Refs.ContainsKey(revision.Guid)) { superprojectRefs.AddRange(spi.Refs[revision.Guid].Where(ShowRemoteRef)); } e.Handled = true; var drawRefArgs = new DrawRefArgs(); drawRefArgs.Graphics = e.Graphics; drawRefArgs.CellBounds = e.CellBounds; drawRefArgs.IsRowSelected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected); if (drawRefArgs.IsRowSelected /*&& !showRevisionCards*/) { e.Graphics.FillRectangle(_selectedItemBrush, e.CellBounds); } else if (ShouldHighlightRevisionByAuthor(revision)) { e.Graphics.FillRectangle(_authoredRevisionsBrush, e.CellBounds); } else { e.Graphics.FillRectangle(Brushes.White, e.CellBounds); } Color foreColor; if (!AppSettings.RevisionGraphDrawNonRelativesTextGray || Revisions.RowIsRelative(e.RowIndex)) { foreColor = drawRefArgs.IsRowSelected && IsFilledBranchesLayout() ? SystemColors.HighlightText : e.CellStyle.ForeColor; } else { foreColor = drawRefArgs.IsRowSelected ? SystemColors.HighlightText : Color.Gray; } using (Brush foreBrush = new SolidBrush(foreColor)) { var rowFont = NormalFont; if (revision.Guid == CurrentCheckout /*&& !showRevisionCards*/) rowFont = HeadFont; else if (spi != null && spi.CurrentBranch == revision.Guid) rowFont = SuperprojectFont; if (columnIndex == messageColIndex) { int baseOffset = 0; if (IsCardLayout()) { baseOffset = 5; Rectangle cellRectangle = new Rectangle(e.CellBounds.Left + baseOffset, e.CellBounds.Top + 1, e.CellBounds.Width - (baseOffset * 2), e.CellBounds.Height - 4); if (!AppSettings.RevisionGraphDrawNonRelativesGray || Revisions.RowIsRelative(e.RowIndex)) { e.Graphics.FillRectangle( new LinearGradientBrush(cellRectangle, Color.FromArgb(255, 220, 220, 231), Color.FromArgb(255, 240, 240, 250), 90, false), cellRectangle); using (var pen = new Pen(Color.FromArgb(255, 200, 200, 200), 1)) { e.Graphics.DrawRectangle(pen, cellRectangle); } } else { e.Graphics.FillRectangle( new LinearGradientBrush(cellRectangle, Color.FromArgb(255, 240, 240, 240), Color.FromArgb(255, 250, 250, 250), 90, false), cellRectangle); } if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { using (var penSelectionBackColor = new Pen(Revisions.RowTemplate.DefaultCellStyle.SelectionBackColor, 1)) e.Graphics.DrawRectangle(penSelectionBackColor, cellRectangle); } } float offset = baseOffset; var gitRefs = revision.Refs; drawRefArgs.RefsFont = IsFilledBranchesLayout() ? rowFont : RefsFont; if (spi != null) { if (spi.Conflict_Base == revision.Guid) offset = DrawRef(drawRefArgs, offset, "Base", Color.OrangeRed, ArrowType.NotFilled); if (spi.Conflict_Local == revision.Guid) offset = DrawRef(drawRefArgs, offset, "Local", Color.OrangeRed, ArrowType.NotFilled); if (spi.Conflict_Remote == revision.Guid) offset = DrawRef(drawRefArgs, offset, "Remote", Color.OrangeRed, ArrowType.NotFilled); } if (gitRefs.Any()) { gitRefs.Sort((left, right) => { if (left.IsTag != right.IsTag) return right.IsTag.CompareTo(left.IsTag); if (left.IsRemote != right.IsRemote) return left.IsRemote.CompareTo(right.IsRemote); return left.Name.CompareTo(right.Name); }); foreach (var gitRef in gitRefs.Where(head => (!head.IsRemote || AppSettings.ShowRemoteBranches))) { if (gitRef.IsTag) { if (!AppSettings.ShowTags) { continue; } } Color headColor = GetHeadColor(gitRef); ArrowType arrowType = gitRef.Selected ? ArrowType.Filled : gitRef.SelectedHeadMergeSource ? ArrowType.NotFilled : ArrowType.None; var superprojectRef = superprojectRefs.FirstOrDefault(spGitRef => gitRef.CompleteName == spGitRef.CompleteName); if (superprojectRef != null) superprojectRefs.Remove(superprojectRef); string name = gitRef.Name; if ( gitRef.IsTag && gitRef.IsDereference // see note on using IsDereference in CommitInfo class. && AppSettings.ShowAnnotatedTagsMessages && AppSettings.ShowIndicatorForMultilineMessage ) { name = name + " " + MultilineMessageIndicator; } offset = DrawRef(drawRefArgs, offset, name, headColor, arrowType, superprojectRef != null, true); } } for (int i = 0; i < Math.Min(MaxSuperprojectRefs, superprojectRefs.Count); i++) { var gitRef = superprojectRefs[i]; Color headColor = GetHeadColor(gitRef); var gitRefName = i < (MaxSuperprojectRefs - 1) ? gitRef.Name : "…"; ArrowType arrowType = gitRef.Selected ? ArrowType.Filled : gitRef.SelectedHeadMergeSource ? ArrowType.NotFilled : ArrowType.None; offset = DrawRef(drawRefArgs, offset, gitRefName, headColor, arrowType, true, false); } if (IsCardLayout()) offset = baseOffset; var text = (string)e.FormattedValue; var bounds = AdjustCellBounds(e.CellBounds, offset); DrawColumnText(e.Graphics, text, rowFont, foreColor, bounds); if (IsCardLayout()) { int textHeight = (int)e.Graphics.MeasureString(text, rowFont).Height; int gravatarSize = _rowHeigth - textHeight - 12; int gravatarTop = e.CellBounds.Top + textHeight + 6; int gravatarLeft = e.CellBounds.Left + baseOffset + 2; Image gravatar = Gravatar.GravatarService.GetImageFromCache(revision.AuthorEmail + gravatarSize.ToString() + ".png", revision.AuthorEmail, AppSettings.AuthorImageCacheDays, gravatarSize, AppSettings.GravatarCachePath, FallBackService.MonsterId); if (gravatar == null && !string.IsNullOrEmpty(revision.AuthorEmail)) { ThreadPool.QueueUserWorkItem(o => Gravatar.GravatarService.LoadCachedImage(revision.AuthorEmail + gravatarSize.ToString() + ".png", revision.AuthorEmail, null, AppSettings.AuthorImageCacheDays, gravatarSize, AppSettings.GravatarCachePath, RefreshGravatar, FallBackService.MonsterId)); } if (gravatar != null) e.Graphics.DrawImage(gravatar, gravatarLeft + 1, gravatarTop + 1, gravatarSize, gravatarSize); e.Graphics.DrawRectangle(Pens.Black, gravatarLeft, gravatarTop, gravatarSize + 1, gravatarSize + 1); string authorText; string timeText; if (_rowHeigth >= 60) { authorText = revision.Author; timeText = TimeToString(AppSettings.ShowAuthorDate ? revision.AuthorDate : revision.CommitDate); } else { timeText = string.Concat(revision.Author, " (", TimeToString(AppSettings.ShowAuthorDate ? revision.AuthorDate : revision.CommitDate), ")"); authorText = string.Empty; } e.Graphics.DrawString(authorText, rowFont, foreBrush, new PointF(gravatarLeft + gravatarSize + 5, gravatarTop + 6)); e.Graphics.DrawString(timeText, rowFont, foreBrush, new PointF(gravatarLeft + gravatarSize + 5, e.CellBounds.Bottom - textHeight - 4)); } } else if (columnIndex == authorColIndex) { var text = (string)e.FormattedValue; e.Graphics.DrawString(text, rowFont, foreBrush, new PointF(e.CellBounds.Left, e.CellBounds.Top + 4)); } else if (columnIndex == dateColIndex) { var time = AppSettings.ShowAuthorDate ? revision.AuthorDate : revision.CommitDate; var text = TimeToString(time); e.Graphics.DrawString(text, rowFont, foreBrush, new PointF(e.CellBounds.Left, e.CellBounds.Top + 4)); } else if (columnIndex == idColIndex) { if (!revision.IsArtificial()) { var text = revision.Guid; e.Graphics.DrawString(text, new Font("Consolas", rowFont.SizeInPoints), foreBrush, new PointF(e.CellBounds.Left, e.CellBounds.Top + 4)); } } else if (columnIndex == BuildServerWatcher.BuildStatusImageColumnIndex) { BuildInfoDrawingLogic.BuildStatusImageColumnCellPainting(e, revision, foreBrush, rowFont); } else if (columnIndex == BuildServerWatcher.BuildStatusMessageColumnIndex) { BuildInfoDrawingLogic.BuildStatusMessageCellPainting(e, revision, foreBrush, rowFont); } else if (AppSettings.ShowIndicatorForMultilineMessage && columnIndex == isMsgMultilineColIndex) { var text = (string)e.FormattedValue; e.Graphics.DrawString(text, rowFont, foreBrush, new PointF(e.CellBounds.Left, e.CellBounds.Top + 4)); } } } private bool ShouldHighlightRevisionByAuthor(GitRevision revision) { return AppSettings.HighlightAuthoredRevisions && AuthorEmailEqualityComparer.Instance.Equals(revision.AuthorEmail, _revisionHighlighting.AuthorEmailToHighlight); } private float DrawRef(DrawRefArgs drawRefArgs, float offset, string name, Color headColor, ArrowType arrowType, bool dashedLine = false, bool fill = false) { var textColor = fill ? headColor : Lerp(headColor, Color.White, 0.5f); if (IsCardLayout()) { using (Brush textBrush = new SolidBrush(textColor)) { string headName = name; offset += drawRefArgs.Graphics.MeasureString(headName, drawRefArgs.RefsFont).Width + 6; var location = new PointF(drawRefArgs.CellBounds.Right - offset, drawRefArgs.CellBounds.Top + 4); var size = new SizeF(drawRefArgs.Graphics.MeasureString(headName, drawRefArgs.RefsFont).Width, drawRefArgs.Graphics.MeasureString(headName, drawRefArgs.RefsFont).Height); if (fill) drawRefArgs.Graphics.FillRectangle(SystemBrushes.Info, location.X - 1, location.Y - 1, size.Width + 3, size.Height + 2); drawRefArgs.Graphics.DrawRectangle(SystemPens.InfoText, location.X - 1, location.Y - 1, size.Width + 3, size.Height + 2); drawRefArgs.Graphics.DrawString(headName, drawRefArgs.RefsFont, textBrush, location); } } else { string headName = IsFilledBranchesLayout() ? name : string.Concat("[", name, "] "); var headBounds = AdjustCellBounds(drawRefArgs.CellBounds, offset); SizeF textSize = drawRefArgs.Graphics.MeasureString(headName, drawRefArgs.RefsFont); offset += textSize.Width; if (IsFilledBranchesLayout()) { offset += 9; float extraOffset = DrawHeadBackground(drawRefArgs.IsRowSelected, drawRefArgs.Graphics, headColor, headBounds.X, headBounds.Y, RoundToEven(textSize.Width + 3), RoundToEven(textSize.Height), 3, arrowType, dashedLine, fill); offset += extraOffset; headBounds.Offset((int)(extraOffset + 1), 0); } DrawColumnText(drawRefArgs.Graphics, headName, drawRefArgs.RefsFont, textColor, headBounds); } return offset; } private static readonly string MultilineMessageIndicator = "[...]"; private void RevisionsCellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { var columnIndex = e.ColumnIndex; if (e.RowIndex < 0) return; if (Revisions.RowCount <= e.RowIndex) return; var revision = GetRevision(e.RowIndex); if (revision == null) return; e.FormattingApplied = true; int graphColIndex = GraphDataGridViewColumn.Index; int messageColIndex = MessageDataGridViewColumn.Index; int authorColIndex = AuthorDataGridViewColumn.Index; int dateColIndex = DateDataGridViewColumn.Index; int isMsgMultilineColIndex = IsMessageMultilineDataGridViewColumn.Index; if (columnIndex == graphColIndex) { e.Value = revision.Guid; } else if (columnIndex == messageColIndex) { e.Value = revision.Subject; } else if (columnIndex == authorColIndex) { e.Value = revision.Author ?? ""; } else if (columnIndex == dateColIndex) { var time = AppSettings.ShowAuthorDate ? revision.AuthorDate : revision.CommitDate; if (time == DateTime.MinValue || time == DateTime.MaxValue) e.Value = ""; else e.Value = string.Format("{0} {1}", time.ToShortDateString(), time.ToLongTimeString()); } else if (columnIndex == BuildServerWatcher.BuildStatusImageColumnIndex) { BuildInfoDrawingLogic.BuildStatusImageColumnCellFormatting(e, Revisions, revision); } else if (columnIndex == BuildServerWatcher.BuildStatusMessageColumnIndex) { BuildInfoDrawingLogic.BuildStatusMessageCellFormatting(e, revision); } else if (AppSettings.ShowIndicatorForMultilineMessage && columnIndex == isMsgMultilineColIndex) { if (revision.Body == null && !revision.IsArtificial()) { ThreadPool.QueueUserWorkItem(o => LoadIsMultilineMessageInfo(revision, columnIndex, e.RowIndex, Revisions.RowCount)); } if (revision.Body != null) { e.Value = revision.Body.TrimEnd().Contains("\n") ? MultilineMessageIndicator : ""; } else { e.Value = ""; } } else { e.FormattingApplied = false; } } /// <summary> /// /// </summary> /// <param name="revision"></param> /// <param name="totalRowCount">check if grid has changed while thread is queued</param> /// <param name="colIndex"></param> /// <param name="rowIndex"></param> private void LoadIsMultilineMessageInfo(GitRevision revision, int colIndex, int rowIndex, int totalRowCount) { // code taken from CommitInfo.cs CommitData commitData = CommitData.CreateFromRevision(revision); string error = ""; if (revision.Body == null) { CommitData.UpdateCommitMessage(commitData, Module, revision.Guid, ref error); revision.Body = commitData.Body; } // now that Body is filled (not null anymore) the revision grid can be refreshed to display the new information this.InvokeAsync(() => { if (Revisions == null || Revisions.RowCount == 0 || Revisions.RowCount <= rowIndex || Revisions.RowCount != totalRowCount) { return; } Revisions.InvalidateCell(colIndex, rowIndex); }); } private void DrawColumnText(Graphics gc, string text, Font font, Color color, Rectangle bounds) { TextRenderer.DrawText(gc, text, font, bounds, color, TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix); } private static Rectangle AdjustCellBounds(Rectangle cellBounds, float offset) { return new Rectangle((int)(cellBounds.Left + offset), cellBounds.Top + 4, cellBounds.Width - (int)offset, cellBounds.Height); } private static Color GetHeadColor(GitRef gitRef) { if (gitRef.IsTag) return AppSettings.TagColor; if (gitRef.IsHead) return AppSettings.BranchColor; if (gitRef.IsRemote) return AppSettings.RemoteBranchColor; return AppSettings.OtherTagColor; } private float RoundToEven(float value) { int result = ((int)value / 2) * 2; return result < value ? result + 2 : result; } enum ArrowType { None, Filled, NotFilled } static readonly float[] dashPattern = new float[] { 4, 4 }; private float DrawHeadBackground(bool isSelected, Graphics graphics, Color color, float x, float y, float width, float height, float radius, ArrowType arrowType, bool dashedLine, bool fill) { float additionalOffset = arrowType != ArrowType.None ? GetArrowSize(height) : 0; width += additionalOffset; var oldMode = graphics.SmoothingMode; graphics.SmoothingMode = SmoothingMode.AntiAlias; try { // shade if (fill) using (var shadePath = CreateRoundRectPath(x + 1, y + 1, width, height, radius)) { var shadeBrush = isSelected ? Brushes.Black : Brushes.Gray; graphics.FillPath(shadeBrush, shadePath); } using (var forePath = CreateRoundRectPath(x, y, width, height, radius)) { Color fillColor = Lerp(color, Color.White, 0.92F); if (fill) using (var fillBrush = new LinearGradientBrush(new RectangleF(x, y, width, height), fillColor, Lerp(fillColor, Color.White, 0.9F), 90)) graphics.FillPath(fillBrush, forePath); else if (isSelected) graphics.FillPath(Brushes.White, forePath); // frame using (var pen = new Pen(Lerp(color, Color.White, 0.83F))) { if (dashedLine) pen.DashPattern = dashPattern; graphics.DrawPath(pen, forePath); } // arrow if the head is the current branch if (arrowType != ArrowType.None) DrawArrow(graphics, x, y, height, color, arrowType == ArrowType.Filled); } } finally { graphics.SmoothingMode = oldMode; } return additionalOffset; } private float GetArrowSize(float rowHeight) { return rowHeight - 6; } private void DrawArrow(Graphics graphics, float x, float y, float rowHeight, Color color, bool filled) { const float horShift = 4; const float verShift = 3; float height = rowHeight - verShift * 2; float width = height / 2; var points = new[] { new PointF(x + horShift, y + verShift), new PointF(x + horShift + width, y + verShift + height/2), new PointF(x + horShift, y + verShift + height), new PointF(x + horShift, y + verShift) }; if (filled) { using (var solidBrush = new SolidBrush(color)) graphics.FillPolygon(solidBrush, points); } else { using (var pen = new Pen(color)) graphics.DrawPolygon(pen, points); } } private static GraphicsPath CreateRoundRectPath(float x, float y, float width, float height, float radius) { var path = new GraphicsPath(); path.AddLine(x + radius, y, x + width - (radius * 2), y); path.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); path.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); path.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); path.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); path.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); path.AddLine(x, y + height - (radius * 2), x, y + radius); path.AddArc(x, y, radius * 2, radius * 2, 180, 90); path.CloseFigure(); return path; } private static float Lerp(float start, float end, float amount) { float difference = end - start; float adjusted = difference * amount; return start + adjusted; } private static Color Lerp(Color colour, Color to, float amount) { // start colours as lerp-able floats float sr = colour.R, sg = colour.G, sb = colour.B; // end colours as lerp-able floats float er = to.R, eg = to.G, eb = to.B; // lerp the colours to get the difference byte r = (byte)Lerp(sr, er, amount), g = (byte)Lerp(sg, eg, amount), b = (byte)Lerp(sb, eb, amount); // return the new colour return Color.FromArgb(r, g, b); } private void RefreshGravatar(Image image) { this.InvokeAsync(Revisions.Refresh); } private void RevisionsDoubleClick(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; if (DoubleClickRevision != null) { var selectedRevisions = GetSelectedRevisions(); DoubleClickRevision(this, new DoubleClickRevisionEventArgs(selectedRevisions.FirstOrDefault())); } if (!DoubleClickDoesNotOpenCommitInfo) { ViewSelectedRevisions(); } } public void ViewSelectedRevisions() { var selectedRevisions = GetSelectedRevisions(); if (selectedRevisions.Any(rev => !GitRevision.IsArtificial(rev.Guid))) { using (var form = new FormCommitDiff(UICommands, selectedRevisions[0].Guid)) { form.ShowDialog(this); } } else if (!selectedRevisions.Any()) { UICommands.StartCompareRevisionsDialog(this); } } private void SelectionTimerTick(object sender, EventArgs e) { SelectionTimer.Enabled = false; SelectionTimer.Stop(); if (SelectionChanged != null) SelectionChanged(this, e); } private void CreateTagToolStripMenuItemClick(object sender, EventArgs e) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; using (var frm = new FormCreateTag(UICommands, GetRevision(LastRowIndex))) { if (frm.ShowDialog(this) == DialogResult.OK) { RefreshRevisions(); } } } private void ResetCurrentBranchToHereToolStripMenuItemClick(object sender, EventArgs e) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; var frm = new FormResetCurrentBranch(UICommands, GetRevision(LastRowIndex)); frm.ShowDialog(this); } private void CreateNewBranchToolStripMenuItemClick(object sender, EventArgs e) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; UICommands.DoActionOnRepo(() => { var frm = new FormCreateBranch(UICommands, GetRevision(LastRowIndex)); return frm.ShowDialog(this) == DialogResult.OK; }); } private void RevisionsMouseClick(object sender, MouseEventArgs e) { var pt = Revisions.PointToClient(Cursor.Position); var hti = Revisions.HitTest(pt.X, pt.Y); LastRowIndex = hti.RowIndex; } private void RevisionsCellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button != MouseButtons.Right) return; var pt = Revisions.PointToClient(Cursor.Position); var hti = Revisions.HitTest(pt.X, pt.Y); if (LastRowIndex == hti.RowIndex) return; LastRowIndex = hti.RowIndex; Revisions.ClearSelection(); if (LastRowIndex >= 0 && Revisions.Rows.Count > LastRowIndex) Revisions.Rows[LastRowIndex].Selected = true; } private void CommitClick(object sender, EventArgs e) { UICommands.StartCommitDialog(this); } private void GitIgnoreClick(object sender, EventArgs e) { UICommands.StartEditGitIgnoreDialog(this); } internal void InvalidateRevisions() { Revisions.Invalidate(); } // internal because used by RevisonGridMenuCommands internal void ShowCurrentBranchOnly_ToolStripMenuItemClick(object sender, EventArgs e) { if (_showCurrentBranchOnlyToolStripMenuItemChecked) return; AppSettings.BranchFilterEnabled = true; AppSettings.ShowCurrentBranchOnly = true; SetShowBranches(); ForceRefreshRevisions(); } // internal because used by RevisonGridMenuCommands internal void ShowAllBranches_ToolStripMenuItemClick(object sender, EventArgs e) { if (_showAllBranchesToolStripMenuItemChecked) return; AppSettings.BranchFilterEnabled = false; SetShowBranches(); ForceRefreshRevisions(); } // internal because used by RevisonGridMenuCommands internal void ShowFilteredBranches_ToolStripMenuItemClick(object sender, EventArgs e) { if (_showFilteredBranchesToolStripMenuItemChecked) return; AppSettings.BranchFilterEnabled = true; AppSettings.ShowCurrentBranchOnly = false; SetShowBranches(); ForceRefreshRevisions(); } internal bool ShowCurrentBranchOnly_ToolStripMenuItemChecked { get { return _showCurrentBranchOnlyToolStripMenuItemChecked; } } internal bool ShowAllBranches_ToolStripMenuItemChecked { get { return _showAllBranchesToolStripMenuItemChecked; } } internal bool ShowFilteredBranches_ToolStripMenuItemChecked { get { return _showFilteredBranchesToolStripMenuItemChecked; } } private void SetShowBranches() { _showAllBranchesToolStripMenuItemChecked = !AppSettings.BranchFilterEnabled; _showCurrentBranchOnlyToolStripMenuItemChecked = AppSettings.BranchFilterEnabled && AppSettings.ShowCurrentBranchOnly; _showFilteredBranchesToolStripMenuItemChecked = AppSettings.BranchFilterEnabled && !AppSettings.ShowCurrentBranchOnly; BranchFilter = _revisionFilter.GetBranchFilter(); if (!AppSettings.BranchFilterEnabled) _refsOptions = RefsFiltringOptions.All | RefsFiltringOptions.Boundary; else if (AppSettings.ShowCurrentBranchOnly) _refsOptions = 0; else _refsOptions = BranchFilter.Length > 0 ? 0 : RefsFiltringOptions.All | RefsFiltringOptions.Boundary; _revisionGridMenuCommands.TriggerMenuChanged(); // apply checkboxes changes also to FormBrowse main menu } private void RevertCommitToolStripMenuItemClick(object sender, EventArgs e) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; UICommands.StartRevertCommitDialog(this, GetRevision(LastRowIndex)); } internal void FilterToolStripMenuItemClick(object sender, EventArgs e) { _revisionFilter.ShowDialog(this); ForceRefreshRevisions(); } private void ApplyFilterFromRevisionFilterDialog() { BranchFilter = _revisionFilter.GetBranchFilter(); SetShowBranches(); } private void ContextMenuOpening(object sender, CancelEventArgs e) { if (Revisions.RowCount < LastRowIndex || LastRowIndex < 0 || Revisions.RowCount == 0) return; var inTheMiddleOfBisect = Module.InTheMiddleOfBisect(); markRevisionAsBadToolStripMenuItem.Visible = inTheMiddleOfBisect; markRevisionAsGoodToolStripMenuItem.Visible = inTheMiddleOfBisect; bisectSkipRevisionToolStripMenuItem.Visible = inTheMiddleOfBisect; stopBisectToolStripMenuItem.Visible = inTheMiddleOfBisect; bisectSeparator.Visible = inTheMiddleOfBisect; compareWithCurrentBranchToolStripMenuItem.Visible = Module.GetSelectedBranch().IsNotNullOrWhitespace(); var revision = GetRevision(LastRowIndex); var deleteTagDropDown = new ContextMenuStrip(); var deleteBranchDropDown = new ContextMenuStrip(); var checkoutBranchDropDown = new ContextMenuStrip(); var mergeBranchDropDown = new ContextMenuStrip(); var rebaseDropDown = new ContextMenuStrip(); var renameDropDown = new ContextMenuStrip(); var gitRefListsForRevision = new GitRefListsForRevision(revision); foreach (var head in gitRefListsForRevision.AllTags) { ToolStripItem toolStripItem = new ToolStripMenuItem(head.Name); toolStripItem.Tag = head.Name; toolStripItem.Click += ToolStripItemClickDeleteTag; deleteTagDropDown.Items.Add(toolStripItem); toolStripItem = new ToolStripMenuItem(head.Name); toolStripItem.Tag = head.CompleteName; toolStripItem.Click += ToolStripItemClickMergeBranch; mergeBranchDropDown.Items.Add(toolStripItem); } //For now there is no action that could be done on currentBranch bool bareRepository = Module.IsBareRepository(); string currentBranch = Module.GetSelectedBranch(); var allBranches = gitRefListsForRevision.AllBranches; var branchesWithNoIdenticalRemotes = gitRefListsForRevision.BranchesWithNoIdenticalRemotes; bool currentBranchPointsToRevision = false; foreach (var head in branchesWithNoIdenticalRemotes) { if (head.Name.Equals(currentBranch)) currentBranchPointsToRevision = true; else { ToolStripItem toolStripItem = new ToolStripMenuItem(head.Name); toolStripItem.Tag = head.CompleteName; toolStripItem.Click += ToolStripItemClickMergeBranch; mergeBranchDropDown.Items.Add(toolStripItem); toolStripItem = new ToolStripMenuItem(head.Name); toolStripItem.Tag = head.CompleteName; toolStripItem.Click += ToolStripItemClickRebaseBranch; rebaseDropDown.Items.Add(toolStripItem); } } //if there is no branch to rebase on, then allow user to rebase on selected commit if (rebaseDropDown.Items.Count == 0 && !currentBranchPointsToRevision) { ToolStripItem toolStripItem = new ToolStripMenuItem(revision.Guid); toolStripItem.Tag = revision.Guid; toolStripItem.Click += ToolStripItemClickRebaseBranch; rebaseDropDown.Items.Add(toolStripItem); } //if there is no branch to merge, then let user to merge selected commit into current branch if (mergeBranchDropDown.Items.Count == 0 && !currentBranchPointsToRevision) { ToolStripItem toolStripItem = new ToolStripMenuItem(revision.Guid); toolStripItem.Tag = revision.Guid; toolStripItem.Click += ToolStripItemClickMergeBranch; mergeBranchDropDown.Items.Add(toolStripItem); } // clipboard branch and tag menu handling { branchNameCopyToolStripMenuItem.Tag = "caption"; tagNameCopyToolStripMenuItem.Tag = "caption"; MenuUtil.SetAsCaptionMenuItem(branchNameCopyToolStripMenuItem, mainContextMenu); MenuUtil.SetAsCaptionMenuItem(tagNameCopyToolStripMenuItem, mainContextMenu); var branchNames = gitRefListsForRevision.GetAllBranchNames(); CopyToClipboardMenuHelper.SetCopyToClipboardMenuItems( copyToClipboardToolStripMenuItem, branchNameCopyToolStripMenuItem, branchNames, "branchNameItem"); var tagNames = gitRefListsForRevision.GetAllTagNames(); CopyToClipboardMenuHelper.SetCopyToClipboardMenuItems( copyToClipboardToolStripMenuItem, tagNameCopyToolStripMenuItem, tagNames, "tagNameItem"); toolStripSeparator6.Visible = branchNames.Any() || tagNames.Any(); } foreach (var head in allBranches) { ToolStripItem toolStripItem = new ToolStripMenuItem(head.Name); //skip remote branches - they can not be deleted this way if (!head.IsRemote) { if (!head.Name.Equals(currentBranch)) { toolStripItem = new ToolStripMenuItem(head.Name); toolStripItem.Tag = head.Name; toolStripItem.Click += ToolStripItemClickDeleteBranch; deleteBranchDropDown.Items.Add(toolStripItem); //Add to delete branch } toolStripItem = new ToolStripMenuItem(head.Name); toolStripItem.Tag = head.Name; toolStripItem.Click += ToolStripItemClickRenameBranch; renameDropDown.Items.Add(toolStripItem); //Add to rename branch } if (!head.Name.Equals(currentBranch)) { toolStripItem = new ToolStripMenuItem(head.Name); if (head.IsRemote) toolStripItem.Click += ToolStripItemClickCheckoutRemoteBranch; else toolStripItem.Click += ToolStripItemClickCheckoutBranch; checkoutBranchDropDown.Items.Add(toolStripItem); } } deleteTagToolStripMenuItem.DropDown = deleteTagDropDown; deleteTagToolStripMenuItem.Enabled = deleteTagDropDown.Items.Count > 0; deleteBranchToolStripMenuItem.DropDown = deleteBranchDropDown; deleteBranchToolStripMenuItem.Enabled = deleteBranchDropDown.Items.Count > 0; checkoutBranchToolStripMenuItem.DropDown = checkoutBranchDropDown; checkoutBranchToolStripMenuItem.Enabled = !bareRepository && checkoutBranchDropDown.Items.Count > 0; mergeBranchToolStripMenuItem.DropDown = mergeBranchDropDown; mergeBranchToolStripMenuItem.Enabled = !bareRepository && mergeBranchDropDown.Items.Count > 0; rebaseOnToolStripMenuItem.DropDown = rebaseDropDown; rebaseOnToolStripMenuItem.Enabled = !bareRepository && rebaseDropDown.Items.Count > 0; renameBranchToolStripMenuItem.DropDown = renameDropDown; renameBranchToolStripMenuItem.Enabled = renameDropDown.Items.Count > 0; checkoutRevisionToolStripMenuItem.Enabled = !bareRepository; revertCommitToolStripMenuItem.Enabled = !bareRepository; cherryPickCommitToolStripMenuItem.Enabled = !bareRepository; manipulateCommitToolStripMenuItem.Enabled = !bareRepository; toolStripSeparator6.Enabled = branchNameCopyToolStripMenuItem.Enabled || tagNameCopyToolStripMenuItem.Enabled; RefreshOwnScripts(); } private void ToolStripItemClickDeleteTag(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if (toolStripItem == null) return; UICommands.StartDeleteTagDialog(this, toolStripItem.Tag as string); } private void ToolStripItemClickDeleteBranch(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if (toolStripItem == null) return; UICommands.StartDeleteBranchDialog(this, toolStripItem.Tag as string); } private void ToolStripItemClickCheckoutBranch(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if (toolStripItem == null) return; string branch = toolStripItem.Text; UICommands.StartCheckoutBranch(this, branch, false); } private void ToolStripItemClickCheckoutRemoteBranch(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if (toolStripItem == null) return; UICommands.StartCheckoutRemoteBranch(this, toolStripItem.Text); } private void ToolStripItemClickMergeBranch(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if (toolStripItem == null) return; UICommands.StartMergeBranchDialog(this, toolStripItem.Tag as string); } private void ToolStripItemClickRebaseBranch(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if (toolStripItem == null) return; UICommands.StartRebaseDialog(this, toolStripItem.Tag as string); } private void ToolStripItemClickRenameBranch(object sender, EventArgs e) { var toolStripItem = sender as ToolStripItem; if (toolStripItem == null) return; UICommands.StartRenameDialog(this, toolStripItem.Tag as string); } private void CheckoutRevisionToolStripMenuItemClick(object sender, EventArgs e) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; string revision = GetRevision(LastRowIndex).Guid; UICommands.StartCheckoutRevisionDialog(this, revision); } private void ArchiveRevisionToolStripMenuItemClick(object sender, EventArgs e) { var selectedRevisions = GetSelectedRevisions(); if (selectedRevisions.Count > 2) { MessageBox.Show(this, "Select only one or two revisions. Abort.", "Archive revision"); return; } GitRevision mainRevision = selectedRevisions.First(); GitRevision diffRevision = null; if (selectedRevisions.Count == 2) diffRevision = selectedRevisions.Last(); UICommands.StartArchiveDialog(this, mainRevision, diffRevision); } internal void ShowAuthorDate_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowAuthorDate = !AppSettings.ShowAuthorDate; ForceRefreshRevisions(); } internal void OrderRevisionsByDate_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.OrderRevisionByDate = !AppSettings.OrderRevisionByDate; ForceRefreshRevisions(); } internal void ShowRemoteBranches_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowRemoteBranches = !AppSettings.ShowRemoteBranches; InvalidateRevisions(); } internal void ShowSuperprojectTags_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowSuperprojectTags = !AppSettings.ShowSuperprojectTags; ForceRefreshRevisions(); } internal void ShowSuperprojectBranches_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowSuperprojectBranches = !AppSettings.ShowSuperprojectBranches; ForceRefreshRevisions(); } internal void ShowSuperprojectRemoteBranches_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowSuperprojectRemoteBranches = !AppSettings.ShowSuperprojectRemoteBranches; ForceRefreshRevisions(); } private void CherryPickCommitToolStripMenuItemClick(object sender, EventArgs e) { var revisions = GetSelectedRevisions(SortDirection.Descending); UICommands.StartCherryPickDialog(this, revisions); } private void FixupCommitToolStripMenuItemClick(object sender, EventArgs e) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; UICommands.StartFixupCommitDialog(this, GetRevision(LastRowIndex)); } private void SquashCommitToolStripMenuItemClick(object sender, EventArgs e) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; UICommands.StartSquashCommitDialog(this, GetRevision(LastRowIndex)); } internal void ShowRelativeDate_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.RelativeDate = !AppSettings.RelativeDate; ForceRefreshRevisions(); } private string TimeToString(DateTime time) { if (time == DateTime.MinValue || time == DateTime.MaxValue) return ""; if (!AppSettings.RelativeDate) return string.Format("{0} {1}", time.ToShortDateString(), time.ToLongTimeString()); return LocalizationHelpers.GetRelativeDateString(DateTime.Now, time, false); } private bool ShowUncommitedChanges() { return ShowUncommitedChangesIfPossible && AppSettings.RevisionGraphShowWorkingDirChanges; } private string[] _currentCheckoutParents; private void UpdateGraph(GitRevision rev) { if (rev == null) { // Prune the graph and make sure the row count matches reality Revisions.Prune(); return; } if (_filtredCurrentCheckout == null) { if (rev.Guid == CurrentCheckout) { _filtredCurrentCheckout = CurrentCheckout; } else { if (_currentCheckoutParents == null) { _currentCheckoutParents = GetAllParents(CurrentCheckout); } _filtredCurrentCheckout = _currentCheckoutParents.FirstOrDefault(parent => parent == rev.Guid); } } string filtredCurrentCheckout = _filtredCurrentCheckout; if (filtredCurrentCheckout == rev.Guid && ShowUncommitedChanges()) { CheckUncommitedChanged( filtredCurrentCheckout ); } var dataType = DvcsGraph.DataType.Normal; if (rev.Guid == filtredCurrentCheckout) dataType = DvcsGraph.DataType.Active; else if (rev.Refs.Any()) dataType = DvcsGraph.DataType.Special; Revisions.Add(rev.Guid, rev.ParentGuids, dataType, rev); } private void CheckUncommitedChanged(string filtredCurrentCheckout) { if (UnstagedChanges.Result) { //Add working directory as virtual commit var workingDir = new GitRevision(Module, GitRevision.UnstagedGuid) { Subject = Strings.GetCurrentUnstagedChanges(), ParentGuids = StagedChanges.Result ? new[] { GitRevision.IndexGuid } : new[] { filtredCurrentCheckout } }; Revisions.Add(workingDir.Guid, workingDir.ParentGuids, DvcsGraph.DataType.Normal, workingDir); } if (StagedChanges.Result) { //Add index as virtual commit var index = new GitRevision(Module, GitRevision.IndexGuid) { Subject = Strings.GetCurrentIndex(), ParentGuids = new[] { filtredCurrentCheckout } }; Revisions.Add(index.Guid, index.ParentGuids, DvcsGraph.DataType.Normal, index); } } internal void DrawNonrelativesGray_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.RevisionGraphDrawNonRelativesGray = !AppSettings.RevisionGraphDrawNonRelativesGray; _revisionGridMenuCommands.TriggerMenuChanged(); Revisions.Refresh(); } private void MessageToolStripMenuItemClick(object sender, EventArgs e) { Clipboard.SetText(GetRevision(LastRowIndex).Subject); } private void AuthorToolStripMenuItemClick(object sender, EventArgs e) { Clipboard.SetText(GetRevision(LastRowIndex).Author); } private void DateToolStripMenuItemClick(object sender, EventArgs e) { Clipboard.SetText(GetRevision(LastRowIndex).CommitDate.ToString()); } private void HashToolStripMenuItemClick(object sender, EventArgs e) { Clipboard.SetText(GetRevision(LastRowIndex).Guid); } private void MarkRevisionAsBadToolStripMenuItemClick(object sender, EventArgs e) { ContinueBisect(GitBisectOption.Bad); } private void MarkRevisionAsGoodToolStripMenuItemClick(object sender, EventArgs e) { ContinueBisect(GitBisectOption.Good); } private void BisectSkipRevisionToolStripMenuItemClick(object sender, EventArgs e) { ContinueBisect(GitBisectOption.Skip); } private void ContinueBisect(GitBisectOption bisectOption) { if (Revisions.RowCount <= LastRowIndex || LastRowIndex < 0) return; FormProcess.ShowDialog(this, Module, GitCommandHelpers.ContinueBisectCmd(bisectOption, GetRevision(LastRowIndex).Guid), false); RefreshRevisions(); } private void StopBisectToolStripMenuItemClick(object sender, EventArgs e) { FormProcess.ShowDialog(this, Module, GitCommandHelpers.StopBisectCmd()); RefreshRevisions(); } private void RefreshOwnScripts() { RemoveOwnScripts(); AddOwnScripts(); } private void AddOwnScripts() { IList<ScriptInfo> scripts = ScriptManager.GetScripts(); if (scripts == null) return; int lastIndex = mainContextMenu.Items.Count; foreach (ScriptInfo scriptInfo in scripts) { if (scriptInfo.Enabled) { ToolStripItem item = new ToolStripMenuItem(scriptInfo.Name); item.Name = item.Text + "_ownScript"; item.Click += RunScript; if (scriptInfo.AddToRevisionGridContextMenu) mainContextMenu.Items.Add(item); else runScriptToolStripMenuItem.DropDown.Items.Add(item); } } if (lastIndex != mainContextMenu.Items.Count) mainContextMenu.Items.Insert(lastIndex, new ToolStripSeparator()); bool showScriptsMenu = runScriptToolStripMenuItem.DropDown.Items.Count > 0; runScriptToolStripMenuItem.Visible = showScriptsMenu; } private void RemoveOwnScripts() { runScriptToolStripMenuItem.DropDown.Items.Clear(); List<ToolStripItem> list = new List<ToolStripItem>(); foreach (ToolStripItem item in mainContextMenu.Items) list.Add(item); foreach (ToolStripItem item in list) if (item.Name.Contains("_ownScript")) mainContextMenu.Items.RemoveByKey(item.Name); if (mainContextMenu.Items[mainContextMenu.Items.Count - 1] is ToolStripSeparator) mainContextMenu.Items.RemoveAt(mainContextMenu.Items.Count - 1); } private bool _settingsLoaded; private void RunScript(object sender, EventArgs e) { if (_settingsLoaded == false) { new FormSettings(UICommands).LoadSettings(); _settingsLoaded = true; } if (ScriptRunner.RunScript(this, Module, sender.ToString(), this)) RefreshRevisions(); } #region Drag/drop patch files on revision grid void Revisions_DragDrop(object sender, DragEventArgs e) { var fileNameArray = e.Data.GetData(DataFormats.FileDrop) as Array; if (fileNameArray != null) { if (fileNameArray.Length > 10) { //Some users need to be protected against themselves! MessageBox.Show(this, _droppingFilesBlocked.Text); return; } foreach (object fileNameObject in fileNameArray) { var fileName = fileNameObject as string; if (!string.IsNullOrEmpty(fileName) && fileName.EndsWith(".patch", StringComparison.InvariantCultureIgnoreCase)) { //Start apply patch dialog for each dropped patch file... UICommands.StartApplyPatchDialog(this, fileName); } } } } static void Revisions_DragEnter(object sender, DragEventArgs e) { var fileNameArray = e.Data.GetData(DataFormats.FileDrop) as Array; if (fileNameArray != null) { foreach (object fileNameObject in fileNameArray) { var fileName = fileNameObject as string; if (!string.IsNullOrEmpty(fileName) && fileName.EndsWith(".patch", StringComparison.InvariantCultureIgnoreCase)) { //Allow drop (copy, not move) patch files e.Effect = DragDropEffects.Copy; } else { //When a non-patch file is dragged, do not allow it e.Effect = DragDropEffects.None; return; } } } } #endregion internal void ShowGitNotes_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowGitNotes = !AppSettings.ShowGitNotes; ForceRefreshRevisions(); } internal void ShowMergeCommits_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowMergeCommits = !showMergeCommitsToolStripMenuItem.Checked; showMergeCommitsToolStripMenuItem.Checked = AppSettings.ShowMergeCommits; // hide revision graph when hiding merge commits, reasons: // 1, revison graph is no longer relevant, as we are not sohwing all commits // 2, performance hit when both revision graph and no merge commits are enabled if (IsGraphLayout() && !AppSettings.ShowMergeCommits) { ToggleRevisionGraph(); SetRevisionsLayout(); } ForceRefreshRevisions(); } internal void ShowFirstParent_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowFirstParent = !AppSettings.ShowFirstParent; var handler = ShowFirstParentsToggled; if (handler != null) handler(this, e); ForceRefreshRevisions(); } public void OnModuleChanged(object sender, GitModuleEventArgs e) { var handler = GitModuleChanged; if (handler != null) handler(this, e); } private void InitRepository_Click(object sender, EventArgs e) { UICommands.StartInitializeDialog(this, Module.WorkingDir, OnModuleChanged); } private void CloneRepository_Click(object sender, EventArgs e) { if (UICommands.StartCloneDialog(this, null, OnModuleChanged)) ForceRefreshRevisions(); } internal void ShowRevisionGraph_ToolStripMenuItemClick(object sender, EventArgs e) { ToggleRevisionGraph(); SetRevisionsLayout(); _revisionGridMenuCommands.TriggerMenuChanged(); // must show MergeCommits when showing revision graph if (!AppSettings.ShowMergeCommits && IsGraphLayout()) { AppSettings.ShowMergeCommits = true; showMergeCommitsToolStripMenuItem.Checked = true; ForceRefreshRevisions(); } else Refresh(); } private void ToggleRevisionGraph() { if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.Small) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.SmallWithGraph; else if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.Card) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.CardWithGraph; else if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.LargeCard) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.LargeCardWithGraph; else if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.SmallWithGraph) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.Small; else if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.CardWithGraph) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.Card; else if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.LargeCardWithGraph) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.LargeCard; else if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.FilledBranchesSmall) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.FilledBranchesSmallWithGraph; else if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.FilledBranchesSmallWithGraph) AppSettings.RevisionGraphLayout = (int)RevisionGridLayout.FilledBranchesSmall; } internal void ShowTags_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowTags = !AppSettings.ShowTags; _revisionGridMenuCommands.TriggerMenuChanged(); Refresh(); } internal void ShowIds_ToolStripMenuItemClick(object sender, EventArgs e) { AppSettings.ShowIds = !AppSettings.ShowIds; Revisions.IdColumn.Visible = AppSettings.ShowIds; _revisionGridMenuCommands.TriggerMenuChanged(); Refresh(); } public void ToggleRevisionCardLayout() { var layouts = new List<RevisionGridLayout>((RevisionGridLayout[])Enum.GetValues(typeof(RevisionGridLayout))); layouts.Sort(); var maxLayout = (int)layouts[layouts.Count - 1]; int nextLayout = AppSettings.RevisionGraphLayout + 1; if (nextLayout > maxLayout) nextLayout = 1; SetRevisionsLayout((RevisionGridLayout)nextLayout); } public void SetRevisionsLayout(RevisionGridLayout revisionGridLayout) { AppSettings.RevisionGraphLayout = (int)revisionGridLayout; SetRevisionsLayout(); } private void SetRevisionsLayout() { _layout = Enum.IsDefined(typeof(RevisionGridLayout), AppSettings.RevisionGraphLayout) ? (RevisionGridLayout)AppSettings.RevisionGraphLayout : RevisionGridLayout.SmallWithGraph; IsCardLayout(); NormalFont = AppSettings.Font;// new Font(Settings.Font.Name, Settings.Font.Size + 2); // SystemFonts.DefaultFont.FontFamily, SystemFonts.DefaultFont.Size + 2); SetAuthoredRevisionsBrush(); if (IsCardLayout()) { if (AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.Card || AppSettings.RevisionGraphLayout == (int)RevisionGridLayout.CardWithGraph) { _rowHeigth = 45; } else { _rowHeigth = 70; } if (_filledItemBrush == null) { _filledItemBrush = new LinearGradientBrush(new Rectangle(0, 0, _rowHeigth, _rowHeigth), Revisions.RowTemplate.DefaultCellStyle.SelectionBackColor, Color.LightBlue, 90, false); } _selectedItemBrush = _filledItemBrush; Revisions.ShowAuthor(!IsCardLayout()); Revisions.SetDimensions(NodeDimension, LaneWidth, LaneLineWidth, _rowHeigth, _selectedItemBrush); } else { if (IsFilledBranchesLayout()) { using (var graphics = Graphics.FromHwnd(Handle)) { _rowHeigth = (int)graphics.MeasureString("By", NormalFont).Height + 9; } _selectedItemBrush = SystemBrushes.Highlight; } else { _rowHeigth = 25; if (_filledItemBrush == null) { _filledItemBrush = new LinearGradientBrush(new Rectangle(0, 0, _rowHeigth, _rowHeigth), Revisions.RowTemplate.DefaultCellStyle.SelectionBackColor, Color.LightBlue, 90, false); } _selectedItemBrush = _filledItemBrush; } Revisions.ShowAuthor(!IsCardLayout()); Revisions.SetDimensions(NodeDimension, LaneWidth, LaneLineWidth, _rowHeigth, _selectedItemBrush); } //Hide graph column when there it is disabled OR when a filter is active //allowing for special case when history of a single file is being displayed if (!IsGraphLayout() || (ShouldHideGraph(false) && !AllowGraphWithFilter)) { Revisions.HideRevisionGraph(); } else { Revisions.ShowRevisionGraph(); } } private void SetAuthoredRevisionsBrush() { if (_authoredRevisionsBrush != null && _authoredRevisionsBrush.Color != AppSettings.AuthoredRevisionsColor) { _authoredRevisionsBrush.Dispose(); _authoredRevisionsBrush = null; } if (_authoredRevisionsBrush == null) { _authoredRevisionsBrush = new SolidBrush(AppSettings.AuthoredRevisionsColor); } } private bool IsFilledBranchesLayout() { return _layout == RevisionGridLayout.FilledBranchesSmall || _layout == RevisionGridLayout.FilledBranchesSmallWithGraph; } private bool IsCardLayout() { return _layout == RevisionGridLayout.Card || _layout == RevisionGridLayout.CardWithGraph || _layout == RevisionGridLayout.LargeCard || _layout == RevisionGridLayout.LargeCardWithGraph; } internal bool IsGraphLayout() { return _layout == RevisionGridLayout.SmallWithGraph || _layout == RevisionGridLayout.CardWithGraph || _layout == RevisionGridLayout.LargeCardWithGraph || _layout == RevisionGridLayout.FilledBranchesSmallWithGraph; } #region Hotkey commands public const string HotkeySettingsName = "RevisionGrid"; internal enum Commands { ToggleRevisionGraph, RevisionFilter, ToggleAuthorDateCommitDate, ToggleOrderRevisionsByDate, ToggleShowRelativeDate, ToggleDrawNonRelativesGray, ToggleShowGitNotes, ToggleRevisionCardLayout, ToggleShowMergeCommits, ShowAllBranches, ShowCurrentBranchOnly, ShowFilteredBranches, ShowRemoteBranches, ShowFirstParent, GoToParent, GoToChild, ToggleHighlightSelectedBranch, NextQuickSearch, PrevQuickSearch, SelectCurrentRevision, GoToCommit, NavigateBackward, NavigateForward, SelectAsBaseToCompare, CompareToBase } protected override bool ExecuteCommand(int cmd) { Commands command = (Commands)cmd; switch (command) { case Commands.ToggleRevisionGraph: ShowRevisionGraph_ToolStripMenuItemClick(null, null); break; case Commands.RevisionFilter: FilterToolStripMenuItemClick(null, null); break; case Commands.ToggleAuthorDateCommitDate: ShowAuthorDate_ToolStripMenuItemClick(null, null); break; case Commands.ToggleOrderRevisionsByDate: OrderRevisionsByDate_ToolStripMenuItemClick(null, null); break; case Commands.ToggleShowRelativeDate: ShowRelativeDate_ToolStripMenuItemClick(null, null); break; case Commands.ToggleDrawNonRelativesGray: DrawNonrelativesGray_ToolStripMenuItemClick(null, null); break; case Commands.ToggleShowGitNotes: ShowGitNotes_ToolStripMenuItemClick(null, null); break; case Commands.ToggleRevisionCardLayout: ToggleRevisionCardLayout(); break; case Commands.ToggleShowMergeCommits: ShowMergeCommits_ToolStripMenuItemClick(null, null); break; case Commands.ShowAllBranches: ShowAllBranches_ToolStripMenuItemClick(null, null); break; case Commands.ShowCurrentBranchOnly: ShowCurrentBranchOnly_ToolStripMenuItemClick(null, null); break; case Commands.ShowFilteredBranches: ShowFilteredBranches_ToolStripMenuItemClick(null, null); break; case Commands.ShowRemoteBranches: ShowRemoteBranches_ToolStripMenuItemClick(null, null); break; case Commands.ShowFirstParent: ShowFirstParent_ToolStripMenuItemClick(null, null); break; case Commands.SelectCurrentRevision: SetSelectedRevision(new GitRevision(Module, CurrentCheckout)); break; case Commands.GoToCommit: _revisionGridMenuCommands.GotoCommitExcecute(); break; case Commands.GoToParent: goToParentToolStripMenuItem_Click(null, null); break; case Commands.GoToChild: goToChildToolStripMenuItem_Click(null, null); break; case Commands.ToggleHighlightSelectedBranch: ToggleHighlightSelectedBranch(); break; case Commands.NextQuickSearch: NextQuickSearch(true); break; case Commands.PrevQuickSearch: NextQuickSearch(false); break; case Commands.NavigateBackward: NavigateBackward(); break; case Commands.NavigateForward: NavigateForward(); break; case Commands.SelectAsBaseToCompare: selectAsBaseToolStripMenuItem_Click(null, null); break; case Commands.CompareToBase: compareToBaseToolStripMenuItem_Click(null, null); break; default: { bool result = base.ExecuteCommand(cmd); RefreshRevisions(); return result; } } return true; } #endregion internal bool ExecuteCommand(Commands cmd) { return ExecuteCommand((int)cmd); } private void NextQuickSearch(bool down) { var curIndex = -1; if (Revisions.SelectedRows.Count > 0) curIndex = Revisions.SelectedRows[0].Index; RestartQuickSearchTimer(); bool reverse = !down; var nextIndex = 0; if (curIndex >= 0) nextIndex = reverse ? curIndex - 1 : curIndex + 1; _quickSearchString = _lastQuickSearchString; FindNextMatch(nextIndex, _quickSearchString, reverse); ShowQuickSearchString(); } private void ToggleHighlightSelectedBranch() { if (_revisionGraphCommand != null) { MessageBox.Show(_cannotHighlightSelectedBranch.Text); return; } HighlightSelectedBranch(); } public void HighlightSelectedBranch() { var revisions = GetSelectedRevisions(); if (revisions.Count > 0) { HighlightBranch(revisions[0].Guid); Refresh(); } } private void deleteBranchTagToolStripMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { if (item.DropDown != null && item.DropDown.Items.Count == 1) item.DropDown.Items[0].PerformClick(); } } private void goToParentToolStripMenuItem_Click(object sender, EventArgs e) { var r = GetRevision(LastRowIndex); if (r != null) { if (_parentChildNavigationHistory.HasPreviousParent) _parentChildNavigationHistory.NavigateToPreviousParent(r.Guid); else if (r.HasParent()) _parentChildNavigationHistory.NavigateToParent(r.Guid, r.ParentGuids[0]); } } private void goToChildToolStripMenuItem_Click(object sender, EventArgs e) { var r = GetRevision(LastRowIndex); if (r != null) { var children = GetRevisionChildren(r.Guid); if (_parentChildNavigationHistory.HasPreviousChild) _parentChildNavigationHistory.NavigateToPreviousChild(r.Guid); else if (children.Any()) _parentChildNavigationHistory.NavigateToChild(r.Guid, children[0]); } } private void copyToClipboardToolStripMenuItem_DropDownOpened(object sender, EventArgs e) { var r = GetRevision(LastRowIndex); if (r != null) { CopyToClipboardMenuHelper.AddOrUpdateTextPostfix(hashCopyToolStripMenuItem, CopyToClipboardMenuHelper.StrLimitWithElipses(r.Guid, 15)); CopyToClipboardMenuHelper.AddOrUpdateTextPostfix(messageCopyToolStripMenuItem, CopyToClipboardMenuHelper.StrLimitWithElipses(r.Subject, 30)); CopyToClipboardMenuHelper.AddOrUpdateTextPostfix(authorCopyToolStripMenuItem, r.Author); CopyToClipboardMenuHelper.AddOrUpdateTextPostfix(dateCopyToolStripMenuItem, r.CommitDate.ToString()); } } public void GoToRef(string refName, bool showNoRevisionMsg) { string revisionGuid = Module.RevParse(refName); if (!string.IsNullOrEmpty(revisionGuid)) { SetSelectedRevision(new GitRevision(Module, revisionGuid)); } else if (showNoRevisionMsg) { MessageBox.Show((ParentForm as IWin32Window) ?? this, _noRevisionFoundError.Text); } } /// <summary> /// duplicated from GitExtensionsForm /// </summary> /// <param name="commandCode"></param> /// <returns></returns> private Keys GetShortcutKeys(int commandCode) { var hotkey = GetHotkeyCommand(commandCode); return hotkey == null ? Keys.None : hotkey.KeyData; } internal Keys GetShortcutKeys(Commands cmd) { return GetShortcutKeys((int)cmd); } /// <summary> /// duplicated from GitExtensionsForm /// </summary> /// <param name="commandCode"></param> /// <returns></returns> private HotkeyCommand GetHotkeyCommand(int commandCode) { if (Hotkeys == null) return null; return Hotkeys.FirstOrDefault(h => h.CommandCode == commandCode); } internal RevisionGridMenuCommands MenuCommands { get { return _revisionGridMenuCommands; } } private void CompareToBranchToolStripMenuItem_Click(object sender, EventArgs e) { var headCommit = this.GetSelectedRevisions().First(); using (var form = new FormCompareToBranch(UICommands, headCommit.Guid)) { if (form.ShowDialog(this) == DialogResult.OK) { var baseCommit = Module.RevParse(form.BranchName); using (var diffForm = new FormDiff(UICommands, this, baseCommit, headCommit.Guid, form.BranchName, headCommit.Subject)) { diffForm.ShowDialog(this); } } } } private void CompareWithCurrentBranchToolStripMenuItem_Click(object sender, EventArgs e) { var baseCommit = this.GetSelectedRevisions().First(); var headBranch = Module.GetSelectedBranch(); var headBranchName = Module.RevParse(headBranch); using (var diffForm = new FormDiff(UICommands, this, baseCommit.Guid, headBranchName, baseCommit.Subject, headBranch)) { diffForm.ShowDialog(this); } } private void selectAsBaseToolStripMenuItem_Click(object sender, EventArgs e) { _baseCommitToCompare = GetSelectedRevisions().First(); compareToBaseToolStripMenuItem.Enabled = true; } private void compareToBaseToolStripMenuItem_Click(object sender, EventArgs e) { var headCommit = GetSelectedRevisions().First(); using (var diffForm = new FormDiff(UICommands, this, _baseCommitToCompare.Guid, headCommit.Guid, _baseCommitToCompare.Subject, headCommit.Subject)) { diffForm.ShowDialog(this); } } private void getHelpOnHowToUseTheseFeaturesToolStripMenuItem_Click(object sender, EventArgs e) { OpenManual(); } private void OpenManual() { string url = UserManual.UserManual.UrlFor("modify_history", "using-autosquash-rebase-feature"); OsShellUtil.OpenUrlInDefaultBrowser(url); } } }
hkouki/gitextensions
GitUI/UserControls/RevisionGrid.cs
C#
gpl-3.0
128,292
/* * Copyright (c) 2021 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.opal.web.gwt.app.client.fs.presenter; import java.util.List; import javax.annotation.Nullable; import org.obiba.opal.web.gwt.app.client.event.NotificationEvent; import org.obiba.opal.web.gwt.app.client.fs.FileDtos; import org.obiba.opal.web.gwt.app.client.fs.event.FileSelectionEvent; import org.obiba.opal.web.gwt.app.client.fs.event.FileSelectionRequestEvent; import org.obiba.opal.web.gwt.app.client.fs.event.FilesCheckedEvent; import org.obiba.opal.web.gwt.app.client.fs.event.FolderCreatedEvent; import org.obiba.opal.web.gwt.app.client.fs.service.FileService; import org.obiba.opal.web.gwt.app.client.i18n.TranslationMessages; import org.obiba.opal.web.gwt.app.client.i18n.Translations; import org.obiba.opal.web.gwt.app.client.presenter.ModalPresenterWidget; import org.obiba.opal.web.gwt.app.client.presenter.ModalProvider; import org.obiba.opal.web.gwt.app.client.presenter.SplitPaneWorkbenchPresenter; import org.obiba.opal.web.gwt.rest.client.RequestCredentials; import org.obiba.opal.web.gwt.rest.client.ResourceCallback; import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilderFactory; import org.obiba.opal.web.gwt.rest.client.ResponseCodeCallback; import org.obiba.opal.web.model.client.opal.FileDto; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.Response; import com.google.gwt.user.client.ui.HasText; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.PopupView; import com.gwtplatform.mvp.client.PresenterWidget; public class FileSelectorPresenter extends ModalPresenterWidget<FileSelectorPresenter.Display> implements FileSelectorUiHandlers { private final RequestCredentials credentials; private final FilePathPresenter filePathPresenter; private final FilePlacesPresenter filePlacesPresenter; private final FolderDetailsPresenter folderDetailsPresenter; private final ModalProvider<FileUploadModalPresenter> fileUploadModalProvider; private final Translations translations; private final TranslationMessages translationMessages; private final FileService fileService; private Object fileSelectionSource; private FileSelectionType fileSelectionType = FileSelectionType.FILE; private List<FileDto> checkedFiles; @Inject public FileSelectorPresenter(Display display, EventBus eventBus, FilePathPresenter filePathPresenter, FilePlacesPresenter filePlacesPresenter, FolderDetailsPresenter folderDetailsPresenter, ModalProvider<FileUploadModalPresenter> fileUploadModalProvider, RequestCredentials credentials, Translations translations, TranslationMessages translationMessages, FileService fileService) { super(eventBus, display); this.filePathPresenter = filePathPresenter; this.filePlacesPresenter = filePlacesPresenter; this.folderDetailsPresenter = folderDetailsPresenter; this.fileUploadModalProvider = fileUploadModalProvider.setContainer(this); this.credentials = credentials; this.translations = translations; this.translationMessages = translationMessages; this.fileService = fileService; getView().setUiHandlers(this); } public void handle(FileSelectionRequestEvent event) { setFileSelectionSource(event.getSource()); setFileSelectionType(event.getFileSelectionType()); showProject(event.getProject()); } public void showProject(String project) { filePlacesPresenter.showProject(project); } public FileDto getCurrentFolder() { return folderDetailsPresenter.getCurrentFolder(); } public List<FileDto> getCheckedFiles() { return checkedFiles; } public FileDto getSelectedFile() { return checkedFiles == null || getCheckedFiles().isEmpty() ? null : getCheckedFiles().get(0); } public void clearSelection() { checkedFiles = null; folderDetailsPresenter.getView().clearSelection(); } @Override protected void onBind() { super.onBind(); for(SplitPaneWorkbenchPresenter.Slot slot : SplitPaneWorkbenchPresenter.Slot.values()) { setInSlot(slot, getDefaultPresenter(slot)); } addRegisteredHandler(FilesCheckedEvent.getType(), new FilesCheckedEvent.FilesCheckedHandler() { @Override public void onFilesChecked(FilesCheckedEvent event) { checkedFiles = event.getCheckedFiles(); } }); folderDetailsPresenter.setSingleSelectionModel(true); } protected PresenterWidget<?> getDefaultPresenter(SplitPaneWorkbenchPresenter.Slot slot) { switch(slot) { case TOP: return filePathPresenter; case CENTER: return folderDetailsPresenter; case LEFT: return filePlacesPresenter; default: return null; } } private void setDisplaysFiles(boolean displaysFiles) { folderDetailsPresenter.getView().setDisplaysFiles(displaysFiles); } @Override public void onReveal() { // Clear previous state. clearSelection(); // clear previous selection (highlighted row) getView().clearNewFolderName(); // clear previous new folder name // Adjust display based on file selection type. setDisplaysFiles(displaysFiles()); FileDto lastFolder = fileService.getLastFolderDto(); folderDetailsPresenter.setCurrentFolder(lastFolder == null ? FileDtos.user(credentials.getUsername()) : lastFolder); } public void setFileSelectionSource(Object fileSelectionSource) { this.fileSelectionSource = fileSelectionSource; } public void setFileSelectionType(FileSelectionType fileSelectionType) { this.fileSelectionType = fileSelectionType; } public boolean displaysFiles() { return fileSelectionType == FileSelectionType.FILE || fileSelectionType == FileSelectionType.FILE_OR_FOLDER; } private void createFolder(String destination, String folder) { ResourceCallback<FileDto> createdCallback = new ResourceCallback<FileDto>() { @Override public void onResource(Response response, FileDto resource) { fireEvent(new FolderCreatedEvent(resource)); getView().clearNewFolderName(); } }; ResponseCodeCallback callbackHandler = new ResponseCodeCallback() { @Override public void onResponseCode(Request request, Response response) { fireEvent(NotificationEvent.newBuilder().error(response.getText()).build()); } }; ResourceRequestBuilderFactory.<FileDto>newBuilder().forResource("/files" + destination).post() .withBody("text/plain", folder).withCallback(createdCallback) .withCallback(Response.SC_FORBIDDEN, callbackHandler) .withCallback(Response.SC_INTERNAL_SERVER_ERROR, callbackHandler).send(); } @Nullable public FileSelection getSelection() { FileDto selectedFile = getSelectedFile(); if(selectedFile == null) { if (fileSelectionType == FileSelectionType.FOLDER) { selectedFile = getCurrentFolder(); return new FileSelection(selectedFile.getPath(), fileSelectionType); } return null; } if(fileSelectionType == FileSelectionType.FILE_OR_FOLDER) { return new FileSelection(selectedFile.getPath(), fileSelectionType); } if(FileDtos.isFile(selectedFile) && fileSelectionType == FileSelectionType.FILE) { return new FileSelection(selectedFile.getPath(), fileSelectionType); } if(FileDtos.isFolder(selectedFile) && fileSelectionType == FileSelectionType.FOLDER) { return new FileSelection(selectedFile.getPath(), fileSelectionType); } return null; } @Override public void onUploadFile() { FileUploadModalPresenter fileUploadModalPresenter = fileUploadModalProvider.get(); fileUploadModalPresenter.setCurrentFolder(folderDetailsPresenter.getCurrentFolder()); fileUploadModalProvider.show(); } @Override public void onSelect() { FileSelection selection = getSelection(); if(selection == null) { getView().clearErrors(); getView().showError(getNoSelectionErrorMessage()); } else { fireEvent(new FileSelectionEvent(fileSelectionSource, selection)); getView().hideDialog(); } } @Override public void onCancel() { getView().hideDialog(); } @Override public void onCreateFolder() { String newFolder = getView().getCreateFolderName().getText().trim(); FileDto currentFolder = getCurrentFolder(); if(currentFolder != null && !newFolder.isEmpty()) { createFolder(currentFolder.getPath(), newFolder); } } public String getNoSelectionErrorMessage() { if(folderDetailsPresenter.isSingleSelectionModel()) { return translationMessages.mustSelectFileFolder(translations.fileFolderTypeMap().get(fileSelectionType.name())); } return translationMessages .mustSelectAtLeastFileFolder(translations.fileFolderTypeMap().get(fileSelectionType.name())); } public enum FileSelectionType { FILE, FOLDER, FILE_OR_FOLDER } public interface Display extends PopupView, HasUiHandlers<FileSelectorUiHandlers> { void hideDialog(); HasText getCreateFolderName(); void clearNewFolderName(); void clearErrors(); void showError(String errorMessage); } public static class FileSelection { private final String selectionPath; private final FileSelectionType selectionType; public FileSelection(String selectionPath, FileSelectionType selectionType) { this.selectionPath = selectionPath; this.selectionType = selectionType; } public String getSelectionPath() { return selectionPath; } public FileSelectionType getSelectionType() { return selectionType; } } }
kazoompa/opal
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/fs/presenter/FileSelectorPresenter.java
Java
gpl-3.0
10,008
package synch; import java.util.concurrent.locks.*; /** * A bank with a number of bank accounts that uses locks for serializing access. * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { private final double[] accounts; private Lock bankLock; private Condition sufficientFunds; /** * Constructs the bank. * @param n the number of accounts * @param initialBalance the initial balance for each account */ public Bank(int n, double initialBalance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialBalance; bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); } /** * Transfers money from one account to another. * @param from the account to transfer from * @param to the account to transfer to * @param amount the amount to transfer */ public void transfer(int from, int to, double amount) throws InterruptedException { bankLock.lock(); try { while (accounts[from] < amount) sufficientFunds.await(); System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); sufficientFunds.signalAll(); } finally { bankLock.unlock(); } } /** * Gets the sum of all account balances. * @return the total balance */ public double getTotalBalance() { bankLock.lock(); try { double sum = 0; for (double a : accounts) sum += a; return sum; } finally { bankLock.unlock(); } } /** * Gets the number of accounts in the bank. * @return the number of accounts */ public int size() { return accounts.length; } }
seapub/SourceCode
Java/corejava9/v1ch14/synch/Bank.java
Java
gpl-3.0
2,014
package fr.chaffotm.geobase.assertion; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; public class ListParameterizedType implements ParameterizedType { private final Class resourceClass; ListParameterizedType(Class resourceClass) { this.resourceClass = resourceClass; } @Override public Type[] getActualTypeArguments() { return new Type[] { resourceClass }; } @Override public Type getRawType() { return List.class; } @Override public Type getOwnerType() { return List.class; } }
mchaffotte/geo-application
geobase-quarkus/src/test/java/fr/chaffotm/geobase/assertion/ListParameterizedType.java
Java
gpl-3.0
619
dojo.provide("dojo.widget.DropdownTimePicker"); dojo.require("dojo.widget.*"); dojo.require("dojo.widget.DropdownContainer"); dojo.require("dojo.widget.TimePicker"); dojo.require("dojo.event.*"); dojo.require("dojo.html.*"); dojo.require("dojo.date.format"); dojo.require("dojo.date.serialize"); dojo.require("dojo.i18n.common"); dojo.requireLocalization("dojo.widget", "DropdownTimePicker"); dojo.widget.defineWidget( "dojo.widget.DropdownTimePicker", dojo.widget.DropdownContainer, { /* summary: A form input for entering times with a pop-up dojo.widget.TimePicker to aid in selection description: This is TimePicker in a DropdownContainer, it supports all features of TimeePicker. It is possible to customize the user-visible formatting with either the formatLength or displayFormat attributes. The value sent to the server is typically a locale-independent value in a hidden field as defined by the name attribute. RFC3339 representation is used by default, but other options are available with saveFormat. usage: var dtp = dojo.widget.createWidget("DropdownTimePicker", {}, dojo.byId("DropdownTimePickerNode")); <input dojoType="DropdownTimePicker"> */ // iconURL: URL // path of icon for button to display time picker widget iconURL: dojo.uri.moduleUri("dojo.widget", "templates/images/timeIcon.gif"), // formatLength: String // Type of formatting used for visual display, appropriate to locale (choice of long, short, medium or full) // See dojo.date.format for details. formatLength: "short", // displayFormat: String // A pattern used for the visual display of the formatted date. // Setting this overrides the default locale-specific settings as well as the formatLength // attribute. See dojo.date.format for a reference which defines the formatting patterns. displayFormat: "", timeFormat: "", // deprecated, will be removed for 0.5 //FIXME: need saveFormat attribute support // saveFormat: String // Formatting scheme used when submitting the form element. This formatting is used in a hidden // field (name) intended for server use, and is therefore typically locale-independent. // By default, uses rfc3339 style date formatting (rfc) // Use a pattern string like displayFormat or one of the following: // rfc|iso|posix|unix saveFormat: "", // value: String|Date // form value property in rfc3339 format. ex: 12:00 value: "", // name: String // name of the form element, used to create a hidden field by this name for form element submission. name: "", postMixInProperties: function() { // summary: see dojo.widget.DomWidget dojo.widget.DropdownTimePicker.superclass.postMixInProperties.apply(this, arguments); var messages = dojo.i18n.getLocalization("dojo.widget", "DropdownTimePicker", this.lang); this.iconAlt = messages.selectTime; //FIXME: should this be if/else/else? if(typeof(this.value)=='string'&&this.value.toLowerCase()=='today'){ this.value = new Date(); } if(this.value && isNaN(this.value)){ var orig = this.value; this.value = dojo.date.fromRfc3339(this.value); if(!this.value){ var d = dojo.date.format(new Date(), { selector: "dateOnly", datePattern: "yyyy-MM-dd" }); var c = orig.split(":"); for(var i = 0; i < c.length; ++i){ if(c[i].length == 1) c[i] = "0" + c[i]; } orig = c.join(":"); this.value = dojo.date.fromRfc3339(d + "T" + orig); dojo.deprecated("dojo.widget.DropdownTimePicker", "time attributes must be passed in Rfc3339 format", "0.5"); } } if(this.value && !isNaN(this.value)){ this.value = new Date(this.value); } }, fillInTemplate: function(){ // summary: see dojo.widget.DomWidget dojo.widget.DropdownTimePicker.superclass.fillInTemplate.apply(this, arguments); var value = ""; if(this.value instanceof Date) { value = this.value; } else if(this.value) { var orig = this.value; var d = dojo.date.format(new Date(), { selector: "dateOnly", datePattern: "yyyy-MM-dd" }); var c = orig.split(":"); for(var i = 0; i < c.length; ++i){ if(c[i].length == 1) c[i] = "0" + c[i]; } orig = c.join(":"); value = dojo.date.fromRfc3339(d + "T" + orig); } var tpArgs = { widgetContainerId: this.widgetId, lang: this.lang, value: value }; this.timePicker = dojo.widget.createWidget("TimePicker", tpArgs, this.containerNode, "child"); dojo.event.connect(this.timePicker, "onValueChanged", this, "_updateText"); if(this.value){ this._updateText(); } this.containerNode.style.zIndex = this.zIndex; this.containerNode.explodeClassName = "timeContainer"; this.valueNode.name = this.name; }, getValue: function(){ // summary: return current time in time-only portion of RFC 3339 format return this.valueNode.value; /*String*/ }, getTime: function(){ // summary: return current time as a Date object return this.timePicker.storedTime; /*Date*/ }, setValue: function(/*Date|String*/rfcDate){ //summary: set the current time from RFC 3339 formatted string or a date object, synonymous with setTime this.setTime(rfcDate); }, setTime: function(/*Date|String*/dateObj){ // summary: set the current time and update the UI var value = ""; if(dateObj instanceof Date) { value = dateObj; } else if(this.value) { var orig = this.value; var d = dojo.date.format(new Date(), { selector: "dateOnly", datePattern: "yyyy-MM-dd" }); var c = orig.split(":"); for(var i = 0; i < c.length; ++i){ if(c[i].length == 1) c[i] = "0" + c[i]; } orig = c.join(":"); value = dojo.date.fromRfc3339(d + "T" + orig); } this.timePicker.setTime(value); this._syncValueNode(); }, _updateText: function(){ // summary: updates the <input> field according to the current value (ie, displays the formatted date) if(this.timePicker.selectedTime.anyTime){ this.inputNode.value = ""; }else if(this.timeFormat){ dojo.deprecated("dojo.widget.DropdownTimePicker", "Must use displayFormat attribute instead of timeFormat. See dojo.date.format for specification.", "0.5"); this.inputNode.value = dojo.date.strftime(this.timePicker.time, this.timeFormat, this.lang); }else{ this.inputNode.value = dojo.date.format(this.timePicker.time, {formatLength:this.formatLength, timePattern:this.displayFormat, selector:'timeOnly', locale:this.lang}); } this._syncValueNode(); this.onValueChanged(this.getTime()); this.hideContainer(); }, onValueChanged: function(/*Date*/dateObj){ // summary: triggered when this.value is changed }, onInputChange: function(){ // summary: callback when user manually types a time into the <input> field if(this.dateFormat){ dojo.deprecated("dojo.widget.DropdownTimePicker", "Cannot parse user input. Must use displayFormat attribute instead of dateFormat. See dojo.date.format for specification.", "0.5"); }else{ var input = dojo.string.trim(this.inputNode.value); if(input){ var inputTime = dojo.date.parse(input, {formatLength:this.formatLength, timePattern:this.displayFormat, selector:'timeOnly', locale:this.lang}); if(inputTime){ this.setTime(inputTime); } } else { this.valueNode.value = input; } } // If the time entered didn't parse, reset to the old time. KISS, for now. //TODO: usability? should we provide more feedback somehow? an error notice? // seems redundant to do this if the parse failed, but at least until we have validation, // this will fix up the display of entries like 01/32/2006 if(input){ this._updateText(); } }, _syncValueNode: function(){ var time = this.timePicker.time; var value; switch(this.saveFormat.toLowerCase()){ case "rfc": case "iso": case "": value = dojo.date.toRfc3339(time, 'timeOnly'); break; case "posix": case "unix": value = Number(time); break; default: value = dojo.date.format(time, {datePattern:this.saveFormat, selector:'timeOnly', locale:this.lang}); } this.valueNode.value = value; }, destroy: function(/*Boolean*/finalize){ this.timePicker.destroy(finalize); dojo.widget.DropdownTimePicker.superclass.destroy.apply(this, arguments); } } );
idega/org.chiba.web
resources/javascript/dojo-0.4.4/src/widget/DropdownTimePicker.js
JavaScript
gpl-3.0
8,387
/* Copyright (C) 2003-2013 Runtime Revolution Ltd. This file is part of LiveCode. LiveCode is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License v3 as published by the Free Software Foundation. LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */ #include "prefix.h" #include "globdefs.h" #include "objdefs.h" #include "parsedef.h" #include "filedefs.h" #include "mcio.h" #include "globals.h" #include "stack.h" #include "stacklst.h" #include "card.h" #include "mccontrol.h" #include "objptr.h" #include "group.h" #include "field.h" #include "button.h" #include "image.h" #include "redraw.h" #include "util.h" #include "mctheme.h" #include "bitmapeffect.h" #include "tilecache.h" #include "context.h" #include "graphicscontext.h" #include "resolution.h" //////////////////////////////////////////////////////////////////////////////// // This method resets the layer-related attribtues to defaults and marks them // as needing recomputing. void MCControl::layer_resetattrs(void) { m_layer_mode = kMCLayerModeHintStatic; m_layer_is_opaque = false; m_layer_is_unadorned = false; m_layer_is_sprite = false; m_layer_is_direct = false; m_layer_attr_changed = true; m_layer_id = 0; } // This method updates all the layer attributes of the control to make sure they // are consistent with the controls current set of flags. If commit is false, // then the new layermode is returned without changing anything. MCLayerModeHint MCControl::layer_computeattrs(bool p_commit) { // If the attrs have not changed, there is nothing to do. if (!m_layer_attr_changed) return m_layer_mode; // If the layer id is 0, then it means we should clear current settings. if (m_layer_id == 0) { m_layer_mode = kMCLayerModeHintStatic; m_layer_is_opaque = false; m_layer_is_unadorned = false; m_layer_is_sprite = false; m_layer_is_direct = false; } // The opacity of a control depends on what flags it has set - in particular // the 'opaque' flag. However, as 'opaque' determines themed bg rendering this // is not a sufficient condition. // // If a control has external bitmap effects (drop shadow, outerglow) then it // cannot be opaque. Similarly, if the control is rendered with themed bgs then // it cannot be opaque. // // Opacity is more dynamic an attribute than adornedness and should be handled // as a separate computation in the future. // bool t_is_opaque; t_is_opaque = false; if (MCBitmapEffectsIsInteriorOnly(getbitmapeffects())) { switch(gettype()) { case CT_GROUP: // Only consider groups unadorned groups to be opaque. t_is_opaque = getflag(F_OPAQUE) && !getflag(F_HSCROLLBAR | F_VSCROLLBAR | F_SHOW_NAME | F_SHOW_BORDER); break; case CT_FIELD: // Only consider unadorned fields to be opaque. t_is_opaque = getflag(F_OPAQUE) && !getflag(F_HSCROLLBAR | F_VSCROLLBAR | F_SHOW_BORDER | F_SHADOW) && (extraflags & EF_NO_FOCUS_BORDER) != 0; break; case CT_BUTTON: case CT_IMAGE: case CT_SCROLLBAR: case CT_GRAPHIC: case CT_PLAYER: default: // The rest of the control types are hard to assess for opacity as // that depends on their content / or complex theming considerations. t_is_opaque = false; break; } } else t_is_opaque = false; // The unadorned state depends on control type, but in general means that the // control consists of background + content. For a group content is the child // controls, for a field its the text, for an image its the bits, for a button // its the icon (if any), for a graphic it means just its shape. // // If a control has bitmap effects, it is always adorned as this requires further // processing of the image. // // If a control is selected, it is always adorned, since the selection handles // are part of the object. // bool t_is_unadorned; if (getbitmapeffects() == nil && !getstate(CS_SELECTED)) { switch(gettype()) { case CT_GROUP: // A group is unadorned if it has no scrollbars, no border and doesn't // show a name. t_is_unadorned = !getflag(F_HSCROLLBAR | F_VSCROLLBAR | F_SHOW_NAME | F_SHOW_BORDER); uint16_t t_index; // IM-2014-05-02: [[ Bugfix 12044 ]] An opaque group is unadorned if its background is a color and it disallows overscroll t_is_unadorned &= !getflag(F_OPAQUE) || (getcindex(DI_BACK, t_index) && !getflag(F_UNBOUNDED_HSCROLL | F_UNBOUNDED_VSCROLL)); break; case CT_FIELD: // A field is unadorned if it has no shadow, no scrollbars, no border and no focus // border. t_is_unadorned = !getflag(F_HSCROLLBAR | F_VSCROLLBAR | F_SHOW_BORDER | F_SHADOW) && (extraflags & EF_NO_FOCUS_BORDER) != 0; break; case CT_BUTTON: // A button is unadorned if it is not a combo-box is showing an icon, has no border, // no name, no shadow, no hilite border, no arm border and no focus border. if (((MCButton *)this) -> getmenumode() != WM_COMBO) t_is_unadorned = getflag(F_SHOW_ICON) && !getflag(F_SHOW_BORDER | F_SHOW_NAME | F_SHADOW | F_HILITE_BORDER | F_ARM_BORDER) && (extraflags & EF_NO_FOCUS_BORDER) != 0; else t_is_unadorned = false; break; case CT_IMAGE: // An image is unadorned if it is not a pict, has no border and no focus border. if (static_cast<MCImage*>(this)->getcompression() != F_PICT) t_is_unadorned = !getflag(F_SHOW_BORDER) && (extraflags & EF_NO_FOCUS_BORDER) != 0; else t_is_unadorned = false; break; case CT_SCROLLBAR: case CT_GRAPHIC: case CT_PLAYER: default: t_is_unadorned = false; break; } } else t_is_unadorned = false; // The actual type of layer we will use depends on opacity, adornedness, // type and ink. MCLayerModeHint t_layer_mode; if (m_layer_mode_hint == kMCLayerModeHintStatic) { // To be a static layer, we must have an ink that is GXcopy or // GXblendSrcOver. if (ink == GXcopy || ink == GXblendSrcOver) t_layer_mode = kMCLayerModeHintStatic; else t_layer_mode = kMCLayerModeHintDynamic; } else if (m_layer_mode_hint == kMCLayerModeHintDynamic) { // There is no restriction on what control props can be to be // a dynamic layer. t_layer_mode = kMCLayerModeHintDynamic; } else if (m_layer_mode_hint == kMCLayerModeHintScrolling) { // A scrolling layer must be unadorned and a group. if (gettype() == CT_GROUP && t_is_unadorned) t_layer_mode = kMCLayerModeHintScrolling; else t_layer_mode = kMCLayerModeHintDynamic; } else if (m_layer_mode_hint == kMCLayerModeHintContainer) { // A container layer must be unadorned, non-opaque and a group. if (gettype() == CT_GROUP && !t_is_opaque && t_is_unadorned) t_layer_mode = kMCLayerModeHintContainer; else t_layer_mode = kMCLayerModeHintStatic; } // Now compute the sprite attribute. bool t_is_sprite; if (t_layer_mode == kMCLayerModeHintDynamic || t_layer_mode == kMCLayerModeHintScrolling) t_is_sprite = true; else t_is_sprite = false; // And now the direct attribute. bool t_is_direct; if (t_is_sprite) { // An unadorned image or button are direct. if (t_is_unadorned && (gettype() == CT_IMAGE || gettype() == CT_BUTTON)) t_is_direct = true; else t_is_direct = false; } else t_is_direct = false; // Finally, sync the attribtues. if (p_commit) { m_layer_mode = t_layer_mode; m_layer_is_opaque = t_is_opaque; m_layer_is_unadorned = t_is_unadorned; m_layer_is_sprite = t_is_sprite; m_layer_is_direct = t_is_direct; // We've updated the layer attrs now - yay! m_layer_attr_changed = false; } return m_layer_mode; } //////////////////////////////////////////////////////////////////////////////// MCRectangle MCControl::layer_getcontentrect(void) { // As getcontentrect is only called if 'isscrolling' is true, this unchecked // cast is safe. MCRectangle t_content_rect = static_cast<MCGroup *>(this) -> getminrect(); // IM-2014-04-16: [[ Bug 12044 ]] Include rect when computing the coverage of opaque groups if (flags & F_OPAQUE) t_content_rect = MCU_union_rect(t_content_rect, rect); return t_content_rect; } void MCControl::layer_redrawall(void) { if (!opened) return; // Check the visibility state of the object. bool t_is_visible; t_is_visible = isvisible() || MCshowinvisibles; // If we are not a sprite, and are invisible there is nothing to do; otherwise // we must at least try to dump cached updated parts of the sprite. if (!layer_issprite() && !t_is_visible) return; // Scrolling layers are a special case as its the content that must be dirtied // not the effective image. if (!layer_isscrolling()) layer_dirtyeffectiverect(geteffectiverect(), t_is_visible); else layer_dirtycontentrect(layer_getcontentrect(), t_is_visible); } void MCControl::layer_redrawrect(const MCRectangle& p_dirty_rect) { if (!opened) return; // Check the visibility state of the object. bool t_is_visible; t_is_visible = isvisible() || MCshowinvisibles; // If we are not a sprite, and are invisible there is nothing to do; otherwise // we must at least try to dump cached updated parts of the sprite. if (!layer_issprite() && !t_is_visible) return; // Scrolling layers are a special case as its the content that must be dirtied // not the effective image. if (!layer_isscrolling()) { MCRectangle t_dirty_rect; t_dirty_rect = p_dirty_rect; if (m_bitmap_effects != nil) MCBitmapEffectsComputeBounds(m_bitmap_effects, t_dirty_rect, t_dirty_rect); layer_dirtyeffectiverect(t_dirty_rect, t_is_visible); } else layer_dirtycontentrect(p_dirty_rect, t_is_visible); } void MCControl::layer_transientchangedandredrawall(int32_t p_old_transient) { if (!opened) return; // Check the visibility state of the object. bool t_is_visible; t_is_visible = isvisible() || MCshowinvisibles; // If we are not a sprite, and are invisible there is nothing to do; otherwise // we must at least try to dump cached updated parts of the sprite. if (!layer_issprite() && !t_is_visible) return; MCRectangle t_old_effectiverect; t_old_effectiverect = MCU_reduce_rect(rect, -p_old_transient); if (m_bitmap_effects != nil) MCBitmapEffectsComputeBounds(m_bitmap_effects, t_old_effectiverect, t_old_effectiverect); layer_changeeffectiverect(t_old_effectiverect, true, t_is_visible); } void MCControl::layer_setrect(const MCRectangle& p_new_rect, bool p_redraw_all) { if (!opened) { setrect(p_new_rect); return; } // Check the visibility state of the object. bool t_is_visible; t_is_visible = isvisible() || MCshowinvisibles; // If we are not a sprite, and are invisible there is nothing to do; otherwise // we must at least try to dump cached updated parts of the sprite. if (!layer_issprite() && !t_is_visible) { setrect(p_new_rect); return; } MCRectangle t_old_effectiverect; t_old_effectiverect = geteffectiverect(); // If the rect has changed size and we aren't a scrolling layer, then we // redraw all. if (!layer_isscrolling() && (rect . width != p_new_rect . width || rect . height != p_new_rect . height)) p_redraw_all = true; setrect(p_new_rect); layer_changeeffectiverect(t_old_effectiverect, p_redraw_all, t_is_visible); } void MCControl::layer_rectchanged(const MCRectangle& p_old_rect, bool p_redraw_all) { if (!opened) return; // Check the visibility state of the object. bool t_is_visible; t_is_visible = isvisible() || MCshowinvisibles; // If we are not a sprite, and are invisible there is nothing to do; otherwise // we must at least try to dump cached updated parts of the sprite. if (!layer_issprite() && !t_is_visible) return; // Cache the new rectangle. MCRectangle t_new_rect; t_new_rect = rect; // Temporarily set it back to the old one so we can compute the old effective // rect. MCRectangle t_old_effectiverect; rect = p_old_rect; t_old_effectiverect = geteffectiverect(); // If the rect has changed size and we aren't a scrolling layer, then we // redraw all. if (!layer_isscrolling() && (rect . width != t_new_rect . width || rect . height != t_new_rect . height)) p_redraw_all = true; // Replace the new rect and do the rect changed updates. rect = t_new_rect; layer_changeeffectiverect(t_old_effectiverect, p_redraw_all, t_is_visible); } void MCControl::layer_effectiverectchangedandredrawall(const MCRectangle& p_old_effective_rect) { if (!opened) return; // Check the visibility state of the object. bool t_is_visible; t_is_visible = isvisible() || MCshowinvisibles; // If we are not a sprite, and are invisible there is nothing to do; otherwise // we must at least try to dump cached updated parts of the sprite. if (!layer_issprite() && !t_is_visible) return; layer_changeeffectiverect(p_old_effective_rect, true, t_is_visible); } void MCControl::layer_effectschanged(const MCRectangle& p_old_effective_rect) { layer_effectiverectchangedandredrawall(p_old_effective_rect); } // MW-2011-10-17: [[ Bug 9813 ]] We need the effective rect before visibility is // changed, else focus border might be not included in our calculation. void MCControl::layer_visibilitychanged(const MCRectangle& p_old_effective_rect) { if (!opened) return; if (!parent -> isvisible() && !MCshowinvisibles) return; // If the control is currently visible, then its old rect must have been // empty; otherwise the old rect is its effectiverect. layer_changeeffectiverect(getflag(F_VISIBLE) ? MCU_make_rect(0, 0, 0, 0) : p_old_effective_rect, false, true); } void MCControl::layer_contentoriginchanged(int32_t p_dx, int32_t p_dy) { if (!opened) return; if (!layer_isscrolling()) return; // If the layer id is 0 then return. if (m_layer_id == 0) return; // Fetch the tilecache we are using. MCTileCacheRef t_tilecache; t_tilecache = getstack() -> view_gettilecache(); // Scroll the sprite - note that this method is only called if // layer_isscrolling() is true, which is only possible if we have a tilecache. // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCGPoint t_device_point; t_device_point = MCGPointApplyAffineTransform(MCGPointMake(p_dx, p_dy), getstack()->getdevicetransform()); MCGFloat t_dx, t_dy; t_dx = t_device_point.x; t_dy = t_device_point.y; MCTileCacheScrollSprite(t_tilecache, m_layer_id, t_dx, t_dy); } void MCControl::layer_scrolled(void) { if (!opened) return; // Check the visibility state of the object. bool t_is_visible; t_is_visible = isvisible() || MCshowinvisibles; // If the layer isn't scrolling, we must redraw the whole thing. Otherwise // we just need to invalidate a portion of the card. if (!layer_isscrolling()) { // We only actually need to do something if we are in the sprite // case, or we are visible if (layer_issprite() || t_is_visible) layer_dirtyeffectiverect(geteffectiverect(), t_is_visible); } else { // If we are a scrolling layer and not visible, there is nothing to // do. if (t_is_visible) static_cast<MCCard *>(parent) -> layer_dirtyrect(geteffectiverect()); } } void MCControl::layer_dirtycontentrect(const MCRectangle& p_updated_rect, bool p_update_card) { if (MCU_empty_rect(p_updated_rect)) return; MCRectangle t_content_rect; t_content_rect = layer_getcontentrect(); MCTileCacheRef t_tilecache; t_tilecache = getstack() -> view_gettilecache(); // Note that this method is only called if layer_isscrolling() is true, which is only // possible if we have a tilecache. if (m_layer_id != 0) { // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCGAffineTransform t_transform; t_transform = getstack()->getdevicetransform(); MCRectangle32 t_device_updated_rect, t_device_content_rect; t_device_updated_rect = MCRectangle32GetTransformedBounds(p_updated_rect, t_transform); t_device_content_rect = MCRectangle32GetTransformedBounds(t_content_rect, t_transform); MCTileCacheUpdateSprite(t_tilecache, m_layer_id, MCRectangle32Offset(t_device_updated_rect, -t_device_content_rect . x, -t_device_content_rect . y)); } // Add the rect to the update region - but only if instructed (update_card will be // false if the object was invisible). if (p_update_card) static_cast<MCCard *>(parent) -> layer_dirtyrect(MCU_intersect_rect(p_updated_rect, geteffectiverect())); } void MCControl::layer_dirtyeffectiverect(const MCRectangle& p_effective_rect, bool p_update_card) { // The dirty rect will be the input effective rect expanded by any effects // applied by the parent groups (if any). MCRectangle t_dirty_rect; t_dirty_rect = p_effective_rect; // Expand the effective rect by that of all parent groups. MCControl *t_control; t_control = this; while(t_control -> parent -> gettype() == CT_GROUP) { MCControl *t_parent_control; t_parent_control = static_cast<MCControl *>(t_control -> parent); // If the parent control is scrolling, we are done - defer to content // dirtying. if (t_parent_control -> layer_isscrolling()) { t_parent_control -> layer_dirtycontentrect(t_dirty_rect, p_update_card); return; } // Otherwise intersect the dirty rect with the parent's rect. t_dirty_rect = MCU_intersect_rect(t_dirty_rect, t_control -> parent -> getrect()); // Expand due to bitmap effects (if any). if (t_parent_control -> m_bitmap_effects != nil) MCBitmapEffectsComputeBounds(t_parent_control -> m_bitmap_effects, t_dirty_rect, t_dirty_rect); t_control = t_parent_control; } // Fetch the tilecache we are using (if any). MCTileCacheRef t_tilecache; t_tilecache = t_control -> getstack() -> view_gettilecache(); // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCGAffineTransform t_transform; t_transform = getstack()->getdevicetransform(); MCRectangle32 t_device_rect; t_device_rect = MCRectangle32GetTransformedBounds(t_dirty_rect, t_transform); // Notify any tilecache of the changes. if (t_tilecache != nil) { // We must be in tile-cache mode with a top-level control, but if the layer // id is zero, there is nothing to do. if (t_control -> m_layer_id == 0) return; // How we handle the layer depends on whether it is a sprite or not. if (!t_control -> layer_issprite()) { // Non-dynamic layers are scenery in the tilecache, their rect is in // canvas co-ords. MCTileCacheUpdateScenery(t_tilecache, t_control -> m_layer_id, t_device_rect); } else { // Dynamic layers are sprites in the tilecache, their rect is in // sprite co-ords. MCRectangle t_offset_rect; t_offset_rect = MCU_offset_rect(t_dirty_rect, -t_control -> rect . x, -t_control -> rect . y); // MW-2013-10-29: [[ Bug 11329 ]] Tilecache expects sprite rects to be // relative to top-left of sprite. t_transform . tx = 0.0f; t_transform . ty = 0.0f; // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords t_device_rect = MCRectangle32GetTransformedBounds(t_offset_rect, t_transform); MCTileCacheUpdateSprite(t_tilecache, t_control -> m_layer_id, t_device_rect); } } // Add the rect to the update region - but only if instructed (update_card will be // false if the object was invisible). if (p_update_card) static_cast<MCCard *>(t_control -> parent) -> layer_dirtyrect(t_dirty_rect); } void MCControl::layer_changeeffectiverect(const MCRectangle& p_old_effective_rect, bool p_force_update, bool p_update_card) { // Compute the 'new' effectiverect based on visibility. MCRectangle t_new_effective_rect; if (getflag(F_VISIBLE) || MCshowinvisibles) t_new_effective_rect = geteffectiverect(); else MCU_set_rect(t_new_effective_rect, 0, 0, 0, 0); // If the effective rect has not changed this is at most an update. if (MCU_equal_rect(p_old_effective_rect, t_new_effective_rect)) { // If we are forcing an update, use the dirty method. if (p_force_update) { // If the layer is not scrolling just defer to the normal // dirty method; otherwise use the dirty content method. if (!layer_isscrolling()) layer_dirtyeffectiverect(t_new_effective_rect, p_update_card); else layer_dirtycontentrect(layer_getcontentrect(), p_update_card); } // We are done. return; } // Fetch the tilecache, making it nil if the parent is a group (in the // latter case, this is just a dirty op). MCTileCacheRef t_tilecache; if (parent -> gettype() != CT_GROUP) t_tilecache = getstack() -> view_gettilecache(); else t_tilecache = nil; // If no tilecache, then just dirty the old and new effective rects. if (t_tilecache == nil) { layer_dirtyeffectiverect(p_old_effective_rect, p_update_card); layer_dirtyeffectiverect(t_new_effective_rect, p_update_card); return; } // MW-2011-10-17: [[ Bug 9808 ]] Make sure we update the card regardless of // whether we have a layer id - otherwise new objects don't show! // Add the rects to the update region - but only if instructed (update_card will be // false if the object was invisible). if (p_update_card) { static_cast<MCCard *>(parent) -> layer_dirtyrect(p_old_effective_rect); static_cast<MCCard *>(parent) -> layer_dirtyrect(t_new_effective_rect); } // We must be in tile-cache mode with a top-level control, but if the layer // id is zero, there is nothing to do. if (m_layer_id == 0) return; if (!layer_issprite()) { // Non-dynamic layers are scenery in the tilecache, and we must use old // new effective rects so that the appropriate tiles get flushed. Note // that 'force_update' has no effect here as reshaping a scenery layer // implicitly invalidates all tiles it touches. // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCGAffineTransform t_transform; t_transform = getstack()->getdevicetransform(); MCRectangle32 t_old_device_rect, t_new_device_rect; t_old_device_rect = MCRectangle32GetTransformedBounds(p_old_effective_rect, t_transform); t_new_device_rect = MCRectangle32GetTransformedBounds(t_new_effective_rect, t_transform); MCTileCacheReshapeScenery(t_tilecache, m_layer_id, t_old_device_rect, t_new_device_rect); } else { // Dynamic layers are sprites in the tilecache, and there is nothing to // do unless 'force update' is required. In particular, if the layer is // just moving then no redraw of the layer will be needed. Note, however, // that this implicitly assumes that 'force update' is true if the content // in a sprite-relative co-ord system has changed. if (p_force_update) { MCRectangle t_rect; // If the layer is not scrolling, just use the width/height from the // effective rect; otherwise use content width/height. if (!layer_isscrolling()) t_rect = p_old_effective_rect; else t_rect = layer_getcontentrect(); t_rect . x = t_rect . y = 0; // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCGAffineTransform t_transform; t_transform = getstack()->getdevicetransform(); // MW-2013-10-29: [[ Bug 11329 ]] Tilecache expects sprite rects to be // relative to top-left of sprite. t_transform . tx = 0.0f; t_transform . ty = 0.0f; MCRectangle32 t_device_rect; t_device_rect = MCRectangle32GetTransformedBounds(t_rect, t_transform); MCTileCacheUpdateSprite(t_tilecache, m_layer_id, t_device_rect); } } } //////////////////////////////////////////////////////////////////////////////// void MCCard::layer_added(MCControl *p_control, MCObjptr *p_previous, MCObjptr *p_next) { MCTileCacheRef t_tilecache; t_tilecache = getstack() -> view_gettilecache(); // Add the rects to the update region (for clarity, would prefer this at the end // but there is 'return' fall through in the rest :-( ). layer_dirtyrect(p_control -> geteffectiverect()); // Notify any tilecache of the changes. if (t_tilecache != nil) { // Reset all the layer's attributes to defaults, including the layer id. p_control -> layer_resetattrs(); // Recompute the control's attributes. p_control -> layer_computeattrs(true); // If the control is on a dynamic layer there is nothing to do (sprites will // be created implicitly at first render). if (p_control -> layer_issprite()) return; // If the control is not being added between two existing layers then there // is nothing to do. if (p_previous == nil || p_next == nil) return; // If the previous (layer below) objptr has no id, then there is nothing to do // also. This will only occur if only new layers have been added above, // or if no rendering has been done yet. uint32_t t_before_layer_id; t_before_layer_id = p_previous -> getref() -> layer_getid(); if (t_before_layer_id == 0) return; // MW-2013-06-21: [[ Bug 10974 ]] If the previous layer is a sprite then this layer // will change the lower limit of the scenery layers above, thus there is // nothing to do. if (p_previous -> getref() -> layer_issprite()) return; // Now insert the scenery. // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCRectangle32 t_device_rect; t_device_rect = MCRectangle32GetTransformedBounds(p_control->geteffectiverect(), getstack()->getdevicetransform()); MCTileCacheInsertScenery(t_tilecache, t_before_layer_id, t_device_rect); // Finally, set the id of the layer to that of the one before. This causes // the layer to be treated 'as one' with that layer until a redraw is done. // This means that any subsequent updates to the rect of the new layer will // appropriately flush the tiles in the cache. p_control -> layer_setid(t_before_layer_id); } } void MCCard::layer_removed(MCControl *p_control, MCObjptr *p_previous, MCObjptr *p_next) { MCTileCacheRef t_tilecache; t_tilecache = getstack() -> view_gettilecache(); // Add the rects to the update region (for clarity, would prefer this at the end // but there is 'return' fall through in the rest :-( ) layer_dirtyrect(p_control -> geteffectiverect()); // Notify any tilecache of the changes. if (t_tilecache != nil) { // If the control has no layer id then there is nothing to do. if (p_control -> layer_getid() == 0) return; // If the control is on a dynamic layer then remove any associated sprite. if (p_control -> layer_issprite()) { MCTileCacheRemoveSprite(t_tilecache, p_control -> layer_getid()); // MW-2012-09-21: [[ Bug 10005 ]] Make sure we reset the layer attrs so we // don't try and reuse a dead sprite. p_control -> layer_resetattrs(); return; } // Remove the scenery. // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCRectangle32 t_device_rect; t_device_rect = MCRectangle32GetTransformedBounds(p_control->geteffectiverect(), getstack()->getdevicetransform()); MCTileCacheRemoveScenery(t_tilecache, p_control -> layer_getid(), t_device_rect); // MW-2012-10-11: [[ Bug ]] Redraw glitch caused by resetting the layer id // before removing the layer. // MW-2012-09-21: [[ Bug 10005 ]] Make sure we reset the layer attrs so we // don't try and reuse a dead scenery layer. p_control -> layer_resetattrs(); // If there is no previous or next control we have no tweaks to ids // to perform. if (p_previous == nil || p_next == nil) return; // Now layer ids for new layers percolate from the next layer, so the // original layers are always at the bottom of the stack. If the next // layer has a different id than us, make sure all previous layers // with the same id match it. uint32_t t_before_layer_id; t_before_layer_id = p_previous -> getref() -> layer_getid(); // The layer below us has the same id so there's nothing to do, we are // removing a 'new' layer before its been redrawn. if (t_before_layer_id == p_control -> layer_getid()) return; // MW-2013-06-21: [[ Bug 10974 ]] If the layer below is a sprite, then removing // this layer will increase the lower limit of the scenery stack above // thus there is nothing to do. if (p_previous -> getref() -> layer_issprite()) return; // The layer below us has a different id, so this is an existing layer // and thus we must ensure all layers above us now use the id of the // layer below. MCObjptr *t_objptr; t_objptr = p_next; while(t_objptr != p_previous && t_objptr -> getref() -> layer_getid() == p_control -> layer_getid()) { t_objptr -> getref() -> layer_setid(t_before_layer_id); t_objptr = t_objptr -> next(); } } } void MCCard::layer_setviewport(int32_t p_x, int32_t p_y, int32_t p_width, int32_t p_height) { // Get the current rect, before updating it. MCRectangle t_old_rect; t_old_rect = rect; // Update the rect. resize(p_width, p_height); // Add the rects to the update region. // MW-2012-05-01: [[ Bug 10157 ]] If the card has a border then add the whole card // rect to the update region; otherwise just add the exposed rects. if (!getflag(F_SHOW_BORDER)) { if (p_width > t_old_rect.width) layer_dirtyrect(MCU_make_rect(t_old_rect.width, 0, p_width - t_old_rect.width, p_height)); if (p_height > t_old_rect.height) layer_dirtyrect(MCU_make_rect(0, t_old_rect.height, p_width, p_height - t_old_rect.height)); } else layer_dirtyrect(rect); } void MCCard::layer_selectedrectchanged(const MCRectangle& p_old_rect, const MCRectangle& p_new_rect) { MCTileCacheRef t_tilecache; t_tilecache = getstack() -> view_gettilecache(); if (t_tilecache != nil) { // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCGAffineTransform t_transform; t_transform = getstack()->getdevicetransform(); MCRectangle32 t_new_device_rect, t_old_device_rect; t_new_device_rect = MCRectangle32GetTransformedBounds(p_new_rect, t_transform); t_old_device_rect = MCRectangle32GetTransformedBounds(p_old_rect, t_transform); MCTileCacheReshapeScenery(t_tilecache, m_fg_layer_id, t_old_device_rect, t_new_device_rect); } layer_dirtyrect(p_old_rect); layer_dirtyrect(p_new_rect); } void MCCard::layer_dirtyrect(const MCRectangle& p_dirty_rect) { getstack() -> dirtyrect(p_dirty_rect); } //////////////////////////////////////////////////////////////////////////////// // IM-2013-08-21: [[ ResIndependence ]] callback wrapper function to create scaled MCContext // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation typedef bool (*MCTileCacheDeviceRenderCallback)(void *context, MCContext *target, const MCRectangle& region); static bool tilecache_device_renderer(MCTileCacheDeviceRenderCallback p_callback, void *p_context, MCGContextRef p_target, const MCRectangle32 &p_rectangle, bool p_is_sprite) { MCControl *t_control; t_control = static_cast<MCControl*>(p_context); // IM-2013-09-30: [[ FullscreenMode ]] Apply stack transform to device context MCGAffineTransform t_transform; t_transform = t_control->getstack()->getdevicetransform(); // MW-2013-10-29: [[ Bug 11329 ]] Tilecache expects sprite rects to be // relative to top-left of sprite. if (p_is_sprite) { t_transform . tx = 0.0f; t_transform . ty = 0.0f; } MCGContextSave(p_target); MCGContextConcatCTM(p_target, t_transform); MCGraphicsContext *t_gfx_context; /* UNCHECKED */ t_gfx_context = new MCGraphicsContext(p_target); MCRectangle t_user_rect; t_user_rect = MCRectangleGetTransformedBounds(p_rectangle, MCGAffineTransformInvert(t_transform)); bool t_success; t_success = p_callback(p_context, t_gfx_context, t_user_rect); delete t_gfx_context; MCGContextRestore(p_target); return t_success; } static bool testtilecache_sprite_renderer(void *p_context, MCContext *p_target, const MCRectangle& p_rectangle) { MCControl *t_control; t_control = (MCControl *)p_context; // A scrolling layer is an unadorned group. bool t_scrolling; t_scrolling = t_control -> layer_isscrolling(); MCRectangle t_control_rect, t_dirty_rect; if (!t_scrolling) { t_control_rect = t_control -> geteffectiverect(); t_dirty_rect = MCU_intersect_rect(t_control_rect, MCU_offset_rect(p_rectangle, t_control_rect . x, t_control_rect . y)); } else { t_control_rect = t_control -> layer_getcontentrect(); t_dirty_rect = MCU_intersect_rect(t_control_rect, MCU_offset_rect(p_rectangle, t_control_rect . x, t_control_rect . y)); } if (MCU_empty_rect(t_dirty_rect)) return true; // IM-2014-07-03: [[ GraphicsPerformance ]] Context origin is the topleft of the sprite so adjust to card coords. p_target -> setorigin(t_control_rect . x, t_control_rect . y); p_target -> cliprect(t_dirty_rect); p_target -> setfunction(GXcopy); p_target -> setopacity(255); t_control -> draw(p_target, t_dirty_rect, false, true); return true; } static bool testtilecache_device_sprite_renderer(void *p_context, MCGContextRef p_target, const MCRectangle32& p_rectangle) { return tilecache_device_renderer(testtilecache_sprite_renderer, p_context, p_target, p_rectangle, true); } static bool testtilecache_scenery_renderer(void *p_context, MCContext *p_target, const MCRectangle& p_rectangle) { MCControl *t_control; t_control = (MCControl *)p_context; // IM-2014-07-02: [[ GraphicsPerformance ]] Use the redraw() method instead of // reproducing the visibility tests and context clipping here. t_control->redraw(p_target, p_rectangle); return true; } static bool testtilecache_device_scenery_renderer(void *p_context, MCGContextRef p_target, const MCRectangle32& p_rectangle) { return tilecache_device_renderer(testtilecache_scenery_renderer, p_context, p_target, p_rectangle, false); } bool MCCard::tilecache_render_foreground(void *p_context, MCContext *p_target, const MCRectangle& p_dirty) { MCCard *t_card; t_card = (MCCard *)p_context; // IM-2014-07-02: [[ GraphicsPerformance ]] Remove unnecessary setclip call - p_dirty is already the bounds of the clip. p_target -> setfunction(GXcopy); p_target -> setopacity(255); // IM-2013-09-13: [[ RefactorGraphics ]] Use shared code to render card foreground t_card -> drawselectionrect(p_target); return true; } bool device_render_foreground(void *p_context, MCGContextRef p_target, const MCRectangle32& p_rectangle) { return tilecache_device_renderer(MCCard::tilecache_render_foreground, p_context, p_target, p_rectangle, false); } bool MCCard::tilecache_render_background(void *p_context, MCContext *p_target, const MCRectangle& p_dirty) { MCCard *t_card; t_card = (MCCard *)p_context; // MW-2013-10-23: [[ FullscreenMode ]] Make sure we set the clip to the visible rect. // IM-2013-12-20: [[ ShowAll ]] Use MCStack::getvisiblerect() to get the visible area MCRectangle t_visible_rect; t_visible_rect = t_card->getstack()->getvisiblerect(); // IM-2014-07-02: [[ GraphicsPerformance ]] Use cliprect() to reduce the clipping region. p_target -> cliprect(t_visible_rect); p_target -> setfunction(GXcopy); p_target -> setopacity(255); // IM-2013-09-13: [[ RefactorGraphics ]] Use shared code to render card background t_card -> drawbackground(p_target, p_dirty); return true; } bool device_render_background(void *p_context, MCGContextRef p_target, const MCRectangle32& p_rectangle) { return tilecache_device_renderer(MCCard::tilecache_render_background, p_context, p_target, p_rectangle, false); } void MCCard::render(void) { MCTileCacheRef t_tiler; t_tiler = getstack() -> view_gettilecache(); bool t_reset_ids; t_reset_ids = MCTileCacheIsClean(t_tiler); // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCGAffineTransform t_transform; t_transform = getstack()->getdevicetransform(); // IM-2013-10-14: [[ FullscreenMode ]] Get the visible area of the stack // IM-2013-12-20: [[ ShowAll ]] Use MCStack::getvisiblerect() to get the visible area MCRectangle t_visible_rect; t_visible_rect = getstack()->getvisiblerect(); if (getstate(CS_SIZE)) { MCTileCacheLayer t_fg_layer; t_fg_layer . id = m_fg_layer_id; t_fg_layer . region = MCRectangle32GetTransformedBounds(selrect, t_transform); t_fg_layer . clip = MCRectangle32GetTransformedBounds(t_visible_rect, t_transform); t_fg_layer . is_opaque = false; t_fg_layer . opacity = 255; t_fg_layer . ink = GXblendSrcOver; t_fg_layer . callback = device_render_foreground; t_fg_layer . context = this; MCTileCacheRenderScenery(t_tiler, t_fg_layer); m_fg_layer_id = t_fg_layer . id; } else m_fg_layer_id = 0; MCObjptr *t_objptrs; t_objptrs = getobjptrs(); if (t_objptrs != nil) { MCObjptr *t_objptr; t_objptr = t_objptrs -> prev(); do { MCControl *t_control; t_control = t_objptr -> getref(); // If the tilecache is 'clean' then we must reset the attrs to // force a sync. if (t_reset_ids) t_control -> layer_resetattrs(); // Take note of whether the spriteness of a layer has changed. bool t_old_is_sprite; t_old_is_sprite = t_control -> layer_issprite(); // Sync the attributes, make sure we commit the new values. t_control -> layer_computeattrs(true); // Initialize the common layer props. MCTileCacheLayer t_layer; t_layer . id = t_control -> layer_getid(); t_layer . opacity = t_control -> getopacity(); t_layer . ink = t_control -> getink(); t_layer . context = t_control; // The opaqueness of a layer has already been computed. t_layer . is_opaque = t_control -> layer_isopaque(); // Now compute the layer's region/clip. MCRectangle t_layer_region, t_layer_clip; if (!t_control -> getflag(F_VISIBLE) && !MCshowinvisibles) { // Invisible layers just have empty region/clip. t_layer_region = MCU_make_rect(0, 0, 0, 0); t_layer_clip = MCU_make_rect(0, 0, 0, 0); } else if (!t_control -> layer_isscrolling()) { // Non-scrolling layer's are the size of their effective rects. t_layer_region = t_control -> geteffectiverect(); t_layer_clip = t_layer_region; } else { // For a scrolling layer, the clip is the bounds of the control, while // the region we draw is the group's minrect. t_layer_region = t_control -> layer_getcontentrect(); t_layer_clip = t_control -> geteffectiverect(); } // IM-2013-10-14: [[ FullscreenMode ]] Constrain each layer to the visible area t_layer_clip = MCU_intersect_rect(t_layer_clip, t_visible_rect); // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords t_layer . region = MCRectangle32GetTransformedBounds(t_layer_region, t_transform); t_layer . clip = MCRectangle32GetTransformedBounds(t_layer_clip, t_transform); // Now render the layer - what method we use depends on whether the // layer is a sprite or not. if (t_control -> layer_issprite()) { // If the layer was not a sprite before, remove the scenery // layer that it was. if (!t_old_is_sprite && t_layer . id != 0) { // IM-2013-08-21: [[ ResIndependence ]] Use device coords for tilecache operation // IM-2013-09-30: [[ FullscreenMode ]] Use stack transform to get device coords MCTileCacheRemoveScenery(t_tiler, t_layer . id, t_layer . region); t_layer . id = 0; } t_layer . callback = testtilecache_device_sprite_renderer; MCTileCacheRenderSprite(t_tiler, t_layer); } else { // If the layer was a sprite before, remove the sprite // layer that it was. if (t_old_is_sprite && t_layer . id != 0) { MCTileCacheRemoveSprite(t_tiler, t_layer . id); t_layer . id = 0; } // MW-2013-10-29: [[ Bug 11349 ]] Scenery layers regions are clipped // by the clip directly. t_layer . region = MCRectangle32Intersect(t_layer . region, t_layer . clip); t_layer . callback = testtilecache_device_scenery_renderer; MCTileCacheRenderScenery(t_tiler, t_layer); } // Upate the id. t_control -> layer_setid(t_layer . id); // Advance to the object below. t_objptr = t_objptr -> prev(); } while(t_objptr != t_objptrs -> prev()); } // IM-2013-10-14: [[ FullscreenMode ]] Render the background into the card's visible area MCTileCacheLayer t_bg_layer; t_bg_layer . id = m_bg_layer_id; t_bg_layer . region = MCRectangle32GetTransformedBounds(t_visible_rect, t_transform); t_bg_layer . clip = t_bg_layer . region; t_bg_layer . is_opaque = true; t_bg_layer . opacity = 255; t_bg_layer . ink = GXblendSrcOver; t_bg_layer . callback = device_render_background; t_bg_layer . context = this; MCTileCacheRenderScenery(t_tiler, t_bg_layer); m_bg_layer_id = t_bg_layer . id; } //////////////////////////////////////////////////////////////////////////////// static bool s_screen_is_dirty = false; static bool s_screen_updates_disabled = false; bool MCRedrawIsScreenLocked(void) { return MClockscreen != 0; } void MCRedrawSaveLockScreen(uint2& r_lock) { r_lock = MClockscreen; } void MCRedrawRestoreLockScreen(uint2 p_lock) { MClockscreen = p_lock; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } void MCRedrawLockScreen(void) { MClockscreen++; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } void MCRedrawUnlockScreen(void) { if (MClockscreen == 0) return; MClockscreen--; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } void MCRedrawUnlockScreenWithEffects(void) { // MW-2011-09-20: [[ Bug ]] If the screen is unlocked, do nothing. if (MClockscreen == 0) return; MClockscreen--; if (MClockscreen == 0 && MCcur_effects != nil) { Boolean t_abort; // MW-2011-09-24: [[ Effects ]] Play an effect in the chosen rect. MCdefaultstackptr -> effectrect(MCcur_effects_rect, t_abort); } if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } void MCRedrawForceUnlockScreen(void) { MClockscreen = 0; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } //////////////////////////////////////////////////////////////////////////////// bool MCRedrawIsScreenDirty(void) { return s_screen_is_dirty; } void MCRedrawDirtyScreen(void) { MCStacknode *t_stacks; t_stacks = MCstacks -> topnode(); if (t_stacks == nil) return; // MW-2011-10-17: [[ Bug 9810 ]] Make sure we don't miss any stacks // (was previously looping back to t_stacks, not prev(t_stacks). MCStacknode *tptr = t_stacks->prev(); do { MCStack *sptr = tptr->getstack(); sptr -> view_dirty_all(); tptr = tptr->prev(); } while (tptr != t_stacks -> prev()); } void MCRedrawScheduleUpdateForStack(MCStack *stack) { s_screen_is_dirty = true; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } bool MCRedrawIsScreenUpdateEnabled(void) { return !s_screen_updates_disabled; } void MCRedrawDisableScreenUpdates(void) { s_screen_updates_disabled = true; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } void MCRedrawEnableScreenUpdates(void) { s_screen_updates_disabled = false; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } void MCRedrawDoUpdateScreen(void) { if (MClockscreen != 0) return; if (!s_screen_is_dirty) return; if (s_screen_updates_disabled) return; MCStacknode *t_stacks; t_stacks = MCstacks -> topnode(); if (t_stacks == nil) return; MCStacknode *tptr = t_stacks->prev(); do { MCStack *sptr = tptr->getstack(); if (sptr->getstate(CS_NEED_RESIZE)) { sptr->setgeom(); sptr->openrect(sptr->getrect(), WM_LAST, NULL, WP_DEFAULT, OP_NONE); MCRedrawUpdateScreen(); return; } sptr -> applyupdates(); tptr = tptr->prev(); } while (tptr != t_stacks->prev()); s_screen_is_dirty = false; if (MClockscreen == 0 && s_screen_is_dirty && !s_screen_updates_disabled) MCActionsSchedule(kMCActionsUpdateScreen); } ////////////////////////////////////////////////////////////////////////////////
LiveCodeSteven/livecode
engine/src/redraw.cpp
C++
gpl-3.0
45,371
var debug = require('debug')('openframe:model:Frame'); module.exports = function(Frame) { Frame.disableRemoteMethodByName('createChangeStream'); // Remove sensitive data from Artworks being returned // in public frames // Frame.afterRemote('**', function(ctx, resultInstance, next) { // debug('ctx.methodString', ctx.methodString); // function updateResult(result) { // if (result.current_artwork) { // let newArtwork = { // title: result.current_artwork.title, // author_name: result.current_artwork.author_name // }; // if (result.current_artwork.is_public) { // newArtwork.id = result.current_artwork.id; // } // result.current_artwork(newArtwork); // // debug(result.current_artwork); // } // } // if (ctx.result) { // if (Array.isArray(resultInstance)) { // debug('isArray', resultInstance.length); // ctx.result.forEach(function(result) { // updateResult(result); // }); // } else { // updateResult(ctx.result); // } // } // next(); // }); // Never save 'current_artwork' object into DB -- it comes from relation, via currentArtworkId // TODO: I think this is a(nother) loopback bug, since with strict on we should be enforcing // properties, but since this property is the name of a relation it's allowing it to be saved (?) Frame.observe('before save', function(ctx, next) { debug('before save', typeof ctx.instance); if (ctx.instance) { ctx.instance.unsetAttribute('current_artwork'); } else { delete ctx.data.current_artwork; } debug('before save - MODIFIED', ctx.instance); next(); }); // whenever a Frame model is saved, broadcast an update event Frame.observe('after save', function(ctx, next) { if (ctx.instance && Frame.app.pubsub) { debug('Saved %s %s', ctx.Model.modelName, ctx.instance.id); if (ctx.isNewInstance) { debug('New Frame, publishing: /user/' + ctx.instance.ownerId + '/frame/new'); Frame.app.pubsub.publish('/user/' + ctx.instance.ownerId + '/frame/new', ctx.instance.id); } else { debug('Existing Frame, publishing: /frame/' + ctx.instance.id + '/db_updated'); // debug(ctx.instance); Frame.findById(ctx.instance.id, { include: 'current_artwork' }, function(err, frame) { debug(err, frame); Frame.app.pubsub.publish('/frame/' + frame.id + '/db_updated', frame); }); } } next(); }); // Ouch. Ow. Yowsers. Serisously? function removeManagers(frame, managers) { return new Promise((resolve, reject) => { frame.managers(function(err, current_managers) { debug(current_managers); if (current_managers.length) { var count = 0, total = current_managers.length; current_managers.forEach(function(cur_man) { debug(cur_man); if (managers.indexOf(cur_man.username) === -1) { debug('removing %s', cur_man.username); frame.managers.remove(cur_man, function(err) { if (err) debug(err); count++; if (count === total) { // all who are no longer present in the new list have been removed resolve(); } }); } else { count++; if (count === total) { // all who are no longer present in the new list have been removed resolve(); } } }); } else { // there are no current managers resolve(); } }); }); } // Painful painful painful -- so gross. Why loopback, why!? function addManagers(frame, managers) { var OpenframeUser = Frame.app.models.OpenframeUser; return new Promise((resolve, reject) => { OpenframeUser.find({ where: { username: { inq: managers }}}, function(err, users) { if (err) { debug(err); } var count = 0, total = users.length; if (total === 0) { // no managers found by username, return frame including current managers Frame.findById(frame.id, {include: 'managers'}, function(err, frame) { debug(err, frame); resolve(frame); }); } else { // managers found by username, add them to frame, then // return frame including current managers // XXX: Unfortunately loopback doesn't seem to provide a way to batch // update hasAndBelongsToMany relationships :/ users.forEach(function(user) { frame.managers.add(user, function(err) { count++; if (count === total) { Frame.findById(frame.id, {include: 'managers'}, function(err, frame) { debug(err, frame); resolve(frame); }); } }); }); } }); }); } // Update managers by username // // XXX: This is incredibly ugly. Loopback doesn't provide a good way to update // this type of relationship all in one go, which makes it a huge messy pain. Given // time, I may fix this. Frame.prototype.update_managers_by_username = function(managers, cb) { debug(managers); var self = this; removeManagers(self, managers) .then(function() { addManagers(self, managers) .then(function(frame) { cb(null, frame); }) .catch(debug); }).catch(debug); }; // Expose update_managers_by_username remote method Frame.remoteMethod( 'prototype.update_managers_by_username', { description: 'Add a related item by username for managers.', accepts: { arg: 'managers', type: 'array', http: { source: 'body' } }, http: { verb: 'put', path: '/managers/by_username' }, returns: { arg: 'frame', type: 'Object' } } ); /** * Update the current artwork by artwork ID * @param {String} currentArtworkId * @param {Function} callback */ Frame.prototype.update_current_artwork = function(currentArtworkId, cb) { debug('update_current_artwork', currentArtworkId); var self = this; self.updateAttribute('currentArtworkId', currentArtworkId, function(err, instance) { cb(err, instance); }); }; Frame.remoteMethod( 'prototype.update_current_artwork', { description: 'Set the current artwork for this frame', accepts: { arg: 'currentArtworkId', type: 'any', required: true, http: { source: 'path' } }, http: { verb: 'put', path: '/current_artwork/:currentArtworkId' }, returns: { arg: 'frame', type: 'Object' } } ); /** * Override toJSON in order to remove inclusion of email address for users that are * not the currently logged-in user. * * @return {Object} Plain JS Object which will be transformed to JSON for output. */ // Frame.prototype.toJSON = function() { // // TODO: this seems awfully fragile... not very clear when context is available // var ctx = loopback.getCurrentContext(), // user = ctx.get('currentUser'), // userId = user && user.id, // obj = this.toObject(false, true, false); // debug('FRAME toJSON', userId, obj); // // Remove email from managers // if (obj.managers && obj.managers.length) { // obj.managers.forEach((manager) => { // delete manager.email; // }); // } // // Remove email from owner unless it's the currently logged in user. // if (obj.owner && userId !== obj.owner.id) { // delete obj.owner.email; // } // return obj; // }; };
OpenframeProject/Openframe-API
common/models/frame.js
JavaScript
gpl-3.0
9,543
#region Copyright & License Information /* * Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using OpenRA.FileFormats; using OpenRA.FileSystem; using OpenRA.Primitives; namespace OpenRA.Graphics { public struct VoxelRenderData { public readonly int Start; public readonly int Count; public readonly Sheet Sheet; public VoxelRenderData(int start, int count, Sheet sheet) { Start = start; Count = count; Sheet = sheet; } } public class VoxelLoader { SheetBuilder sheetBuilder; Cache<Pair<string,string>, Voxel> voxels; IVertexBuffer<Vertex> vertexBuffer; List<Vertex[]> vertices; int totalVertexCount; int cachedVertexCount; static SheetBuilder CreateSheetBuilder() { var allocated = false; Func<Sheet> allocate = () => { if (allocated) throw new SheetOverflowException(""); allocated = true; return SheetBuilder.AllocateSheet(); }; return new SheetBuilder(SheetType.DualIndexed, allocate); } public VoxelLoader() { voxels = new Cache<Pair<string,string>, Voxel>(LoadFile); vertices = new List<Vertex[]>(); totalVertexCount = 0; cachedVertexCount = 0; sheetBuilder = CreateSheetBuilder(); } static float[] channelSelect = { 0.75f, 0.25f, -0.25f, -0.75f }; Vertex[] GenerateSlicePlane(int su, int sv, Func<int,int,VxlElement> first, Func<int,int,VxlElement> second, Func<int, int, float[]> coord) { var colors = new byte[su*sv]; var normals = new byte[su*sv]; var c = 0; for (var v = 0; v < sv; v++) for (var u = 0; u < su; u++) { var voxel = first(u,v) ?? second(u,v); colors[c] = voxel == null ? (byte)0 : voxel.Color; normals[c] = voxel == null ? (byte)0 : voxel.Normal; c++; } var s = sheetBuilder.Allocate(new Size(su, sv)); Util.FastCopyIntoChannel(s, 0, colors); Util.FastCopyIntoChannel(s, 1, normals); s.sheet.CommitData(); var channelP =channelSelect[(int)s.channel]; var channelC = channelSelect[(int)s.channel + 1]; return new Vertex[4] { new Vertex(coord(0, 0), s.left, s.top, channelP, channelC), new Vertex(coord(su, 0),s.right, s.top, channelP, channelC), new Vertex(coord(su, sv), s.right, s.bottom, channelP, channelC), new Vertex(coord(0, sv), s.left, s.bottom, channelP, channelC) }; } IEnumerable<Vertex[]> GenerateSlicePlanes(VxlLimb l) { Func<int,int,int,VxlElement> get = (x,y,z) => { if (x < 0 || y < 0 || z < 0) return null; if (x >= l.Size[0] || y >= l.Size[1] || z >= l.Size[2]) return null; var v = l.VoxelMap[(byte)x,(byte)y]; if (v == null || !v.ContainsKey((byte)z)) return null; return l.VoxelMap[(byte)x,(byte)y][(byte)z]; }; // Cull slices without any visible faces var xPlanes = new bool[l.Size[0]+1]; var yPlanes = new bool[l.Size[1]+1]; var zPlanes = new bool[l.Size[2]+1]; for (var x = 0; x < l.Size[0]; x++) { for (var y = 0; y < l.Size[1]; y++) { for (var z = 0; z < l.Size[2]; z++) { if (get(x,y,z) == null) continue; // Only generate a plane if it is actually visible if (!xPlanes[x] && get(x-1,y,z) == null) xPlanes[x] = true; if (!xPlanes[x+1] && get(x+1,y,z) == null) xPlanes[x+1] = true; if (!yPlanes[y] && get(x,y-1,z) == null) yPlanes[y] = true; if (!yPlanes[y+1] && get(x,y+1,z) == null) yPlanes[y+1] = true; if (!zPlanes[z] && get(x,y,z-1) == null) zPlanes[z] = true; if (!zPlanes[z+1] && get(x,y,z+1) == null) zPlanes[z+1] = true; } } } for (var x = 0; x <= l.Size[0]; x++) if (xPlanes[x]) yield return GenerateSlicePlane(l.Size[1], l.Size[2], (u,v) => get(x, u, v), (u,v) => get(x - 1, u, v), (u,v) => new float[] {x, u, v}); for (var y = 0; y <= l.Size[1]; y++) if (yPlanes[y]) yield return GenerateSlicePlane(l.Size[0], l.Size[2], (u,v) => get(u, y, v), (u,v) => get(u, y - 1, v), (u,v) => new float[] {u, y, v}); for (var z = 0; z <= l.Size[2]; z++) if (zPlanes[z]) yield return GenerateSlicePlane(l.Size[0], l.Size[1], (u,v) => get(u, v, z), (u,v) => get(u, v, z - 1), (u,v) => new float[] {u, v, z}); } public VoxelRenderData GenerateRenderData(VxlLimb l) { Vertex[] v; try { v = GenerateSlicePlanes(l).SelectMany(x => x).ToArray(); } catch (SheetOverflowException) { // Sheet overflow - allocate a new sheet and try once more Log.Write("debug", "Voxel sheet overflow! Generating new sheet"); sheetBuilder.Current.ReleaseBuffer(); sheetBuilder = CreateSheetBuilder(); v = GenerateSlicePlanes(l).SelectMany(x => x).ToArray(); } vertices.Add(v); var start = totalVertexCount; var count = v.Length; totalVertexCount += count; return new VoxelRenderData(start, count, sheetBuilder.Current); } public void RefreshBuffer() { vertexBuffer = Game.Renderer.Device.CreateVertexBuffer(totalVertexCount); vertexBuffer.SetData(vertices.SelectMany(v => v).ToArray(), totalVertexCount); cachedVertexCount = totalVertexCount; } public IVertexBuffer<Vertex> VertexBuffer { get { if (cachedVertexCount != totalVertexCount) RefreshBuffer(); return vertexBuffer; } } Voxel LoadFile(Pair<string,string> files) { VxlReader vxl; HvaReader hva; using (var s = GlobalFileSystem.OpenWithExts(files.First, ".vxl")) vxl = new VxlReader(s); using (var s = GlobalFileSystem.OpenWithExts(files.Second, ".hva")) hva = new HvaReader(s); return new Voxel(this, vxl, hva); } public Voxel Load(string vxl, string hva) { return voxels[Pair.New(vxl, hva)]; } public void Finish() { sheetBuilder.Current.ReleaseBuffer(); } } }
penev92/OpenRA
OpenRA.Game/Graphics/VoxelLoader.cs
C#
gpl-3.0
6,140
/* This file is part of HSPlasma. * * HSPlasma 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. * * HSPlasma 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 HSPlasma. If not, see <http://www.gnu.org/licenses/>. */ #include <PyPlasma.h> #include <PRP/Geometry/plSpan.h> #include "pySpan.h" #include "PRP/KeyedObject/pyKey.h" #include "PRP/Region/pyBounds.h" #include "Stream/pyStream.h" #include "Math/pyMatrix.h" extern "C" { static void pySpan_dealloc(pySpan* self) { if (self->fPyOwned) delete self->fThis; Py_TYPE(self)->tp_free((PyObject*)self); } static int pySpan___init__(pySpan* self, PyObject* args, PyObject* kwds) { if (!PyArg_ParseTuple(args, "")) return -1; return 0; } static PyObject* pySpan_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { pySpan* self = (pySpan*)type->tp_alloc(type, 0); if (self != NULL) { self->fThis = new plSpan(); self->fPyOwned = true; } return (PyObject*)self; } static PyObject* pySpan_ClassName(pySpan* self) { return PyString_FromString(self->fThis->ClassName()); } static PyObject* pySpan_read(pySpan* self, PyObject* args) { pyStream* stream; if (!PyArg_ParseTuple(args, "O", &stream)) { PyErr_SetString(PyExc_TypeError, "read expects an hsStream"); return NULL; } if (!pyStream_Check((PyObject*)stream)) { PyErr_SetString(PyExc_TypeError, "read expects an hsStream"); return NULL; } self->fThis->read(stream->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_write(pySpan* self, PyObject* args) { pyStream* stream; if (!PyArg_ParseTuple(args, "O", &stream)) { PyErr_SetString(PyExc_TypeError, "write expects an hsStream"); return NULL; } if (!pyStream_Check((PyObject*)stream)) { PyErr_SetString(PyExc_TypeError, "write expects an hsStream"); return NULL; } self->fThis->write(stream->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_clearPermaLights(pySpan* self, PyObject* args) { self->fThis->clearPermaLights(); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_clearPermaProjs(pySpan* self, PyObject* args) { self->fThis->clearPermaProjs(); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_addPermaLight(pySpan* self, PyObject* args) { pyKey* key; if (!PyArg_ParseTuple(args, "O", &key)) { PyErr_SetString(PyExc_TypeError, "addPermaLight expects a plKey"); return NULL; } if (!pyKey_Check((PyObject*)key)) { PyErr_SetString(PyExc_TypeError, "addPermaLight expects a plKey"); return NULL; } self->fThis->addPermaLight(*key->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_addPermaProj(pySpan* self, PyObject* args) { pyKey* key; if (!PyArg_ParseTuple(args, "O", &key)) { PyErr_SetString(PyExc_TypeError, "addPermaProj expects a plKey"); return NULL; } if (!pyKey_Check((PyObject*)key)) { PyErr_SetString(PyExc_TypeError, "addPermaProj expects a plKey"); return NULL; } self->fThis->addPermaProj(*key->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_getFog(pySpan* self, void*) { return pyKey_FromKey(self->fThis->getFogEnvironment()); } static PyObject* pySpan_getLights(pySpan* self, void*) { PyObject* list = PyList_New(self->fThis->getPermaLights().size()); for (size_t i=0; i<self->fThis->getPermaLights().size(); i++) PyList_SET_ITEM(list, i, pyKey_FromKey(self->fThis->getPermaLights()[i])); return list; } static PyObject* pySpan_getProjs(pySpan* self, void*) { PyObject* list = PyList_New(self->fThis->getPermaProjs().size()); for (size_t i=0; i<self->fThis->getPermaProjs().size(); i++) PyList_SET_ITEM(list, i, pyKey_FromKey(self->fThis->getPermaProjs()[i])); return list; } static PyObject* pySpan_getL2W(pySpan* self, void*) { return pyMatrix44_FromMatrix44(self->fThis->getLocalToWorld()); } static PyObject* pySpan_getW2L(pySpan* self, void*) { return pyMatrix44_FromMatrix44(self->fThis->getWorldToLocal()); } static PyObject* pySpan_getSubType(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getSubType()); } static PyObject* pySpan_getMaterial(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getMaterialIdx()); } static PyObject* pySpan_getNumMatrices(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getNumMatrices()); } static PyObject* pySpan_getProps(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getProps()); } static PyObject* pySpan_getBaseMatrix(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getBaseMatrix()); } static PyObject* pySpan_getMaxBoneIdx(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getMaxBoneIdx()); } static PyObject* pySpan_getPenBoneIdx(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getPenBoneIdx()); } static PyObject* pySpan_getLocalUVWChans(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getLocalUVWChans()); } static PyObject* pySpan_getMinDist(pySpan* self, void*) { return PyFloat_FromDouble(self->fThis->getMinDist()); } static PyObject* pySpan_getMaxDist(pySpan* self, void*) { return PyFloat_FromDouble(self->fThis->getMaxDist()); } static PyObject* pySpan_getWaterHeight(pySpan* self, void*) { return PyFloat_FromDouble(self->fThis->getWaterHeight()); } static PyObject* pySpan_getLocalBounds(pySpan* self, void*) { return pyBounds3Ext_FromBounds3Ext(self->fThis->getLocalBounds()); } static PyObject* pySpan_getWorldBounds(pySpan* self, void*) { return pyBounds3Ext_FromBounds3Ext(self->fThis->getWorldBounds()); } static int pySpan_setFog(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyKey_Check(value)) { PyErr_SetString(PyExc_TypeError, "fog should be a plKey"); return -1; } self->fThis->setFogEnvironment(*((pyKey*)value)->fThis); return 0; } static int pySpan_setLights(pySpan* self, PyObject* value, void*) { PyErr_SetString(PyExc_RuntimeError, "To add Lights, use addPermaLight and addPermaProj"); return -1; } static int pySpan_setL2W(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyMatrix44_Check(value)) { PyErr_SetString(PyExc_TypeError, "localToWorld should be an hsMatrix44"); return -1; } self->fThis->setLocalToWorld(*((pyMatrix44*)value)->fThis); return 0; } static int pySpan_setW2L(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyMatrix44_Check(value)) { PyErr_SetString(PyExc_TypeError, "worldToLocal should be an hsMatrix44"); return -1; } self->fThis->setWorldToLocal(*((pyMatrix44*)value)->fThis); return 0; } static int pySpan_setSubType(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "subType should be an int"); return -1; } self->fThis->setSubType(PyInt_AsLong(value)); return 0; } static int pySpan_setMaterial(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "materialIdx should be an int"); return -1; } self->fThis->setMaterialIdx(PyInt_AsLong(value)); return 0; } static int pySpan_setNumMatrices(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "numMatrices should be an int"); return -1; } self->fThis->setNumMatrices(PyInt_AsLong(value)); return 0; } static int pySpan_setProps(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "props should be an int"); return -1; } self->fThis->setProps(PyInt_AsLong(value)); return 0; } static int pySpan_setBaseMatrix(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "baseMatrix should be an int"); return -1; } self->fThis->setBaseMatrix(PyInt_AsLong(value)); return 0; } static int pySpan_setMaxBoneIdx(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "maxBoneIdx should be an int"); return -1; } self->fThis->setMaxBoneIdx(PyInt_AsLong(value)); return 0; } static int pySpan_setPenBoneIdx(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "penBoneIdx should be an int"); return -1; } self->fThis->setPenBoneIdx(PyInt_AsLong(value)); return 0; } static int pySpan_setLocalUVWChans(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "localUVWChans should be an int"); return -1; } self->fThis->setLocalUVWChans(PyInt_AsLong(value)); return 0; } static int pySpan_setMinDist(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "minDist should be an int"); return -1; } self->fThis->setMinDist(PyFloat_AsDouble(value)); return 0; } static int pySpan_setMaxDist(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "maxDist should be an int"); return -1; } self->fThis->setMaxDist(PyFloat_AsDouble(value)); return 0; } static int pySpan_setWaterHeight(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "waterHeight should be an int"); return -1; } self->fThis->setWaterHeight(PyFloat_AsDouble(value)); return 0; } static int pySpan_setLocalBounds(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyBounds3Ext_Check(value)) { PyErr_SetString(PyExc_TypeError, "localBounds should be an hsBounds3Ext"); return -1; } self->fThis->setLocalBounds(*((pyBounds3Ext*)value)->fThis); return 0; } static int pySpan_setWorldBounds(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyBounds3Ext_Check(value)) { PyErr_SetString(PyExc_TypeError, "worldBounds should be an hsBounds3Ext"); return -1; } self->fThis->setWorldBounds(*((pyBounds3Ext*)value)->fThis); return 0; } static PyMethodDef pySpan_Methods[] = { { "ClassName", (PyCFunction)pySpan_ClassName, METH_NOARGS, "Returns the RTTI Class name of this Span object" }, { "read", (PyCFunction)pySpan_read, METH_VARARGS, "Params: stream\n" "Read this Span object from the stream" }, { "write", (PyCFunction)pySpan_write, METH_VARARGS, "Params: stream\n" "Write this Span object to the stream" }, { "clearPermaLights", (PyCFunction)pySpan_clearPermaLights, METH_NOARGS, "Remove all Perma Lights from this Span" }, { "clearPermaProjs", (PyCFunction)pySpan_clearPermaProjs, METH_NOARGS, "Remove all Perma Projs from this Span" }, { "addPermaLight", (PyCFunction)pySpan_addPermaLight, METH_VARARGS, "Params: key\n" "Add a Perma Light to the span" }, { "addPermaProj", (PyCFunction)pySpan_addPermaProj, METH_VARARGS, "Params: key\n" "Add a Perma Proj to the span" }, { NULL, NULL, 0, NULL } }; static PyGetSetDef pySpan_GetSet[] = { { _pycs("fog"), (getter)pySpan_getFog, (setter)pySpan_setFog, _pycs("Fog Environment key"), NULL }, { _pycs("permaLights"), (getter)pySpan_getLights, (setter)pySpan_setLights, NULL, NULL }, { _pycs("permaProjs"), (getter)pySpan_getProjs, (setter)pySpan_setLights, NULL, NULL }, { _pycs("localToWorld"), (getter)pySpan_getL2W, (setter)pySpan_setL2W, NULL, NULL }, { _pycs("worldToLocal"), (getter)pySpan_getW2L, (setter)pySpan_setW2L, NULL, NULL }, { _pycs("subType"), (getter)pySpan_getSubType, (setter)pySpan_setSubType, NULL, NULL }, { _pycs("materialIdx"), (getter)pySpan_getMaterial, (setter)pySpan_setMaterial, _pycs("Index of the material from the DrawableSpans to use"), NULL }, { _pycs("numMatrices"), (getter)pySpan_getNumMatrices, (setter)pySpan_setNumMatrices, NULL, NULL }, { _pycs("props"), (getter)pySpan_getProps, (setter)pySpan_setProps, NULL, NULL }, { _pycs("baseMatrix"), (getter)pySpan_getBaseMatrix, (setter)pySpan_setBaseMatrix, NULL, NULL }, { _pycs("maxBoneIdx"), (getter)pySpan_getMaxBoneIdx, (setter)pySpan_setMaxBoneIdx, NULL, NULL }, { _pycs("penBoneIdx"), (getter)pySpan_getPenBoneIdx, (setter)pySpan_setPenBoneIdx, NULL, NULL }, { _pycs("localUVWChans"), (getter)pySpan_getLocalUVWChans, (setter)pySpan_setLocalUVWChans, NULL, NULL }, { _pycs("minDist"), (getter)pySpan_getMinDist, (setter)pySpan_setMinDist, NULL, NULL }, { _pycs("maxDist"), (getter)pySpan_getMaxDist, (setter)pySpan_setMaxDist, NULL, NULL }, { _pycs("waterHeight"), (getter)pySpan_getWaterHeight, (setter)pySpan_setWaterHeight, NULL, NULL }, { _pycs("localBounds"), (getter)pySpan_getLocalBounds, (setter)pySpan_setLocalBounds, NULL, NULL }, { _pycs("worldBounds"), (getter)pySpan_getWorldBounds, (setter)pySpan_setWorldBounds, NULL, NULL }, { NULL, NULL, NULL, NULL, NULL } }; PyTypeObject pySpan_Type = { PyVarObject_HEAD_INIT(NULL, 0) "PyHSPlasma.plSpan", /* tp_name */ sizeof(pySpan), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pySpan_dealloc, /* tp_dealloc */ NULL, /* tp_print */ NULL, /* tp_getattr */ NULL, /* tp_setattr */ NULL, /* tp_compare */ NULL, /* tp_repr */ NULL, /* tp_as_number */ NULL, /* tp_as_sequence */ NULL, /* tp_as_mapping */ NULL, /* tp_hash */ NULL, /* tp_call */ NULL, /* tp_str */ NULL, /* tp_getattro */ NULL, /* tp_setattro */ NULL, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "plSpan wrapper", /* tp_doc */ NULL, /* tp_traverse */ NULL, /* tp_clear */ NULL, /* tp_richcompare */ 0, /* tp_weaklistoffset */ NULL, /* tp_iter */ NULL, /* tp_iternext */ pySpan_Methods, /* tp_methods */ NULL, /* tp_members */ pySpan_GetSet, /* tp_getset */ NULL, /* tp_base */ NULL, /* tp_dict */ NULL, /* tp_descr_get */ NULL, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)pySpan___init__, /* tp_init */ NULL, /* tp_alloc */ pySpan_new, /* tp_new */ NULL, /* tp_free */ NULL, /* tp_is_gc */ NULL, /* tp_bases */ NULL, /* tp_mro */ NULL, /* tp_cache */ NULL, /* tp_subclasses */ NULL, /* tp_weaklist */ NULL, /* tp_del */ TP_VERSION_TAG_INIT /* tp_version_tag */ TP_FINALIZE_INIT /* tp_finalize */ }; PyObject* Init_pySpan_Type() { if (PyType_Ready(&pySpan_Type) < 0) return NULL; PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteMaterial", PyInt_FromLong(plSpan::kLiteMaterial)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropNoDraw", PyInt_FromLong(plSpan::kPropNoDraw)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropNoShadowCast", PyInt_FromLong(plSpan::kPropNoShadowCast)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropFacesSortable", PyInt_FromLong(plSpan::kPropFacesSortable)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropVolatile", PyInt_FromLong(plSpan::kPropVolatile)); PyDict_SetItemString(pySpan_Type.tp_dict, "kWaterHeight", PyInt_FromLong(plSpan::kWaterHeight)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropRunTimeLight", PyInt_FromLong(plSpan::kPropRunTimeLight)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropReverseSort", PyInt_FromLong(plSpan::kPropReverseSort)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropHasPermaLights", PyInt_FromLong(plSpan::kPropHasPermaLights)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropHasPermaProjs", PyInt_FromLong(plSpan::kPropHasPermaProjs)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteVtxPreshaded", PyInt_FromLong(plSpan::kLiteVtxPreshaded)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteVtxNonPreshaded", PyInt_FromLong(plSpan::kLiteVtxNonPreshaded)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteProjection", PyInt_FromLong(plSpan::kLiteProjection)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteShadowErase", PyInt_FromLong(plSpan::kLiteShadowErase)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteShadow", PyInt_FromLong(plSpan::kLiteShadow)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropMatHasSpecular", PyInt_FromLong(plSpan::kPropMatHasSpecular)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropProjAsVtx", PyInt_FromLong(plSpan::kPropProjAsVtx)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropSkipProjection", PyInt_FromLong(plSpan::kPropSkipProjection)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropNoShadow", PyInt_FromLong(plSpan::kPropNoShadow)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropForceShadow", PyInt_FromLong(plSpan::kPropForceShadow)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropDisableNormal", PyInt_FromLong(plSpan::kPropDisableNormal)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropCharacter", PyInt_FromLong(plSpan::kPropCharacter)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPartialSort", PyInt_FromLong(plSpan::kPartialSort)); PyDict_SetItemString(pySpan_Type.tp_dict, "kVisLOS", PyInt_FromLong(plSpan::kVisLOS)); // plSpanType PyDict_SetItemString(pySpan_Type.tp_dict, "kSpan", PyInt_FromLong(plSpan::kSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kVertexSpan", PyInt_FromLong(plSpan::kVertexSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kIcicleSpan", PyInt_FromLong(plSpan::kIcicleSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kNullSpan", PyInt_FromLong(plSpan::kNullSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kParticleSpan", PyInt_FromLong(plSpan::kParticleSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kParticleSet", PyInt_FromLong(plSpan::kParticleSet)); Py_INCREF(&pySpan_Type); return (PyObject*)&pySpan_Type; } int pySpan_Check(PyObject* obj) { if (obj->ob_type == &pySpan_Type || PyType_IsSubtype(obj->ob_type, &pySpan_Type)) return 1; return 0; } PyObject* pySpan_FromSpan(plSpan* span) { if (span == NULL) { Py_INCREF(Py_None); return Py_None; } pySpan* obj = PyObject_New(pySpan, &pySpan_Type); obj->fThis = span; obj->fPyOwned = false; return (PyObject*)obj; } }
diafero/libhsplasma
Python/PRP/Geometry/pySpan.cpp
C++
gpl-3.0
21,397
package org.zarroboogs.weibo.hot.bean.hotweibo; import org.json.*; import java.util.ArrayList; public class HotWeibo { private CardlistInfo cardlistInfo; private ArrayList<Cards> cards; public HotWeibo() { } public HotWeibo(JSONObject json) { this.cardlistInfo = new CardlistInfo(json.optJSONObject("cardlistInfo")); this.cards = new ArrayList<Cards>(); JSONArray arrayCards = json.optJSONArray("cards"); if (null != arrayCards) { int cardsLength = arrayCards.length(); for (int i = 0; i < cardsLength; i++) { JSONObject item = arrayCards.optJSONObject(i); if (null != item) { this.cards.add(new Cards(item)); } } } else { JSONObject item = json.optJSONObject("cards"); if (null != item) { this.cards.add(new Cards(item)); } } } public CardlistInfo getCardlistInfo() { return this.cardlistInfo; } public void setCardlistInfo(CardlistInfo cardlistInfo) { this.cardlistInfo = cardlistInfo; } public ArrayList<Cards> getCards() { return this.cards; } public void setCards(ArrayList<Cards> cards) { this.cards = cards; } }
andforce/iBeebo
app/src/main/java/org/zarroboogs/weibo/hot/bean/hotweibo/HotWeibo.java
Java
gpl-3.0
1,329
UMI.CMS 15 = a681fe704f6e1c131ab39f8a2cb92d1a
gohdan/DFC
known_files/hashes/sys-temp/updates/emarket/classes/modules/emarket/classes/orders/order.php
PHP
gpl-3.0
46
import web import sam.common import sam.models.links class Details: def __init__(self, db, subscription, ds, address, timestamp_range=None, port=None, page_size=50): self.db = db self.sub = subscription self.table_nodes = "s{acct}_Nodes".format(acct=self.sub) self.table_links = "s{acct}_ds{id}_Links".format(acct=self.sub, id=ds) self.table_links_in = "s{acct}_ds{id}_LinksIn".format(acct=self.sub, id=ds) self.table_links_out = "s{acct}_ds{id}_LinksOut".format(acct=self.sub, id=ds) self.ds = ds self.ip_start, self.ip_end = sam.common.determine_range_string(address) self.page_size = page_size self.port = port if timestamp_range: self.time_range = timestamp_range else: linksModel = sam.models.links.Links(db, self.sub, self.ds) tr = linksModel.get_timerange() self.time_range = (tr['min'], tr['max']) if self.db.dbname == 'mysql': self.elapsed = '(UNIX_TIMESTAMP(MAX(timestamp)) - UNIX_TIMESTAMP(MIN(timestamp)))' self.divop = 'DIV' else: self.elapsed = '(MAX(timestamp) - MIN(timestamp))' self.divop = '/' sam.common.sqlite_udf(self.db) def get_metadata(self): qvars = {"start": self.ip_start, "end": self.ip_end} # TODO: seconds has a magic number 300 added to account for DB time quantization. query = """ SELECT {address_q} AS 'address' , COALESCE(n.hostname, '') AS 'hostname' , COALESCE(l_out.unique_out_ip, 0) AS 'unique_out_ip' , COALESCE(l_out.unique_out_conn, 0) AS 'unique_out_conn' , COALESCE(l_out.total_out, 0) AS 'total_out' , COALESCE(l_out.b_s, 0) AS 'out_bytes_sent' , COALESCE(l_out.b_r, 0) AS 'out_bytes_received' , COALESCE(l_out.max_bps, 0) AS 'out_max_bps' , COALESCE(l_out.sum_b * 1.0 / l_out.sum_duration, 0) AS 'out_avg_bps' , COALESCE(l_out.p_s, 0) AS 'out_packets_sent' , COALESCE(l_out.p_r, 0) AS 'out_packets_received' , COALESCE(l_out.sum_duration * 1.0 / l_out.total_out, 0) AS 'out_duration' , COALESCE(l_in.unique_in_ip, 0) AS 'unique_in_ip' , COALESCE(l_in.unique_in_conn, 0) AS 'unique_in_conn' , COALESCE(l_in.total_in, 0) AS 'total_in' , COALESCE(l_in.b_s, 0) AS 'in_bytes_sent' , COALESCE(l_in.b_r, 0) AS 'in_bytes_received' , COALESCE(l_in.max_bps, 0) AS 'in_max_bps' , COALESCE(l_in.sum_b * 1.0 / l_in.sum_duration, 0) AS 'in_avg_bps' , COALESCE(l_in.p_s, 0) AS 'in_packets_sent' , COALESCE(l_in.p_r, 0) AS 'in_packets_received' , COALESCE(l_in.sum_duration * 1.0 / l_in.total_in, 0) AS 'in_duration' , COALESCE(l_in.ports_used, 0) AS 'ports_used' , children.endpoints AS 'endpoints' , COALESCE(t.seconds, 0) + 300 AS 'seconds' , (COALESCE(l_in.sum_b, 0) + COALESCE(l_out.sum_b, 0)) / (COALESCE(t.seconds, 0) + 300) AS 'overall_bps' , COALESCE(l_in.protocol, "") AS 'in_protocols' , COALESCE(l_out.protocol, "") AS 'out_protocols' FROM ( SELECT ipstart, subnet, alias AS 'hostname' FROM {nodes_table} WHERE ipstart = $start AND ipend = $end ) AS n LEFT JOIN ( SELECT $start AS 's1' , COUNT(DISTINCT dst) AS 'unique_out_ip' , (SELECT COUNT(1) FROM (SELECT DISTINCT src, dst, port FROM {links_table} WHERE src BETWEEN $start AND $end) AS `temp1`) AS 'unique_out_conn' , SUM(links) AS 'total_out' , SUM(bytes_sent) AS 'b_s' , SUM(bytes_received) AS 'b_r' , MAX((bytes_sent + bytes_received) * 1.0 / duration) AS 'max_bps' , SUM(bytes_sent + bytes_received) AS 'sum_b' , SUM(packets_sent) AS 'p_s' , SUM(packets_received) AS 'p_r' , SUM(duration * links) AS 'sum_duration' , GROUP_CONCAT(DISTINCT protocol) AS 'protocol' FROM {links_table} WHERE src BETWEEN $start AND $end GROUP BY 's1' ) AS l_out ON n.ipstart = l_out.s1 LEFT JOIN ( SELECT $start AS 's1' , COUNT(DISTINCT src) AS 'unique_in_ip' , (SELECT COUNT(1) FROM (SELECT DISTINCT src, dst, port FROM {links_table} WHERE dst BETWEEN $start AND $end) AS `temp2`) AS 'unique_in_conn' , SUM(links) AS 'total_in' , SUM(bytes_sent) AS 'b_s' , SUM(bytes_received) AS 'b_r' , MAX((bytes_sent + bytes_received) * 1.0 / duration) AS 'max_bps' , SUM(bytes_sent + bytes_received) AS 'sum_b' , SUM(packets_sent) AS 'p_s' , SUM(packets_received) AS 'p_r' , SUM(duration * links) AS 'sum_duration' , COUNT(DISTINCT port) AS 'ports_used' , GROUP_CONCAT(DISTINCT protocol) AS 'protocol' FROM {links_table} WHERE dst BETWEEN $start AND $end GROUP BY 's1' ) AS l_in ON n.ipstart = l_in.s1 LEFT JOIN ( SELECT $start AS 's1' , COUNT(ipstart) AS 'endpoints' FROM {nodes_table} WHERE ipstart = ipend AND ipstart BETWEEN $start AND $end ) AS children ON n.ipstart = children.s1 LEFT JOIN ( SELECT $start AS 's1' , {elapsed} AS 'seconds' FROM {links_table} GROUP BY 's1' ) AS t ON n.ipstart = t.s1 LIMIT 1; """.format( address_q=sam.common.db_concat(self.db, 'decodeIP(n.ipstart)', "'/'", 'n.subnet'), elapsed=self.elapsed, nodes_table=self.table_nodes, links_table=self.table_links) results = self.db.query(query, vars=qvars) first = results.first() if first: return first else: return {} def build_where_clause(self, timestamp_range=None, port=None, protocol=None, rounding=True): """ Build a WHERE SQL clause that covers basic timerange, port, and protocol filtering. :param timestamp_range: start and end times as unix timestamps (integers). Default is all time. :type timestamp_range: tuple[int, int] :param port: exclusively report traffic destined for this port, if specified. :type port: int or str :param protocol: exclusively report traffic using this protocol :type protocol: str :param rounding: round each time stamp to the nearest quantization mark. (db records are quantized for consiceness) :type rounding: bool :return: String SQL clause :rtype: str """ clauses = [] t_start = 0 t_end = 0 if timestamp_range: t_start = timestamp_range[0] t_end = timestamp_range[1] if rounding: # rounding to 5 minutes, for use with the Syslog table if t_start > 150: t_start -= 150 if t_end <= 2 ** 31 - 150: t_end += 149 if self.db.dbname == 'sqlite': clauses.append("timestamp BETWEEN $tstart AND $tend") else: clauses.append("timestamp BETWEEN FROM_UNIXTIME($tstart) AND FROM_UNIXTIME($tend)") if port: clauses.append("port = $port") if protocol: clauses.append("protocols LIKE $protocol") protocol = "%{0}%".format(protocol) qvars = {'tstart': t_start, 'tend': t_end, 'port': port, 'protocol': protocol} where = str(web.db.reparam("\n AND ".join(clauses), qvars)) if where: where = " AND " + where return where def get_details_connections(self, inbound, page=1, order="-links", simple=False): sort_options = ['links', 'src', 'dst', 'port', 'sum_bytes', 'sum_packets', 'protocols', 'avg_duration'] sort_options_simple = ['links', 'src', 'dst', 'port'] qvars = { 'table_links': self.table_links, 'start': self.ip_start, 'end': self.ip_end, 'page': self.page_size * (page - 1), 'page_size': self.page_size, 'WHERE': self.build_where_clause(self.time_range, self.port) } if inbound: qvars['collected'] = "src" qvars['filtered'] = "dst" else: qvars['filtered'] = "src" qvars['collected'] = "dst" # determine the sort direction if order and order[0] == '-': sort_dir = "DESC" else: sort_dir = "ASC" # determine the sort column if simple: if order and order[1:] in sort_options_simple: sort_by = order[1:] else: sort_by = sort_options_simple[0] else: if order and order[1:] in sort_options: sort_by = order[1:] else: sort_by = sort_options[0] # add table prefix for some columns if sort_by in ['port', 'src', 'dst']: sort_by = "`links`." + sort_by qvars['order'] = "{0} {1}".format(sort_by, sort_dir) if simple: query = """ SELECT decodeIP({collected}) AS '{collected}' , port AS 'port' , sum(links) AS 'links' FROM {table_links} AS `links` WHERE {filtered} BETWEEN $start AND $end {WHERE} GROUP BY `links`.{collected}, `links`.port ORDER BY {order} LIMIT {page}, {page_size} """.format(**qvars) else: query = """ SELECT src, dst, port, links, protocols , sum_bytes , (sum_bytes / links) AS 'avg_bytes' , sum_packets , (sum_packets / links) AS 'avg_packets' , avg_duration FROM( SELECT decodeIP(src) AS 'src' , decodeIP(dst) AS 'dst' , port AS 'port' , SUM(links) AS 'links' , GROUP_CONCAT(DISTINCT protocol) AS 'protocols' , SUM(bytes_sent + COALESCE(bytes_received, 0)) AS 'sum_bytes' , SUM(packets_sent + COALESCE(packets_received, 0)) AS 'sum_packets' , SUM(duration*links) / SUM(links) AS 'avg_duration' FROM {table_links} AS `links` WHERE {filtered} BETWEEN $start AND $end {WHERE} GROUP BY `links`.src, `links`.dst, `links`.port ORDER BY {order} LIMIT {page}, {page_size} ) AS precalc; """.format(**qvars) return list(self.db.query(query, vars=qvars)) def get_details_ports(self, page=1, order="-links"): sort_options = ['links', 'port'] first_result = (page - 1) * self.page_size qvars = { 'links_table': self.table_links, 'start': self.ip_start, 'end': self.ip_end, 'first': first_result, 'size': self.page_size, 'WHERE': self.build_where_clause(self.time_range, self.port), } if order and order[0] == '-': sort_dir = "DESC" else: sort_dir = "ASC" if order and order[1:] in sort_options: sort_by = order[1:] else: sort_by = sort_options[0] qvars['order'] = "{0} {1}".format(sort_by, sort_dir) query = """ SELECT port AS 'port', sum(links) AS 'links' FROM {links_table} WHERE dst BETWEEN $start AND $end {WHERE} GROUP BY port ORDER BY {order} LIMIT $first, $size; """.format(**qvars) return list(sam.common.db.query(query, vars=qvars)) def get_details_children(self, order='+ipstart'): sort_options = ['ipstart', 'hostname', 'endpoints', 'ratio'] ip_diff = self.ip_end - self.ip_start if ip_diff == 0: return [] elif ip_diff == 255: quotient = 1 child_subnet_start = 25 child_subnet_end = 32 elif ip_diff == 65535: quotient = 256 child_subnet_start = 17 child_subnet_end = 24 elif ip_diff == 16777215: quotient = 65536 child_subnet_start = 9 child_subnet_end = 16 else: quotient = 16777216 child_subnet_start = 1 child_subnet_end = 8 qvars = {'ip_start': self.ip_start, 'ip_end': self.ip_end, 's_start': child_subnet_start, 's_end': child_subnet_end, 'quot': quotient, 'quot_1': quotient - 1} if order and order[0] == '-': sort_dir = "DESC" else: sort_dir = "ASC" if order and order[1:] in sort_options: sort_by = order[1:] else: sort_by = sort_options[0] qvars['order'] = "{0} {1}".format(sort_by, sort_dir) query = """ SELECT decodeIP(`n`.ipstart) AS 'address' , COALESCE(`n`.alias, '') AS 'hostname' , `n`.subnet AS 'subnet' , `sn`.kids AS 'endpoints' , COALESCE(COALESCE(`l_in`.links,0) / (COALESCE(`l_in`.links,0) + COALESCE(`l_out`.links,0)), 0) AS 'ratio' FROM {nodes_table} AS `n` LEFT JOIN ( SELECT dst_start {div} $quot * $quot AS 'low' , dst_end {div} $quot * $quot + $quot_1 AS 'high' , sum(links) AS 'links' FROM {links_in_table} GROUP BY low, high ) AS `l_in` ON `l_in`.low = `n`.ipstart AND `l_in`.high = `n`.ipend LEFT JOIN ( SELECT src_start {div} $quot * $quot AS 'low' , src_end {div} $quot * $quot + $quot_1 AS 'high' , sum(links) AS 'links' FROM {links_out_table} GROUP BY low, high ) AS `l_out` ON `l_out`.low = `n`.ipstart AND `l_out`.high = `n`.ipend LEFT JOIN ( SELECT ipstart {div} $quot * $quot AS 'low' , ipend {div} $quot * $quot + $quot_1 AS 'high' , COUNT(ipstart) AS 'kids' FROM {nodes_table} WHERE ipstart = ipend GROUP BY low, high ) AS `sn` ON `sn`.low = `n`.ipstart AND `sn`.high = `n`.ipend WHERE `n`.ipstart BETWEEN $ip_start AND $ip_end AND `n`.subnet BETWEEN $s_start AND $s_end ORDER BY {order}; """.format(div=self.divop, order=qvars['order'], nodes_table=self.table_nodes, links_in_table=self.table_links_in, links_out_table=self.table_links_out) return list(sam.common.db.query(query, vars=qvars)) def get_details_summary(self): where = self.build_where_clause(timestamp_range=self.time_range, port=self.port) # TODO: seconds has a magic number 300 added to account for DB time quantization. query = """ SELECT `inputs`.ips AS 'unique_in' , `outputs`.ips AS 'unique_out' , `inputs`.ports AS 'unique_ports' FROM (SELECT COUNT(DISTINCT src) AS 'ips', COUNT(DISTINCT port) AS 'ports' FROM {links_table} WHERE dst BETWEEN $start AND $end {where} ) AS `inputs` JOIN (SELECT COUNT(DISTINCT dst) AS 'ips' FROM {links_table} WHERE src BETWEEN $start AND $end {where} ) AS `outputs`;""".format(where=where, links_table=self.table_links) qvars = {'start': self.ip_start, 'end': self.ip_end} rows = sam.common.db.query(query, vars=qvars) return rows.first()
riolet/SAM
sam/models/details.py
Python
gpl-3.0
16,289
define( [ 'views/AlertMessageView', 'lib/Mediator' ], function (AlertMessageView, Mediator) { describe('AlertMessageView', function () { var resultsCollection, view, mediator; beforeEach(function () { resultsCollection = new Backbone.Collection(); mediator = new Mediator(); }); it('should initially be hidden', function () { view = new AlertMessageView().render(); expect(view.$el.find('.alert')).toHaveClass('hidden'); }); it('should become visible when a new message arrives', function () { view = new AlertMessageView(); view.setMediator(mediator); mediator.trigger('app:alert', {title: 'x', content: 'y'}); expect(view.$el.find('.alert')).not.toHaveClass('hidden'); }); it('should close it when a user clicks the X', function () { view = new AlertMessageView().render(); view.setMediator(mediator); view.removeAlertMessage(); expect(view.$el.find('.alert')).toHaveClass('hidden'); }); }); });
nsidc/search-interface
spec/views/AlertMessageView_spec.js
JavaScript
gpl-3.0
1,079
(function (angular) { 'use strict'; describe('adminStoreApi', function () { var $firebaseObjectMock; var firebaseObjectResult; var firebaseRef; var adminStoreApi; beforeEach(module('movieClub')); beforeEach(function () { firebaseObjectResult = {'$loaded': angular.noop}; $firebaseObjectMock = jasmine.createSpy('$firebaseObject'); $firebaseObjectMock.and.returnValue(firebaseObjectResult); module(function ($provide) { $provide.value('$firebaseObject', $firebaseObjectMock); }); }); beforeEach(inject(function (_firebaseRef_, _adminStoreApi_) { firebaseRef = _firebaseRef_; adminStoreApi = _adminStoreApi_; })); describe('get', function () { it('should get a firebase adminStore object', function () { spyOn(firebaseRef, 'child'); adminStoreApi.get(); expect(firebaseRef.child).toHaveBeenCalledWith('adminStore'); }); }); }); }(window.angular));
BrandonCKrueger/movie-club
src/adminStore/adminStoreApi.service.spec.js
JavaScript
gpl-3.0
1,129
/** * Copyright (c) 2006-2016 LOVE 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. **/ // LOVE #include "filesystem/wrap_Filesystem.h" #include "theora/Video.h" #include "wrap_Video.h" #include "wrap_VideoStream.h" namespace love { namespace video { #define instance() (Module::getInstance<Video>(Module::M_VIDEO)) int w_newVideoStream(lua_State *L) { love::filesystem::File *file = love::filesystem::luax_getfile(L, 1); VideoStream *stream = nullptr; luax_catchexcept(L, [&]() { // Can't check if open for reading if (!file->isOpen() && !file->open(love::filesystem::File::MODE_READ)) luaL_error(L, "File is not open and cannot be opened"); stream = instance()->newVideoStream(file); }); luax_pushtype(L, VIDEO_VIDEO_STREAM_ID, stream); stream->release(); return 1; } static const lua_CFunction types[] = { luaopen_videostream, 0 }; static const luaL_Reg functions[] = { { "newVideoStream", w_newVideoStream }, { 0, 0 } }; extern "C" int luaopen_love_video(lua_State *L) { Video *instance = instance(); if (instance == nullptr) { luax_catchexcept(L, [&](){ instance = new love::video::theora::Video(); }); } else instance->retain(); WrappedModule w; w.module = instance; w.name = "video"; w.type = MODULE_ID; w.functions = functions; w.types = types; return luax_register_module(L, w); } } // video } // love
RobLoach/love
src/modules/video/wrap_Video.cpp
C++
gpl-3.0
2,196
package generated.glib20.glib; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Library; import org.bridj.ann.Ptr; @Library("glib-2.0") public class GAsyncQueue extends StructObject { static { BridJ.register(); } public GAsyncQueue() { super(); } public GAsyncQueue(Pointer pointer) { super(pointer); } protected native int g_async_queue_length( @Ptr long queue); public int length() { return this.g_async_queue_length(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native int g_async_queue_length_unlocked( @Ptr long queue); public int length_unlocked() { return this.g_async_queue_length_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_lock( @Ptr long queue); public void lock() { this.g_async_queue_lock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected native long g_async_queue_pop( @Ptr long queue); public Pointer pop() { return Pointer.pointerToAddress(this.g_async_queue_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } @Ptr protected native long g_async_queue_pop_unlocked( @Ptr long queue); public Pointer pop_unlocked() { return Pointer.pointerToAddress(this.g_async_queue_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_push( @Ptr long queue, @Ptr long data); public void push(Pointer data) { this.g_async_queue_push(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data)); } protected native void g_async_queue_push_unlocked( @Ptr long queue, @Ptr long data); public void push_unlocked(Pointer data) { this.g_async_queue_push_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data)); } @Ptr protected native long g_async_queue_ref( @Ptr long queue); public Pointer ref() { return Pointer.pointerToAddress(this.g_async_queue_ref(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_ref_unlocked( @Ptr long queue); public void ref_unlocked() { this.g_async_queue_ref_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected native long g_async_queue_timed_pop( @Ptr long queue, @Ptr long end_time); public Pointer timed_pop(Pointer end_time) { return Pointer.pointerToAddress(this.g_async_queue_timed_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(end_time))); } @Ptr protected native long g_async_queue_timed_pop_unlocked( @Ptr long queue, @Ptr long end_time); public Pointer timed_pop_unlocked(Pointer end_time) { return Pointer.pointerToAddress(this.g_async_queue_timed_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(end_time))); } @Ptr protected native long g_async_queue_timeout_pop( @Ptr long queue, long timeout); public Pointer timeout_pop(long timeout) { return Pointer.pointerToAddress(this.g_async_queue_timeout_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), timeout)); } @Ptr protected native long g_async_queue_timeout_pop_unlocked( @Ptr long queue, long timeout); public Pointer timeout_pop_unlocked(long timeout) { return Pointer.pointerToAddress(this.g_async_queue_timeout_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), timeout)); } @Ptr protected native long g_async_queue_try_pop( @Ptr long queue); public Pointer try_pop() { return Pointer.pointerToAddress(this.g_async_queue_try_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } @Ptr protected native long g_async_queue_try_pop_unlocked( @Ptr long queue); public Pointer try_pop_unlocked() { return Pointer.pointerToAddress(this.g_async_queue_try_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_unlock( @Ptr long queue); public void unlock() { this.g_async_queue_unlock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_unref( @Ptr long queue); public void unref() { this.g_async_queue_unref(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_unref_and_unlock( @Ptr long queue); public void unref_and_unlock() { this.g_async_queue_unref_and_unlock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected static native long g_async_queue_new(); public static Pointer _new() { return Pointer.pointerToAddress(GAsyncQueue.g_async_queue_new()); } @Ptr protected static native long g_async_queue_new_full( @Ptr long item_free_func); public static Pointer<GAsyncQueue> new_full(Pointer item_free_func) { return Pointer.pointerToAddress(GAsyncQueue.g_async_queue_new_full(Pointer.getPeer(item_free_func)), GAsyncQueue.class); } protected native void g_async_queue_push_sorted( @Ptr long queue, @Ptr long data, @Ptr long func, @Ptr long user_data); public void push_sorted(Pointer data, Pointer func, Pointer user_data) { this.g_async_queue_push_sorted(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_push_sorted_unlocked( @Ptr long queue, @Ptr long data, @Ptr long func, @Ptr long user_data); public void push_sorted_unlocked(Pointer data, Pointer func, Pointer user_data) { this.g_async_queue_push_sorted_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_sort_unlocked( @Ptr long queue, @Ptr long func, @Ptr long user_data); public void sort_unlocked(Pointer func, Pointer user_data) { this.g_async_queue_sort_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_sort( @Ptr long queue, @Ptr long func, @Ptr long user_data); public void sort(Pointer func, Pointer user_data) { this.g_async_queue_sort(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(func), Pointer.getPeer(user_data)); } }
gstreamer-java/gir2java
generated-src/generated/glib20/glib/GAsyncQueue.java
Java
gpl-3.0
7,257
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Module.StaticPage")] [assembly: AssemblyDescription("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("62aecc0e-a75d-4491-948b-683af516b273")]
tech-nik89/website-builder
src/Module.StaticPage/Properties/AssemblyInfo.cs
C#
gpl-3.0
493
using Nikse.SubtitleEdit.Core.Common; using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Nikse.SubtitleEdit.Core.SubtitleFormats { public class UnknownSubtitle70 : SubtitleFormat { private static readonly Regex RegexMicroDvdLine = new Regex(@"^\[-?\d+\]\[-?\d+\].*$", RegexOptions.Compiled); public string Errors { get; private set; } private StringBuilder _errors; private int _lineNumber; public override string Extension => ".txt"; public override string Name => "Unknown 70"; public override bool IsTimeBased => false; public override bool IsMine(List<string> lines, string fileName) { int totalRead = 0; int errors = 0; foreach (string line in lines) { if (string.IsNullOrWhiteSpace(line)) { continue; } if (line.Contains('[')) { string s = RemoveIllegalSpacesAndFixEmptyCodes(line); if (RegexMicroDvdLine.IsMatch(s)) { totalRead++; } else { errors++; } } else { errors++; } } Errors = null; return totalRead > errors; } private static string RemoveIllegalSpacesAndFixEmptyCodes(string line) { if (string.IsNullOrEmpty(line) || line.Length > 2000) { return line; } int index = line.IndexOf(']'); if (index >= 0 && index < line.Length) { index = line.IndexOf(']', index + 1); if (index >= 0 && index + 1 < line.Length) { var indexOfBrackets = line.IndexOf("[]", StringComparison.Ordinal); if (indexOfBrackets >= 0 && indexOfBrackets < index) { line = line.Insert(indexOfBrackets + 1, "0"); // set empty time codes to zero index++; } while (line.Contains(' ') && line.IndexOf(' ') < index) { line = line.Remove(line.IndexOf(' '), 1); index--; } } } return line; } public override string ToText(Subtitle subtitle, string title) { var sb = new StringBuilder(); foreach (Paragraph p in subtitle.Paragraphs) { sb.Append('['); sb.Append(MillisecondsToFrames(p.StartTime.TotalMilliseconds)); sb.Append("]["); sb.Append(MillisecondsToFrames(p.EndTime.TotalMilliseconds)); sb.Append(']'); //{y:b} is italics for single line //{Y:b} is italics for both lines var parts = p.Text.SplitToLines(); int count = 0; bool italicOn = false; bool boldOn = false; bool underlineOn = false; var lineSb = new StringBuilder(); foreach (string line in parts) { if (count > 0) { lineSb.Append('|'); } bool alreadyItalic = italicOn; bool alreadyBold = boldOn; bool alreadyUnderline = underlineOn; var pre = new StringBuilder(); string s = line; for (int i = 0; i < 5; i++) { if (alreadyItalic && i == 0) { italicOn = true; boldOn = false; underlineOn = false; pre.Append("{y:i}"); // italic single line alreadyItalic = false; } else if (s.StartsWith("<i>", StringComparison.Ordinal)) { italicOn = true; boldOn = false; underlineOn = false; if (pre.ToString() != "{y:i}") { pre.Append("{y:i}"); // italic single line } s = s.Remove(0, 3); } else if (alreadyBold && i == 0) { italicOn = false; boldOn = true; underlineOn = false; pre.Append("{y:b}"); // bold single line } else if (s.StartsWith("<b>", StringComparison.Ordinal)) { italicOn = false; boldOn = true; underlineOn = false; if (pre.ToString() != "{y:b}") { pre.Append("{y:b}"); // bold single line } s = s.Remove(0, 3); } else if (alreadyUnderline && i == 0) { italicOn = false; boldOn = false; underlineOn = true; pre.Append("{y:u}"); // underline single line } else if (s.StartsWith("<u>", StringComparison.Ordinal)) { italicOn = false; boldOn = false; underlineOn = true; if (pre.ToString() != "{y:u}") { pre.Append("{y:u}"); // underline single line } s = s.Remove(0, 3); } if (s.StartsWith("<font ", StringComparison.OrdinalIgnoreCase)) { int end = s.IndexOf('>'); if (end > 0) { string tag = s.Substring(0, end); if (tag.Contains(" color=", StringComparison.OrdinalIgnoreCase)) { int colorStart = tag.IndexOf(" color=", StringComparison.OrdinalIgnoreCase); int colorEnd = tag.IndexOf('"', colorStart + " color=".Length + 1); if (colorEnd > 0) { string color = tag.Substring(colorStart, colorEnd - colorStart); color = color.Remove(0, " color=".Length); color = color.Trim('"'); color = color.Trim('\''); color = color.TrimStart('#'); if (color.Length == 6) { if (s.Contains(Environment.NewLine) && s.Contains("</font>" + Environment.NewLine, StringComparison.OrdinalIgnoreCase)) { pre.Append("{c:$" + color.Substring(4, 2) + color.Substring(2, 2) + color.Substring(0, 2) + "}"); } else { pre.Append("{C:$" + color.Substring(4, 2) + color.Substring(2, 2) + color.Substring(0, 2) + "}"); } } } } if (tag.Contains(" face=", StringComparison.OrdinalIgnoreCase)) { var faceStart = tag.IndexOf(" face=", StringComparison.OrdinalIgnoreCase); var faceEnd = tag.IndexOf('"', faceStart + " face=".Length + 1); if (faceEnd > 0) { string fontName = tag.Substring(faceStart, faceEnd - faceStart); fontName = fontName.Remove(0, " face=".Length).Trim(); fontName = fontName.Trim('"'); fontName = fontName.Trim('\''); if (fontName.Length > 0) { if (s.Contains(Environment.NewLine) && s.Contains("</font>" + Environment.NewLine, StringComparison.OrdinalIgnoreCase)) { pre.Append("{f:" + fontName + "}"); } else { pre.Append("{F:" + fontName + "}"); } } } } if (tag.Contains(" size=", StringComparison.OrdinalIgnoreCase)) { var sizeStart = tag.IndexOf(" size=", StringComparison.OrdinalIgnoreCase); var sizeEnd = tag.IndexOf('"', sizeStart + " size=".Length + 1); if (sizeEnd > 0) { string fontSize = tag.Substring(sizeStart, sizeEnd - sizeStart); fontSize = fontSize.Remove(0, " size=".Length).Trim(); fontSize = fontSize.Trim('"'); fontSize = fontSize.Trim('\''); if (fontSize.Length > 0) { if (s.Contains(Environment.NewLine) && s.Contains("</font>" + Environment.NewLine, StringComparison.OrdinalIgnoreCase)) { pre.Append("{s:" + fontSize + "}"); } else { pre.Append("{S:" + fontSize + "}"); } } } } s = s.Remove(0, end + 1); } } } if (s.Contains("</i>", StringComparison.OrdinalIgnoreCase)) { italicOn = false; } if (s.Contains("</b>", StringComparison.OrdinalIgnoreCase)) { boldOn = false; } if (s.Contains("</u>", StringComparison.OrdinalIgnoreCase)) { underlineOn = false; } lineSb.Append(HtmlUtil.RemoveHtmlTags(pre + line)); count++; } string text = lineSb.ToString(); int noOfLines = Utilities.CountTagInText(text, '|') + 1; if (Utilities.CountTagInText(text, "{y:i}") == noOfLines && text.StartsWith("{y:i}", StringComparison.Ordinal)) { text = "{Y:i}" + text.Replace("{y:i}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:b}") == noOfLines && text.StartsWith("{y:b}", StringComparison.Ordinal)) { text = "{Y:b}" + text.Replace("{y:b}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:u}") == noOfLines && text.StartsWith("{y:u}", StringComparison.Ordinal)) { text = "{Y:u}" + text.Replace("{y:u}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:u}{y:i}") == noOfLines && text.StartsWith("{y:u}{y:i}", StringComparison.Ordinal)) { text = "{Y:u}{Y:i}" + text.Replace("{y:u}", string.Empty).Replace("{y:i}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:i}{y:u}") == noOfLines && text.StartsWith("{y:i}{y:u}", StringComparison.Ordinal)) { text = "{Y:i}{Y:u}" + text.Replace("{y:i}", string.Empty).Replace("{y:u}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:i}{y:b}") == noOfLines && text.StartsWith("{y:i}{y:b}", StringComparison.Ordinal)) { text = "{Y:i}{Y:b}" + text.Replace("{y:i}", string.Empty).Replace("{y:b}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:b}{y:i}") == noOfLines && text.StartsWith("{y:b}{y:i}", StringComparison.Ordinal)) { text = "{Y:b}{Y:i}" + text.Replace("{y:i}", string.Empty).Replace("{y:b}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:b}{y:u}") == noOfLines && text.StartsWith("{y:b}{y:u}", StringComparison.Ordinal)) { text = "{Y:b}{Y:u}" + text.Replace("{y:b}", string.Empty).Replace("{y:u}", string.Empty); } else if (Utilities.CountTagInText(text, "{y:u}{y:b}") == noOfLines && text.StartsWith("{y:u}{y:b}", StringComparison.Ordinal)) { text = "{Y:u}{Y:b}" + text.Replace("{y:u}", string.Empty).Replace("{y:b}", string.Empty); } if (Utilities.CountTagInText(text, "{y:i}") == 1 && noOfLines == 1) { text = text.Replace("{y:i}", "{Y:i}"); } if (Utilities.CountTagInText(text, "{y:b}") == 1 && noOfLines == 1) { text = text.Replace("{y:b}", "{Y:b}"); } if (Utilities.CountTagInText(text, "{y:u}") == 1 && noOfLines == 1) { text = text.Replace("{y:u}", "{Y:u}"); } sb.AppendLine(HtmlUtil.RemoveHtmlTags(text)); } return sb.ToString().Trim(); } public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName) { _errorCount = 0; _errors = new StringBuilder(); Errors = null; _lineNumber = 0; foreach (string line in lines) { _lineNumber++; string s = RemoveIllegalSpacesAndFixEmptyCodes(line); if (RegexMicroDvdLine.IsMatch(s)) { try { int textIndex = GetTextStartIndex(s); if (textIndex < s.Length) { string text = s.Substring(textIndex); string temp = s.Substring(0, textIndex - 1); string[] frames = temp.Replace("][", ":").Replace("[", string.Empty).Replace("]", string.Empty).Split(':'); int startFrame = int.Parse(frames[0]); int endFrame = int.Parse(frames[1]); string post = string.Empty; string[] parts = text.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); int count = 0; var lineSb = new StringBuilder(); foreach (string s2 in parts) { if (count > 0) { lineSb.AppendLine(); } s = s2.Trim(); var pre = new StringBuilder(); string singlePost = string.Empty; for (int i = 0; i < 5; i++) { if (s.StartsWith("{Y:i}", StringComparison.Ordinal)) { s = s.Remove(0, 5); pre.Append("<i>"); post = "</i>" + post; } else if (s.StartsWith("{Y:b}", StringComparison.Ordinal)) { s = s.Remove(0, 5); pre.Append("<b>"); post = "</b>" + post; } else if (s.StartsWith("{Y:u}", StringComparison.Ordinal)) { s = s.Remove(0, 5); pre.Append("<u>"); post = "</u>" + post; } else if (s.StartsWith("{y:i}", StringComparison.Ordinal)) { s = s.Remove(0, 5); singlePost = "</i>" + singlePost; pre.Append("<i>"); } else if (s.StartsWith("{y:b}", StringComparison.Ordinal)) { s = s.Remove(0, 5); singlePost = "</b>" + singlePost; pre.Append("<b>"); } else if (s.StartsWith("{y:u}", StringComparison.Ordinal)) { s = s.Remove(0, 5); singlePost = "</u>" + singlePost; pre.Append("<u>"); } else if (s.StartsWith("{y:b,u}", StringComparison.Ordinal)) { s = s.Remove(0, 7); singlePost = "</u></b>" + singlePost; pre.Append("<b><u>"); } else if (s.StartsWith("{y:u,b}", StringComparison.Ordinal)) { s = s.Remove(0, 7); singlePost = "</b></u>" + singlePost; pre.Append("<u><b>"); } else if (s.StartsWith("{y:b,i}", StringComparison.Ordinal)) { s = s.Remove(0, 7); singlePost = "</i></b>" + singlePost; pre.Append("<b><i>"); } else if (s.StartsWith("{y:i,b}", StringComparison.Ordinal)) { s = s.Remove(0, 7); singlePost = "</b></i>" + singlePost; pre.Append("<i><b>"); } else if (s.StartsWith("{y:i,u}", StringComparison.Ordinal)) { s = s.Remove(0, 7); singlePost = "</u></i>" + singlePost; pre.Append("<i><u>"); } else if (s.StartsWith("{y:u,i}", StringComparison.Ordinal)) { s = s.Remove(0, 7); singlePost = "</i></u>" + singlePost; pre.Append("<><i>"); } else if (s.StartsWith("{Y:b,u}", StringComparison.Ordinal) || s.StartsWith("{Y:u,b}", StringComparison.Ordinal)) { s = s.Remove(0, 7); pre.Append("<b><u>"); post = "</u></b>" + post; } else if (s.StartsWith("{Y:b,i}", StringComparison.Ordinal) || s.StartsWith("{Y:i,b}", StringComparison.Ordinal)) { s = s.Remove(0, 7); pre.Append("<b><i>"); post = "</i></b>" + post; } else if (s.StartsWith("{Y:i,u}", StringComparison.Ordinal) || s.StartsWith("{Y:u,i}", StringComparison.Ordinal)) { s = s.Remove(0, 7); pre.Append("<i><u>"); post = "</u></i>" + post; } else if (s.Contains("{c:$")) { int start = s.IndexOf("{c:$", StringComparison.Ordinal); int end = s.IndexOf('}', start); if (end > start) { string tag = s.Substring(start, end - start); tag = tag.Remove(0, 4); if (tag.Length == 6) { pre.Append("<font color=\"#" + tag.Substring(4, 2) + tag.Substring(2, 2) + tag.Substring(0, 2) + "\">"); s = s.Remove(start, end - start + 1); singlePost = "</font>" + singlePost; } } } else if (s.Contains("{C:$")) // uppercase=all lines { int start = s.IndexOf("{C:$", StringComparison.Ordinal); int end = s.IndexOf('}', start); if (end > start) { string tag = s.Substring(start, end - start); tag = tag.Remove(0, 4); if (tag.Length == 6) { pre.Append("<font color=\"#" + tag.Substring(4, 2) + tag.Substring(2, 2) + tag.Substring(0, 2) + "\">"); s = s.Remove(start, end - start + 1); post = "</font>" + post; } } } else if (s.Contains("{f:")) { int start = s.IndexOf("{f:", StringComparison.Ordinal); int end = s.IndexOf('}', start); if (end > start) { string tag = s.Substring(start, end - start); tag = tag.Remove(0, 3).Trim(); if (tag.Length > 0) { pre.Append("<font face=\"" + tag + "\">"); s = s.Remove(start, end - start + 1); singlePost = "</font>" + singlePost; } } } else if (s.Contains("{F:")) // uppercase=all lines { int start = s.IndexOf("{F:", StringComparison.Ordinal); int end = s.IndexOf('}', start); if (end > start) { string tag = s.Substring(start, end - start); tag = tag.Remove(0, 3).Trim(); if (tag.Length > 0) { pre.Append("<font face=\"" + tag + "\">"); s = s.Remove(start, end - start + 1); post = "</font>" + post; } } } else if (s.Contains("{s:")) { int start = s.IndexOf("{s:", StringComparison.Ordinal); int end = s.IndexOf('}', start); if (end > start) { string tag = s.Substring(start, end - start); tag = tag.Remove(0, 3).Trim(); if (tag.Length > 0) { pre.Append("<font size=\"" + tag + "\">"); s = s.Remove(start, end - start + 1); singlePost = "</font>" + singlePost; } } } else if (s.Contains("{S:")) // uppercase=all lines { int start = s.IndexOf("{S:", StringComparison.Ordinal); int end = s.IndexOf('}', start); if (end > start) { string tag = s.Substring(start, end - start); tag = tag.Remove(0, 3).Trim(); if (tag.Length > 0) { pre.Append("<font size=\"" + tag + "\">"); s = s.Remove(start, end - start + 1); post = "</font>" + post; } } } } s = s.Replace("{Y:i}", string.Empty).Replace("{y:i}", string.Empty); s = s.Replace("{Y:b}", string.Empty).Replace("{y:b}", string.Empty); s = s.Replace("{Y:u}", string.Empty).Replace("{y:u}", string.Empty); lineSb.Append(pre + s + singlePost); count++; } text = lineSb + post; subtitle.Paragraphs.Add(new Paragraph(text, FramesToMilliseconds(startFrame), FramesToMilliseconds(endFrame))); } } catch { _errorCount++; if (_errors.Length < 2000) { _errors.AppendLine(string.Format(FormatLanguage.LineNumberXErrorReadingFromSourceLineY, _lineNumber, line)); } } } else { _errorCount++; if (_errors.Length < 2000) { _errors.AppendLine(string.Format(FormatLanguage.LineNumberXErrorReadingFromSourceLineY, _lineNumber, line)); } } } int j = 0; foreach (Paragraph p in subtitle.Paragraphs) { Paragraph previous = subtitle.GetParagraphOrDefault(j - 1); if (p.StartTime.TotalMilliseconds == 0 && previous != null) { p.StartTime.TotalMilliseconds = previous.EndTime.TotalMilliseconds + 1; } if (p.EndTime.TotalMilliseconds == 0) { p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds; } j++; } subtitle.Renumber(); Errors = _errors.ToString(); } private static int GetTextStartIndex(string line) { int i = 0; int tagCount = 0; while (i < line.Length && tagCount < 4) { if (line[i] == '[' || line[i] == ']') { tagCount++; } i++; } return i; } } }
SubtitleEdit/subtitleedit
src/libse/SubtitleFormats/UnknownSubtitle70.cs
C#
gpl-3.0
31,926
/* * This file is part of Hootenanny. * * Hootenanny is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -------------------------------------------------------------------- * * The following copyright notices are generated automatically. If you * have a new notice to add, please use the format: * " * @copyright Copyright ..." * This will properly maintain the copyright information. DigitalGlobe * copyrights will be updated automatically. * * @copyright Copyright (C) 2015 DigitalGlobe (http://www.digitalglobe.com/) */ #include "CalculateAreaForStatsVisitor.h" // geos #include <geos/geom/LineString.h> // hoot #include <hoot/core/Factory.h> #include <hoot/core/OsmMap.h> #include <hoot/core/util/ElementConverter.h> namespace hoot { HOOT_FACTORY_REGISTER(ElementVisitor, CalculateAreaForStatsVisitor) Meters CalculateAreaForStatsVisitor::getArea(const OsmMapPtr& map, ElementPtr e) { CalculateAreaForStatsVisitor v; v.setOsmMap(map.get()); e->visitRo(*map, v); return v.getArea(); } void CalculateAreaForStatsVisitor::visit(ElementType type, long id) { const shared_ptr<const Element> e = _map->getElement(type, id); shared_ptr<Geometry> g = ElementConverter(_map->shared_from_this()).convertToGeometry(e, true); _total += g->getArea(); //cout << "CAFS: geo id=" << e->getId() << ", area=" << g->getArea() << ", total area=" << _total << endl; } }
nstarke/hootenanny
hoot-core/src/main/cpp/hoot/core/visitors/CalculateAreaForStatsVisitor.cpp
C++
gpl-3.0
1,974
/* ** Copyright (©) 2018- Matt Postiff. ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #include "crossrefs.h" #include <glib/gi18n.h> #include "progresswindow.h" #include "directories.h" #include <locale> #include "gtkwrappers.h" // I should have a better way of accessing this extern book_record books_table[]; CrossReferences::CrossReferences() { bbl = LoadXrefs("/bibles/bi.crf", "BI_XREF"); bblopenxref = LoadXrefs("/bibles/open_bible_info.crf", "OPENBIBLE_XREF"); } bible_bixref *CrossReferences::LoadXrefs(const ustring& filename, const ustring &xrefbiblename) { // Load the whole set of cross references. It is a lot of data--over half a megabyte // of memory, but the way it is stored in binary format (see linux/buildcrf.pl and // linux/readcrf.pl) makes it fairly quick. ustring crossref_file = Directories->get_package_data() + filename; ReadBinary rb(crossref_file); uint32_t *dataptr = rb.get_data(); unsigned int num32BitWords = rb.get_num32BitWords(); bible_bixref *bbl_internal = nullptr; if ((dataptr == 0x0) || (num32BitWords == 0)) { // There was a problem opening the file bbl_internal = nullptr; gtkw_dialog_error(NULL, _("Cannot open file ") + crossref_file); return bbl_internal; } bbl_internal = new bible_bixref(xrefbiblename); // Create empty books right now, since we know we are going to need them bbl_internal->books.resize(67, 0x0); unsigned int b; for (b = 1; b <= 66; b++) { ustring bookname = books_table[b].name; bbl_internal->books[b] = new book_bixref(bbl_internal, bookname, b); } unsigned int i; bool startNewList = true; book *bk = nullptr; chapter *ch = nullptr; verse_xref *vs = nullptr; ProgressWindow progresswindow (_("Loading cross-reference data: ")+filename, false); progresswindow.set_iterate (0, 1, num32BitWords>>10); // shifting by 10 is dividing by appx 1000 (1024) for (i = 0; i < num32BitWords; i++) { // Logic is this: whenever last 10 bits of counter i are zero, iterate if ((i&0x3FF) == 0) { progresswindow.iterate(); } unsigned int encoded = *dataptr; dataptr++; // should advance by 4 bytes for next time around if (encoded == 0) { startNewList = true; continue; } if (startNewList) { Reference ref(encoded); bk = bbl_internal->books[ref.book_get()]; bk->check_chapter_in_range(ref.chapter_get()); ch = bk->chapters[ref.chapter_get()]; if (ch == 0) { // First time we are encountering this chapter. We need // to create it. ch = new chapter(bk, ref.chapter_get()); bk->chapters[ref.chapter_get()] = ch; } // As designed, the "starter" verse only appears // one time. Therefore, when we come to it, we know we need to create a // new verse to contain the upcoming cross-references. ch->check_verse_in_range(ref.verse_get_single()); vs = new verse_xref(ch, ref.verse_get_single(), ""); ch->verses[ref.verse_get_single()] = vs; startNewList = false; } else { // Add to an existing list. vs->xrefs.push_back(encoded); } } // When rb goes out of scope, destructor frees up the buffer that was read return bbl_internal; } CrossReferences::~CrossReferences() { if (bbl) { delete bbl; bbl = nullptr; } if (bblopenxref) { delete bblopenxref; bblopenxref = nullptr; } } void CrossReferences::write(const Reference &ref, HtmlWriter2 &htmlwriter) { WriteXrefs(bbl, ref, htmlwriter); WriteXrefs(bblopenxref, ref, htmlwriter); } void CrossReferences::WriteXrefs(bible_bixref *bbl_internal, const Reference &ref, HtmlWriter2 &htmlwriter) { vector <unsigned int> *xrefs; // could transfer over to uint32_t here and elsewhere htmlwriter.paragraph_open(); htmlwriter.text_add(bbl_internal->projname + _(": Cross references for ") + books_id_to_localname(ref.book_get()) + " " + std::to_string(ref.chapter_get()) + ":" + ref.verse_get()); htmlwriter.paragraph_close(); if (bbl_internal == 0x0) { htmlwriter.paragraph_open(); htmlwriter.text_add(_("Could not open cross-reference file ")); htmlwriter.paragraph_close(); return; } if ((ref.book_get() == 0) || (ref.chapter_get() == 0) || (ref.verse_get_single() == 0)) { htmlwriter.paragraph_open(); htmlwriter.text_add(_("Invalid reference; therefore not looking up cross references")); htmlwriter.paragraph_close(); return; } try { xrefs = bbl_internal->retrieve_xrefs(ref); // this copies xrefs from the returned vector<>& } catch (std::runtime_error &e) { htmlwriter.paragraph_open(); htmlwriter.text_add(e.what()); htmlwriter.paragraph_close(); } if ((xrefs == nullptr) || (xrefs->empty())) { htmlwriter.paragraph_open(); htmlwriter.text_add(_("No cross references")); htmlwriter.paragraph_close(); } else { extern Settings *settings; ustring project = settings->genconfig.project_get(); Reference firstRef; bool finishComplexRange = false; for (auto &it : *xrefs) { Reference ref(it); // construct it directly from the bit-encoded reference if (ref.getRefType() == Reference::complexRange) { firstRef = ref; finishComplexRange = true; continue; // I am assuming that there is at least one more verse in xrefs...by // construction there has to be. } ustring verse; ustring address; if (finishComplexRange == true) { verse = project_retrieve_verse(project, firstRef); address = books_id_to_localname(firstRef.book_get()) + " " + std::to_string(firstRef.chapter_get()) + ":" + firstRef.verse_get(); // In this iteration of the loop, "ref" is now actually "secondRef" but I don't bother calling it that } else { // the most common case, a regular-old singleVerse (John 3:16) or multiVerse (John 3:16-17) verse = project_retrieve_verse(project, ref); address = books_id_to_localname(ref.book_get()) + " " + std::to_string(ref.chapter_get()) + ":" + ref.verse_get(); } // Get data about the project. // This is exact same code as Concordance::writeVerses...should re-factor htmlwriter.paragraph_open(); htmlwriter.hyperlink_add ("goto " + address, address); if (verse.empty()) { verse.append(_("<empty>")); } else { replace_text(verse, "\n", " "); CategorizeLine cl(verse); cl.remove_verse_number(ref.verse_get()); verse = cl.verse; htmlwriter.text_add(" " + verse); } if (finishComplexRange == true) { htmlwriter.text_add("....."); address = books_id_to_localname(ref.book_get()) + " " + std::to_string(ref.chapter_get()) + ":" + ref.verse_get(); htmlwriter.hyperlink_add ("goto " + address, address); finishComplexRange = false; } htmlwriter.paragraph_close(); } } }
postiffm/bibledit-desktop
src/crossrefs.cpp
C++
gpl-3.0
8,385
//= require ./map
cloudtm/geograph
geograph/app/assets/javascripts/map_lib/index.js
JavaScript
gpl-3.0
17
const log = require('app/lib/core/log') module.exports = config => props => { const [ pluginName, pluginPath, pluginExports ] = props log.trace(`Initialzing includer: ${log.ul(pluginPath)}.`) const exports = {} exports.name = pluginExports.name || pluginName exports.options = pluginExports.options exports.setOptions = newOpts => { log.trace(`Setting options for modifier: ${log.ul(pluginPath)} ${log.hl(pluginName)}.`) exports.options = newOpts } exports.configure = conf => new Promise(resolve => { log.trace(`Configuring includer ${log.hl(pluginName)}.`) config = conf exports.htmlCommentIncluder = pluginExports.plugin(pluginExports, config) if (!exports.htmlCommentIncluder) { const msg = `Could not configure includer: ${pluginName}.` log.error(msg) // return reject(msg) resolve(exports) } resolve(exports) }) return exports }
F1LT3R/markserv-cli
lib/plugin/includer.js
JavaScript
gpl-3.0
890
/* XMRig * Copyright 2018-2021 SChernykh <https://github.com/SChernykh> * Copyright 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.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/>. */ #include "ghostrider.h" #include "sph_blake.h" #include "sph_bmw.h" #include "sph_groestl.h" #include "sph_jh.h" #include "sph_keccak.h" #include "sph_skein.h" #include "sph_luffa.h" #include "sph_cubehash.h" #include "sph_shavite.h" #include "sph_simd.h" #include "sph_echo.h" #include "sph_hamsi.h" #include "sph_fugue.h" #include "sph_shabal.h" #include "sph_whirlpool.h" #include "base/io/log/Log.h" #include "base/io/log/Tags.h" #include "base/tools/Chrono.h" #include "backend/cpu/Cpu.h" #include "crypto/cn/CnHash.h" #include "crypto/cn/CnCtx.h" #include "crypto/cn/CryptoNight.h" #include "crypto/common/VirtualMemory.h" #include <thread> #include <atomic> #include <uv.h> #ifdef XMRIG_FEATURE_HWLOC #include "base/kernel/Platform.h" #include "backend/cpu/platform/HwlocCpuInfo.h" #include <hwloc.h> #endif #if defined(XMRIG_ARM) # include "crypto/cn/sse2neon.h" #elif defined(__GNUC__) # include <x86intrin.h> #else # include <intrin.h> #endif #define CORE_HASH(i, x) static void h##i(const uint8_t* data, size_t size, uint8_t* output) \ { \ sph_##x##_context ctx; \ sph_##x##_init(&ctx); \ sph_##x(&ctx, data, size); \ sph_##x##_close(&ctx, output); \ } CORE_HASH( 0, blake512 ); CORE_HASH( 1, bmw512 ); CORE_HASH( 2, groestl512 ); CORE_HASH( 3, jh512 ); CORE_HASH( 4, keccak512 ); CORE_HASH( 5, skein512 ); CORE_HASH( 6, luffa512 ); CORE_HASH( 7, cubehash512); CORE_HASH( 8, shavite512 ); CORE_HASH( 9, simd512 ); CORE_HASH(10, echo512 ); CORE_HASH(11, hamsi512 ); CORE_HASH(12, fugue512 ); CORE_HASH(13, shabal512 ); CORE_HASH(14, whirlpool ); #undef CORE_HASH typedef void (*core_hash_func)(const uint8_t* data, size_t size, uint8_t* output); static const core_hash_func core_hash[15] = { h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13, h14 }; namespace xmrig { static constexpr Algorithm::Id cn_hash[6] = { Algorithm::CN_GR_0, Algorithm::CN_GR_1, Algorithm::CN_GR_2, Algorithm::CN_GR_3, Algorithm::CN_GR_4, Algorithm::CN_GR_5, }; static constexpr const char* cn_names[6] = { "cn/dark (512 KB)", "cn/dark-lite (256 KB)", "cn/fast (2 MB)", "cn/lite (1 MB)", "cn/turtle (256 KB)", "cn/turtle-lite (128 KB)", }; static constexpr size_t cn_sizes[6] = { Algorithm::l3(Algorithm::CN_GR_0), // 512 KB Algorithm::l3(Algorithm::CN_GR_1) / 2, // 256 KB Algorithm::l3(Algorithm::CN_GR_2), // 2 MB Algorithm::l3(Algorithm::CN_GR_3), // 1 MB Algorithm::l3(Algorithm::CN_GR_4), // 256 KB Algorithm::l3(Algorithm::CN_GR_5) / 2, // 128 KB }; static constexpr CnHash::AlgoVariant av_hw_aes[5] = { CnHash::AV_SINGLE, CnHash::AV_SINGLE, CnHash::AV_DOUBLE, CnHash::AV_TRIPLE, CnHash::AV_QUAD }; static constexpr CnHash::AlgoVariant av_soft_aes[5] = { CnHash::AV_SINGLE_SOFT, CnHash::AV_SINGLE_SOFT, CnHash::AV_DOUBLE_SOFT, CnHash::AV_TRIPLE_SOFT, CnHash::AV_QUAD_SOFT }; template<size_t N> static inline void select_indices(uint32_t (&indices)[N], const uint8_t* seed) { bool selected[N] = {}; uint32_t k = 0; for (uint32_t i = 0; i < 64; ++i) { const uint8_t index = ((seed[i / 2] >> ((i & 1) * 4)) & 0xF) % N; if (!selected[index]) { selected[index] = true; indices[k++] = index; if (k >= N) { return; } } } for (uint32_t i = 0; i < N; ++i) { if (!selected[i]) { indices[k++] = i; } } } namespace ghostrider { #ifdef XMRIG_FEATURE_HWLOC static struct AlgoTune { double hashrate = 0.0; uint32_t step = 1; uint32_t threads = 1; } tuneDefault[6], tune8MB[6]; struct HelperThread { HelperThread(hwloc_bitmap_t cpu_set, int priority, bool is8MB) : m_cpuSet(cpu_set), m_priority(priority), m_is8MB(is8MB) { uv_mutex_init(&m_mutex); uv_cond_init(&m_cond); m_thread = new std::thread(&HelperThread::run, this); do { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } while (!m_ready); } ~HelperThread() { uv_mutex_lock(&m_mutex); m_finished = true; uv_cond_signal(&m_cond); uv_mutex_unlock(&m_mutex); m_thread->join(); delete m_thread; uv_mutex_destroy(&m_mutex); uv_cond_destroy(&m_cond); hwloc_bitmap_free(m_cpuSet); } struct TaskBase { virtual ~TaskBase() {} virtual void run() = 0; }; template<typename T> struct Task : TaskBase { inline Task(T&& task) : m_task(std::move(task)) { static_assert(sizeof(Task) <= 128, "Task struct is too large"); } void run() override { m_task(); this->~Task(); } T m_task; }; template<typename T> inline void launch_task(T&& task) { uv_mutex_lock(&m_mutex); new (&m_tasks[m_numTasks++]) Task<T>(std::move(task)); uv_cond_signal(&m_cond); uv_mutex_unlock(&m_mutex); } inline void wait() const { while (m_numTasks) { _mm_pause(); } } void run() { if (hwloc_bitmap_weight(m_cpuSet) > 0) { hwloc_topology_t topology = reinterpret_cast<HwlocCpuInfo*>(Cpu::info())->topology(); if (hwloc_set_cpubind(topology, m_cpuSet, HWLOC_CPUBIND_THREAD | HWLOC_CPUBIND_STRICT) < 0) { hwloc_set_cpubind(topology, m_cpuSet, HWLOC_CPUBIND_THREAD); } } Platform::setThreadPriority(m_priority); uv_mutex_lock(&m_mutex); m_ready = true; do { uv_cond_wait(&m_cond, &m_mutex); const uint32_t n = m_numTasks; if (n > 0) { for (uint32_t i = 0; i < n; ++i) { reinterpret_cast<TaskBase*>(&m_tasks[i])->run(); } std::atomic_thread_fence(std::memory_order_seq_cst); m_numTasks = 0; } } while (!m_finished); uv_mutex_unlock(&m_mutex); } uv_mutex_t m_mutex; uv_cond_t m_cond; alignas(16) uint8_t m_tasks[4][128] = {}; volatile uint32_t m_numTasks = 0; volatile bool m_ready = false; volatile bool m_finished = false; hwloc_bitmap_t m_cpuSet = {}; int m_priority = -1; bool m_is8MB = false; std::thread* m_thread = nullptr; }; void benchmark() { #ifndef XMRIG_ARM static std::atomic<int> done{ 0 }; if (done.exchange(1)) { return; } std::thread t([]() { // Try to avoid CPU core 0 because many system threads use it and can interfere uint32_t thread_index1 = (Cpu::info()->threads() > 2) ? 2 : 0; hwloc_topology_t topology = reinterpret_cast<HwlocCpuInfo*>(Cpu::info())->topology(); hwloc_obj_t pu = hwloc_get_pu_obj_by_os_index(topology, thread_index1); hwloc_obj_t pu2; hwloc_get_closest_objs(topology, pu, &pu2, 1); uint32_t thread_index2 = pu2 ? pu2->os_index : thread_index1; if (thread_index2 < thread_index1) { std::swap(thread_index1, thread_index2); } Platform::setThreadAffinity(thread_index1); Platform::setThreadPriority(3); constexpr uint32_t N = 1U << 21; VirtualMemory::init(0, N); VirtualMemory* memory = new VirtualMemory(N * 8, true, false, false); // 2 MB cache per core by default size_t max_scratchpad_size = 1U << 21; if ((Cpu::info()->L3() >> 22) > Cpu::info()->cores()) { // At least 1 core can run with 8 MB cache max_scratchpad_size = 1U << 23; } else if ((Cpu::info()->L3() >> 22) >= Cpu::info()->cores()) { // All cores can run with 4 MB cache max_scratchpad_size = 1U << 22; } LOG_VERBOSE("Running GhostRider benchmark on logical CPUs %u and %u (max scratchpad size %zu MB, huge pages %s)", thread_index1, thread_index2, max_scratchpad_size >> 20, memory->isHugePages() ? "on" : "off"); cryptonight_ctx* ctx[8]; CnCtx::create(ctx, memory->scratchpad(), N, 8); const CnHash::AlgoVariant* av = Cpu::info()->hasAES() ? av_hw_aes : av_soft_aes; uint8_t buf[80]; uint8_t hash[32 * 8]; LOG_VERBOSE("%24s | N | Hashrate", "Algorithm"); LOG_VERBOSE("-------------------------|-----|-------------"); for (uint32_t algo = 0; algo < 6; ++algo) { for (uint64_t step : { 1, 2, 4}) { const size_t cur_scratchpad_size = cn_sizes[algo] * step; if (cur_scratchpad_size > max_scratchpad_size) { continue; } auto f = CnHash::fn(cn_hash[algo], av[step], Assembly::AUTO); double start_time = Chrono::highResolutionMSecs(); double min_dt = 1e10; for (uint32_t iter = 0;; ++iter) { double t1 = Chrono::highResolutionMSecs(); // Stop after 15 milliseconds, but only if at least 10 iterations were done if ((iter >= 10) && (t1 - start_time >= 15.0)) { break; } f(buf, sizeof(buf), hash, ctx, 0); const double dt = Chrono::highResolutionMSecs() - t1; if (dt < min_dt) { min_dt = dt; } } const double hashrate = step * 1e3 / min_dt; LOG_VERBOSE("%24s | %" PRIu64 "x1 | %.2f h/s", cn_names[algo], step, hashrate); if (hashrate > tune8MB[algo].hashrate) { tune8MB[algo].hashrate = hashrate; tune8MB[algo].step = static_cast<uint32_t>(step); tune8MB[algo].threads = 1; } if ((cur_scratchpad_size < (1U << 23)) && (hashrate > tuneDefault[algo].hashrate)) { tuneDefault[algo].hashrate = hashrate; tuneDefault[algo].step = static_cast<uint32_t>(step); tuneDefault[algo].threads = 1; } } } hwloc_bitmap_t helper_set = hwloc_bitmap_alloc(); hwloc_bitmap_set(helper_set, thread_index2); HelperThread* helper = new HelperThread(helper_set, 3, false); for (uint32_t algo = 0; algo < 6; ++algo) { for (uint64_t step : { 1, 2, 4}) { const size_t cur_scratchpad_size = cn_sizes[algo] * step * 2; if (cur_scratchpad_size > max_scratchpad_size) { continue; } auto f = CnHash::fn(cn_hash[algo], av[step], Assembly::AUTO); double start_time = Chrono::highResolutionMSecs(); double min_dt = 1e10; for (uint32_t iter = 0;; ++iter) { double t1 = Chrono::highResolutionMSecs(); // Stop after 30 milliseconds, but only if at least 10 iterations were done if ((iter >= 10) && (t1 - start_time >= 30.0)) { break; } helper->launch_task([&f, &buf, &hash, &ctx, &step]() { f(buf, sizeof(buf), hash + step * 32, ctx + step, 0); }); f(buf, sizeof(buf), hash, ctx, 0); helper->wait(); const double dt = Chrono::highResolutionMSecs() - t1; if (dt < min_dt) { min_dt = dt; } } const double hashrate = step * 2e3 / min_dt * 1.0075; LOG_VERBOSE("%24s | %" PRIu64 "x2 | %.2f h/s", cn_names[algo], step, hashrate); if (hashrate > tune8MB[algo].hashrate) { tune8MB[algo].hashrate = hashrate; tune8MB[algo].step = static_cast<uint32_t>(step); tune8MB[algo].threads = 2; } if ((cur_scratchpad_size < (1U << 23)) && (hashrate > tuneDefault[algo].hashrate)) { tuneDefault[algo].hashrate = hashrate; tuneDefault[algo].step = static_cast<uint32_t>(step); tuneDefault[algo].threads = 2; } } } delete helper; CnCtx::release(ctx, 8); delete memory; }); t.join(); LOG_VERBOSE("---------------------------------------------"); LOG_VERBOSE("| GhostRider tuning results |"); LOG_VERBOSE("---------------------------------------------"); for (int algo = 0; algo < 6; ++algo) { LOG_VERBOSE("%24s | %ux%u | %.2f h/s", cn_names[algo], tuneDefault[algo].step, tuneDefault[algo].threads, tuneDefault[algo].hashrate); if ((tune8MB[algo].step != tuneDefault[algo].step) || (tune8MB[algo].threads != tuneDefault[algo].threads)) { LOG_VERBOSE("%24s | %ux%u | %.2f h/s", cn_names[algo], tune8MB[algo].step, tune8MB[algo].threads, tune8MB[algo].hashrate); } } #endif } template <typename func> static inline bool findByType(hwloc_obj_t obj, hwloc_obj_type_t type, func lambda) { for (size_t i = 0; i < obj->arity; i++) { if (obj->children[i]->type == type) { if (lambda(obj->children[i])) { return true; } } else { if (findByType(obj->children[i], type, lambda)) { return true; } } } return false; } HelperThread* create_helper_thread(int64_t cpu_index, int priority, const std::vector<int64_t>& affinities) { #ifndef XMRIG_ARM hwloc_bitmap_t helper_cpu_set = hwloc_bitmap_alloc(); hwloc_bitmap_t main_threads_set = hwloc_bitmap_alloc(); for (int64_t i : affinities) { if (i >= 0) { hwloc_bitmap_set(main_threads_set, i); } } if (cpu_index >= 0) { hwloc_topology_t topology = reinterpret_cast<HwlocCpuInfo*>(Cpu::info())->topology(); hwloc_obj_t root = hwloc_get_root_obj(topology); bool is8MB = false; findByType(root, HWLOC_OBJ_L3CACHE, [cpu_index, &is8MB](hwloc_obj_t obj) { if (!hwloc_bitmap_isset(obj->cpuset, cpu_index)) { return false; } uint32_t num_cores = 0; findByType(obj, HWLOC_OBJ_CORE, [&num_cores](hwloc_obj_t) { ++num_cores; return false; }); if ((obj->attr->cache.size >> 22) > num_cores) { uint32_t num_8MB_cores = (obj->attr->cache.size >> 22) - num_cores; is8MB = findByType(obj, HWLOC_OBJ_CORE, [cpu_index, &num_8MB_cores](hwloc_obj_t obj2) { if (num_8MB_cores > 0) { --num_8MB_cores; if (hwloc_bitmap_isset(obj2->cpuset, cpu_index)) { return true; } } return false; }); } return true; }); for (auto obj_type : { HWLOC_OBJ_CORE, HWLOC_OBJ_L1CACHE, HWLOC_OBJ_L2CACHE, HWLOC_OBJ_L3CACHE }) { findByType(root, obj_type, [cpu_index, helper_cpu_set, main_threads_set](hwloc_obj_t obj) { const hwloc_cpuset_t& s = obj->cpuset; if (hwloc_bitmap_isset(s, cpu_index)) { hwloc_bitmap_andnot(helper_cpu_set, s, main_threads_set); if (hwloc_bitmap_weight(helper_cpu_set) > 0) { return true; } } return false; }); if (hwloc_bitmap_weight(helper_cpu_set) > 0) { return new HelperThread(helper_cpu_set, priority, is8MB); } } } #endif return nullptr; } void destroy_helper_thread(HelperThread* t) { delete t; } void hash_octa(const uint8_t* data, size_t size, uint8_t* output, cryptonight_ctx** ctx, HelperThread* helper, bool verbose) { enum { N = 8 }; uint8_t* ctx_memory[N]; for (size_t i = 0; i < N; ++i) { ctx_memory[i] = ctx[i]->memory; } // PrevBlockHash (GhostRider's seed) is stored in bytes [4; 36) uint32_t core_indices[15]; select_indices(core_indices, data + 4); uint32_t cn_indices[6]; select_indices(cn_indices, data + 4); if (verbose) { static uint32_t prev_indices[3]; if (memcmp(cn_indices, prev_indices, sizeof(prev_indices)) != 0) { memcpy(prev_indices, cn_indices, sizeof(prev_indices)); for (int i = 0; i < 3; ++i) { LOG_INFO("%s GhostRider algo %d: %s", Tags::cpu(), i + 1, cn_names[cn_indices[i]]); } } } const CnHash::AlgoVariant* av = Cpu::info()->hasAES() ? av_hw_aes : av_soft_aes; const AlgoTune* tune = (helper && helper->m_is8MB) ? tune8MB : tuneDefault; uint8_t tmp[64 * N]; if (helper && (tune[cn_indices[0]].threads == 2) && (tune[cn_indices[1]].threads == 2) && (tune[cn_indices[2]].threads == 2)) { const size_t n = N / 2; helper->launch_task([n, av, data, size, &ctx_memory, ctx, &cn_indices, &core_indices, &tmp, output, tune]() { const uint8_t* input = data; size_t input_size = size; for (size_t part = 0; part < 3; ++part) { const AlgoTune& t = tune[cn_indices[part]]; // Allocate scratchpads { uint8_t* p = ctx_memory[4]; for (size_t i = n, k = 4; i < N; ++i) { if ((i % t.step) == 0) { k = 4; p = ctx_memory[4]; } else if (p - ctx_memory[k] >= (1 << 21)) { ++k; p = ctx_memory[k]; } ctx[i]->memory = p; p += cn_sizes[cn_indices[part]]; } } for (size_t i = 0; i < 5; ++i) { for (size_t j = n; j < N; ++j) { core_hash[core_indices[part * 5 + i]](input + j * input_size, input_size, tmp + j * 64); } input = tmp; input_size = 64; } auto f = CnHash::fn(cn_hash[cn_indices[part]], av[t.step], Assembly::AUTO); for (size_t j = n; j < N; j += t.step) { f(tmp + j * 64, 64, output + j * 32, ctx + n, 0); } for (size_t j = n; j < N; ++j) { memcpy(tmp + j * 64, output + j * 32, 32); memset(tmp + j * 64 + 32, 0, 32); } } }); const uint8_t* input = data; size_t input_size = size; for (size_t part = 0; part < 3; ++part) { const AlgoTune& t = tune[cn_indices[part]]; // Allocate scratchpads { uint8_t* p = ctx_memory[0]; for (size_t i = 0, k = 0; i < n; ++i) { if ((i % t.step) == 0) { k = 0; p = ctx_memory[0]; } else if (p - ctx_memory[k] >= (1 << 21)) { ++k; p = ctx_memory[k]; } ctx[i]->memory = p; p += cn_sizes[cn_indices[part]]; } } for (size_t i = 0; i < 5; ++i) { for (size_t j = 0; j < n; ++j) { core_hash[core_indices[part * 5 + i]](input + j * input_size, input_size, tmp + j * 64); } input = tmp; input_size = 64; } auto f = CnHash::fn(cn_hash[cn_indices[part]], av[t.step], Assembly::AUTO); for (size_t j = 0; j < n; j += t.step) { f(tmp + j * 64, 64, output + j * 32, ctx, 0); } for (size_t j = 0; j < n; ++j) { memcpy(tmp + j * 64, output + j * 32, 32); memset(tmp + j * 64 + 32, 0, 32); } } helper->wait(); } else { for (size_t part = 0; part < 3; ++part) { const AlgoTune& t = tune[cn_indices[part]]; // Allocate scratchpads { uint8_t* p = ctx_memory[0]; const size_t n = N / t.threads; // Thread 1 for (size_t i = 0, k = 0; i < n; ++i) { if ((i % t.step) == 0) { k = 0; p = ctx_memory[0]; } else if (p - ctx_memory[k] >= (1 << 21)) { ++k; p = ctx_memory[k]; } ctx[i]->memory = p; p += cn_sizes[cn_indices[part]]; } // Thread 2 for (size_t i = n, k = 4; i < N; ++i) { if ((i % t.step) == 0) { k = 4; p = ctx_memory[4]; } else if (p - ctx_memory[k] >= (1 << 21)) { ++k; p = ctx_memory[k]; } ctx[i]->memory = p; p += cn_sizes[cn_indices[part]]; } } size_t n = N; if (helper && (t.threads == 2)) { n = N / 2; helper->launch_task([data, size, n, &cn_indices, &core_indices, part, &tmp, av, &t, output, ctx]() { const uint8_t* input = data; size_t input_size = size; for (size_t i = 0; i < 5; ++i) { for (size_t j = n; j < N; ++j) { core_hash[core_indices[part * 5 + i]](input + j * input_size, input_size, tmp + j * 64); } input = tmp; input_size = 64; } auto f = CnHash::fn(cn_hash[cn_indices[part]], av[t.step], Assembly::AUTO); for (size_t j = n; j < N; j += t.step) { f(tmp + j * 64, 64, output + j * 32, ctx + n, 0); } for (size_t j = n; j < N; ++j) { memcpy(tmp + j * 64, output + j * 32, 32); memset(tmp + j * 64 + 32, 0, 32); } }); } for (size_t i = 0; i < 5; ++i) { for (size_t j = 0; j < n; ++j) { core_hash[core_indices[part * 5 + i]](data + j * size, size, tmp + j * 64); } data = tmp; size = 64; } auto f = CnHash::fn(cn_hash[cn_indices[part]], av[t.step], Assembly::AUTO); for (size_t j = 0; j < n; j += t.step) { f(tmp + j * 64, 64, output + j * 32, ctx, 0); } for (size_t j = 0; j < n; ++j) { memcpy(tmp + j * 64, output + j * 32, 32); memset(tmp + j * 64 + 32, 0, 32); } if (helper && (t.threads == 2)) { helper->wait(); } } } for (size_t i = 0; i < N; ++i) { ctx[i]->memory = ctx_memory[i]; } } #else // XMRIG_FEATURE_HWLOC void benchmark() {} HelperThread* create_helper_thread(int64_t, int, const std::vector<int64_t>&) { return nullptr; } void destroy_helper_thread(HelperThread*) {} void hash_octa(const uint8_t* data, size_t size, uint8_t* output, cryptonight_ctx** ctx, HelperThread*, bool verbose) { constexpr uint32_t N = 8; // PrevBlockHash (GhostRider's seed) is stored in bytes [4; 36) const uint8_t* seed = data + 4; uint32_t core_indices[15]; select_indices(core_indices, seed); uint32_t cn_indices[6]; select_indices(cn_indices, seed); #ifdef XMRIG_ARM uint32_t step[6] = { 1, 1, 1, 1, 1, 1 }; #else uint32_t step[6] = { 4, 4, 1, 2, 4, 4 }; #endif if (verbose) { static uint32_t prev_indices[3]; if (memcmp(cn_indices, prev_indices, sizeof(prev_indices)) != 0) { memcpy(prev_indices, cn_indices, sizeof(prev_indices)); for (int i = 0; i < 3; ++i) { LOG_INFO("%s GhostRider algo %d: %s", Tags::cpu(), i + 1, cn_names[cn_indices[i]]); } } } const CnHash::AlgoVariant* av = Cpu::info()->hasAES() ? av_hw_aes : av_soft_aes; const cn_hash_fun f[3] = { CnHash::fn(cn_hash[cn_indices[0]], av[step[cn_indices[0]]], Assembly::AUTO), CnHash::fn(cn_hash[cn_indices[1]], av[step[cn_indices[1]]], Assembly::AUTO), CnHash::fn(cn_hash[cn_indices[2]], av[step[cn_indices[2]]], Assembly::AUTO), }; uint8_t tmp[64 * N]; for (uint64_t part = 0; part < 3; ++part) { for (uint64_t i = 0; i < 5; ++i) { for (uint64_t j = 0; j < N; ++j) { core_hash[core_indices[part * 5 + i]](data + j * size, size, tmp + j * 64); data = tmp; size = 64; } } for (uint64_t j = 0, k = step[cn_indices[part]]; j < N; j += k) { f[part](tmp + j * 64, 64, output + j * 32, ctx, 0); } for (uint64_t j = 0; j < N; ++j) { memcpy(tmp + j * 64, output + j * 32, 32); memset(tmp + j * 64 + 32, 0, 32); } } } #endif // XMRIG_FEATURE_HWLOC } // namespace ghostrider } // namespace xmrig
Bendr0id/xmrigCC
src/crypto/ghostrider/ghostrider.cpp
C++
gpl-3.0
26,717
/*! * \file gps_l1_ca_kf_tracking.cc * \brief Implementation of an adapter of a DLL + Kalman carrier * tracking loop block for GPS L1 C/A signals * \author Javier Arribas, 2018. jarribas(at)cttc.es * \author Jordi Vila-Valls 2018. jvila(at)cttc.es * \author Carles Fernandez-Prades 2018. cfernandez(at)cttc.es * * Reference: * J. Vila-Valls, P. Closas, M. Navarro and C. Fernández-Prades, * "Are PLLs Dead? A Tutorial on Kalman Filter-based Techniques for Digital * Carrier Synchronization", IEEE Aerospace and Electronic Systems Magazine, * Vol. 32, No. 7, pp. 28–45, July 2017. DOI: 10.1109/MAES.2017.150260 * * ----------------------------------------------------------------------------- * * GNSS-SDR is a Global Navigation Satellite System software-defined receiver. * This file is part of GNSS-SDR. * * Copyright (C) 2010-2020 (see AUTHORS file for a list of contributors) * SPDX-License-Identifier: GPL-3.0-or-later * * ----------------------------------------------------------------------------- */ #include "gps_l1_ca_kf_tracking.h" #include "GPS_L1_CA.h" #include "configuration_interface.h" #include "gnss_sdr_flags.h" #include <glog/logging.h> GpsL1CaKfTracking::GpsL1CaKfTracking( const ConfigurationInterface* configuration, const std::string& role, unsigned int in_streams, unsigned int out_streams) : role_(role), in_streams_(in_streams), out_streams_(out_streams) { DLOG(INFO) << "role " << role; // ################# CONFIGURATION PARAMETERS ######################## const std::string default_item_type("gr_complex"); std::string item_type = configuration->property(role + ".item_type", default_item_type); int order = configuration->property(role + ".order", 2); int fs_in_deprecated = configuration->property("GNSS-SDR.internal_fs_hz", 2048000); int fs_in = configuration->property("GNSS-SDR.internal_fs_sps", fs_in_deprecated); bool dump = configuration->property(role + ".dump", false); float dll_bw_hz = configuration->property(role + ".dll_bw_hz", static_cast<float>(2.0)); if (FLAGS_dll_bw_hz != 0.0) { dll_bw_hz = static_cast<float>(FLAGS_dll_bw_hz); } float early_late_space_chips = configuration->property(role + ".early_late_space_chips", static_cast<float>(0.5)); const std::string default_dump_filename("./track_ch"); std::string dump_filename = configuration->property(role + ".dump_filename", default_dump_filename); const auto vector_length = static_cast<int>(std::round(fs_in / (GPS_L1_CA_CODE_RATE_CPS / GPS_L1_CA_CODE_LENGTH_CHIPS))); bool bce_run = configuration->property(role + ".bce_run", false); unsigned int bce_ptrans = configuration->property(role + ".p_transient", 0); unsigned int bce_strans = configuration->property(role + ".s_transient", 0); int bce_nu = configuration->property(role + ".bce_nu", 0); int bce_kappa = configuration->property(role + ".bce_kappa", 0); // ################# MAKE TRACKING GNURadio object ################### if (item_type == "gr_complex") { item_size_ = sizeof(gr_complex); tracking_ = gps_l1_ca_kf_make_tracking_cc( order, fs_in, vector_length, dump, dump_filename, dll_bw_hz, early_late_space_chips, bce_run, bce_ptrans, bce_strans, bce_nu, bce_kappa); } else { item_size_ = 0; LOG(WARNING) << item_type << " unknown tracking item type."; } channel_ = 0; DLOG(INFO) << "tracking(" << tracking_->unique_id() << ")"; if (in_streams_ == 0) { in_streams_ = 1; // Avoid compiler warning } if (out_streams_ == 0) { out_streams_ = 1; // Avoid compiler warning } } void GpsL1CaKfTracking::stop_tracking() { } void GpsL1CaKfTracking::start_tracking() { tracking_->start_tracking(); } /* * Set tracking channel unique ID */ void GpsL1CaKfTracking::set_channel(unsigned int channel) { channel_ = channel; tracking_->set_channel(channel); } void GpsL1CaKfTracking::set_gnss_synchro(Gnss_Synchro* p_gnss_synchro) { tracking_->set_gnss_synchro(p_gnss_synchro); } void GpsL1CaKfTracking::connect(gr::top_block_sptr top_block) { if (top_block) { /* top_block is not null */ }; // nothing to connect, now the tracking uses gr_sync_decimator } void GpsL1CaKfTracking::disconnect(gr::top_block_sptr top_block) { if (top_block) { /* top_block is not null */ }; // nothing to disconnect, now the tracking uses gr_sync_decimator } gr::basic_block_sptr GpsL1CaKfTracking::get_left_block() { return tracking_; } gr::basic_block_sptr GpsL1CaKfTracking::get_right_block() { return tracking_; }
gnss-sdr/gnss-sdr
src/algorithms/tracking/adapters/gps_l1_ca_kf_tracking.cc
C++
gpl-3.0
4,965
# dialogs - provide common dialogs # # Copyright (c) 2006 FSF Europe # # Authors: # Sebastian Heinlein <glatzor@ubuntu.com> # Michael Vogt <mvo@canonical.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA from gi.repository import Gtk def show_error_dialog(parent, primary, secondary): p = "<span weight=\"bold\" size=\"larger\">%s</span>" % primary dialog = Gtk.MessageDialog(parent,Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR,Gtk.ButtonsType.CLOSE,"") dialog.set_markup(p); dialog.format_secondary_text(secondary); dialog.run() dialog.hide()
ruibarreira/linuxtrail
usr/lib/python3/dist-packages/softwareproperties/gtk/dialogs.py
Python
gpl-3.0
1,305
using System; using System.Diagnostics; using System.Windows.Forms; using OpenDentBusiness; using CodeBase; using System.IO; namespace OpenDental.Bridges { /// <summary></summary> public class VixWinNumbered { /// <summary></summary> public VixWinNumbered() { } ///<summary>Sends data for Patient.Cur by command line interface.</summary> public static void SendData(Program ProgramCur,Patient pat) { string path=Programs.GetProgramPath(ProgramCur); if(pat==null) { MsgBox.Show("VixWinNumbered","Please select a patient first."); return; } string ppImagePath=ProgramProperties.GetPropVal(ProgramCur.ProgramNum,"Image Path"); if(ppImagePath.Trim()=="") { MsgBox.Show("VixWinNumbered","Missing Image Path."); return; } string subDirNumbers=(pat.PatNum%100).ToString().PadLeft(2,'0');//Take the rightmost 2 numbers, preceeding with 0 if patnum<10 string fullPath=ODFileUtils.CombinePaths(ppImagePath.Trim(),subDirNumbers,pat.PatNum.ToString()); if(!Directory.Exists(fullPath)){ try { Directory.CreateDirectory(fullPath); } catch { MessageBox.Show(Lan.g("VixWinNumbered","Patient image path could not be created. This usually indicates a permission issue. Path")+":\r\n" +fullPath); return; } } //Example: c:\vixwin\vixwin -I 123ABC -N Bill^Smith -P X:\VXImages\02\196402\ string info="-I "; if(ProgramProperties.GetPropVal(ProgramCur.ProgramNum,"Enter 0 to use PatientNum, or 1 to use ChartNum")=="0") { info+=pat.PatNum.ToString(); } else { info+=pat.ChartNumber;//max 64 char } info+=" -N "+pat.FName.Replace(" ","")+"^"+pat.LName.Replace(" ","");//no spaces allowed info+=" -P "+fullPath;//This is the Numbered Mode subdirectory try { Process.Start(path,info); } catch(Exception ex) { MessageBox.Show(ex.Message+"\r\nFile and command line:\r\n"+path+" "+info); } } } }
eae/opendental
OpenDental/Bridges/VixWinNumbered.cs
C#
gpl-3.0
1,939
<?php Sleek\Modules\render_flexible('global_modules', $global_module) ?>
powerbuoy/sleek
modules/global-module/template.php
PHP
gpl-3.0
73
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ // #ifdef __AMLTEXTBOX || __AMLSECRET || __AMLTEXTAREA || __AMLINPUT || __INC_ALL //@todo DOCUMENT the modules too /** * Element displaying a rectangular area wich allows a * user to type information. The information typed can be * restricted by using this.$masking. The information can also * be hidden from view when used in password mode. By adding an * {@link element.autocomplete autocomplete element} as a child the * value for the textbox can be looked up as you type. By setting the * {@link element.textbox.attribute.mask mask atribute}, complex data input * validation is done while the users types. * * @constructor * @define input, secret, textarea, textbox * @allowchild autocomplete, {smartbinding} * @addnode elements * * @inherits apf.StandardBinding * @inherits apf.XForms * * @author Ruben Daniels (ruben AT ajax DOT org) * @version %I%, %G% * @since 0.1 * * @binding value Determines the way the value for the element is retrieved * from the bound data. * Example: * Sets the value based on data loaded into this component. * <code> * <a:model id="mdlTextbox"> * <data name="Lukasz"></data> * </a:model> * <a:textbox model="mdlTextbox" value="[@name]" /> * </code> * Example: * A shorter way to write this is: * <code> * <a:model id="mdlTextbox"> * <data name="Lukasz"></data> * </a:model> * <a:textbox value="[mdlTextbox::@name]" /> * </code> * * @event click Fires when the user presses a mousebutton while over this element and then let's the mousebutton go. * @event mouseup Fires when the user lets go of a mousebutton while over this element. * @event mousedown Fires when the user presses a mousebutton while over this element. * @event keyup Fires when the user lets go of a keyboard button while this element is focussed. * object: * {Number} keyCode which key was pressed. This is an ascii number. * @event clear Fires when the content of this element is cleared. */ apf.input = function(struct, tagName){ this.$init(tagName || "input", apf.NODE_VISIBLE, struct); }; apf.secret = function(struct, tagName){ this.$init(tagName || "secret", apf.NODE_VISIBLE, struct); }; apf.password = function(struct, tagName){ this.$init(tagName || "password", apf.NODE_VISIBLE, struct); }; apf.textarea = function(struct, tagName){ this.$init(tagName || "textarea", apf.NODE_VISIBLE, struct); this.multiline = true; }; // HTML5 email element apf.email = function(struct, tagName){ this.$init(tagName || "email", apf.NODE_VISIBLE, struct); }; apf.textbox = function(struct, tagName){ this.$init(tagName || "textbox", apf.NODE_VISIBLE, struct); }; (function(){ this.implement( //#ifdef __WITH_DATAACTION apf.DataAction //#endif //#ifdef __WITH_XFORMS //,apf.XForms //#endif ); this.$focussable = true; // This object can get the focus this.$masking = false; this.$autoComplete = false; this.$childProperty = "value"; //this.realtime = false; this.value = ""; this.$isTextInput = true; this.multiline = false; /** * @attribute {Boolean} realtime whether the value of the bound data is * updated as the user types it, or only when this element looses focus or * the user presses enter. */ this.$booleanProperties["focusselect"] = true; this.$booleanProperties["realtime"] = true; this.$supportedProperties.push("value", "mask", "initial-message", "focusselect", "realtime", "type"); /** * @attribute {String} value the text of this element * @todo apf3.0 check use of this.$propHandlers["value"].call */ this.$propHandlers["value"] = function(value, prop, force, initial){ if (!this.$input || !initial && this.getValue() == value) return; // Set Value if (!initial && !value && !this.hasFocus()) //@todo apf3.x research the use of clear return this.$clear(); else if (this.isHTMLBox) { if (this.$input.innerHTML != value) this.$input.innerHTML = value; } else if (this.$input.value != value) this.$input.value = value; if (!initial) apf.setStyleClass(this.$ext, "", [this.$baseCSSname + "Initial"]); if (this.$button) this.$button.style.display = value && !initial ? "block" : "none"; }; //See validation //var oldPropHandler = this.$propHandlers["maxlength"]; this.addEventListener("prop.maxlength", function(e){ //Special validation support using nativate max-length browser support if (this.$input.tagName.toLowerCase().match(/input|textarea/)) this.$input.maxLength = parseInt(e.value) || null; }); this.addEventListener("prop.editable", function(e){ if (apf.isIE) this.$input.unselectable = e.value ? "On" : "Off"; else { if (e.value) apf.addListener(this.$input, "mousedown", apf.preventDefault); else apf.removeListener(this.$input, "mousedown", apf.preventDefault); } }); /** * @attribute {String} mask a complex input pattern that the user should * adhere to. This is a string which is a combination of special and normal * characters. Then comma seperated it has two options. The first option * specifies whether the non input characters (the chars not typed by the * user) are in the value of this element. The second option specifies the * character that is displayed when the user hasn't yet filled in a * character. * Characters: * 0 Any digit * 1 The number 1 or 2. * 9 Any digit or a space. * # User can enter a digit, space, plus or minus sign. * L Any alpha character, case insensitive. * ? Any alpha character, case insensitive or space. * A Any alphanumeric character. * a Any alphanumeric character or space. * X Hexadecimal character, case insensitive. * x Hexadecimal character, case insensitive or space. * & Any whitespace. * C Any character. * ! Causes the input mask to fill from left to right instead of from right to left. * ' The start or end of a literal part. * " The start or end of a literal part. * > Converts all characters that follow to uppercase. * < Converts all characters that follow to lowercase. * \ Cancel the special meaning of a character. * Example: * An american style phone number. * <code> * <a:textbox mask="(000)0000-0000;;_" /> * </code> * Example: * A dutch postal code * <code> * <a:textbox mask="0000 AA;;_" /> * </code> * Example: * A date * <code> * <a:textbox mask="00-00-0000;;_" datatype="xsd:date" /> * </code> * Example: * A serial number * <code> * <a:textbox mask="'WCS74'0000-00000;1;_" /> * </code> * Example: * A MAC address * <code> * <a:textbox mask="XX-XX-XX-XX-XX-XX;;_" /> * </code> */ this.$propHandlers["mask"] = function(value){ if (this.mask.toLowerCase() == "password")// || !apf.hasMsRangeObject) return; if (!value) { throw new Error("Not Implemented"); } if (!this.$masking) { this.$masking = true; this.implement(apf.textbox.masking); this.focusselect = false; //this.realtime = false; } this.setMask(this.mask); }; //this.$propHandlers["ref"] = function(value) { // this.$input.setAttribute("name", value.split("/").pop().split("::").pop() // .replace(/[\@\.\(\)]*/g, "")); //}; /** * @attribute {String} initial-message the message displayed by this element * when it doesn't have a value set. This property is inherited from parent * nodes. When none is found it is looked for on the appsettings element. */ this.$propHandlers["initial-message"] = function(value){ if (value) { //#ifdef __WITH_WINDOW_FOCUS if (apf.hasFocusBug) this.$input.onblur(); //#endif //this.$propHandlers["value"].call(this, value, null, true); } if (!this.value) this.$clear(true); if (this.type == "password" && this.$inputInitFix) { this.$inputInitFix.innerHTML = value; apf.setStyleClass(this.$inputInitFix, "initFxEnabled"); } }; /** * @attribute {Boolean} focusselect whether the text in this element is * selected when this element receives focus. */ this.$propHandlers["focusselect"] = function(value){ var _self = this; this.$input.onmousedown = function(){ _self.focusselect = false; }; this.$input.onmouseup = this.$input.onmouseout = function(){ _self.focusselect = value; }; }; /** * @attribute {String} type the type or function this element represents. * This can be any arbitrary name. Although there are some special values. * Possible values: * username this element is used to type in the name part of login credentials. * password this element is used to type in the password part of login credentials. */ this.$propHandlers["type"] = function(value){ if (value && "password|username".indexOf(value) > -1 && typeof this.focusselect == "undefined") { this.focusselect = true; this.$propHandlers["focusselect"].call(this, true); } }; this.$isTextInput = function(e){ return true; }; /**** Public Methods ****/ //#ifdef __WITH_CONVENIENCE_API /** * Sets the value of this element. This should be one of the values * specified in the values attribute. * @param {String} value the new value of this element */ this.setValue = function(value){ return this.setProperty("value", value, false, true); }; this.clear = function(){ this.setProperty("value", ""); } //@todo cleanup and put initial-message behaviour in one location this.$clear = function(noEvent){ if (this["initial-message"]) { apf.setStyleClass(this.$ext, this.$baseCSSname + "Initial"); this.$propHandlers["value"].call(this, this["initial-message"], null, null, true); } else { this.$propHandlers["value"].call(this, "", null, null, true); } if (!noEvent) this.dispatchEvent("clear");//@todo this should work via value change } /** * Returns the current value of this element. * @return {String} */ this.getValue = function(){ var v = this.isHTMLBox ? this.$input.innerHTML : this.$input.value; return v == this["initial-message"] ? "" : v.replace(/\r/g, ""); }; //#endif /** * Selects the text in this element. */ this.select = function(){ try { this.$input.select(); } catch(e){} }; /** * Deselects the text in this element. */ this.deselect = function(){this.$input.deselect();}; /**** Private Methods *****/ this.$enable = function(){this.$input.disabled = false;}; this.$disable = function(){this.$input.disabled = true;}; this.$insertData = function(str){ return this.setValue(str); }; /** * @private */ this.insert = function(text){ if (apf.hasMsRangeObject) { try { this.$input.focus(); } catch(e) {} var range = document.selection.createRange(); if (this.oninsert) text = this.oninsert(text); range.pasteHTML(text); range.collapse(true); range.select(); } else { this.$input.value += text; } }; this.addEventListener("$clear", function(){ this.value = "";//@todo what about property binding? if (this["initial-message"] && apf.document.activeElement != this) { this.$propHandlers["value"].call(this, this["initial-message"], null, null, true); apf.setStyleClass(this.$ext, this.$baseCSSname + "Initial"); } else { this.$propHandlers["value"].call(this, ""); } if (!this.$input.tagName.toLowerCase().match(/input|textarea/i)) { if (apf.hasMsRangeObject) { try { var range = document.selection.createRange(); range.moveStart("sentence", -1); //range.text = ""; range.select(); } catch(e) {} } } this.dispatchEvent("clear"); //@todo apf3.0 }); this.$keyHandler = function(key, ctrlKey, shiftKey, altKey, e){ if (this.$button && key == 27) { //this.$clear(); if (this.value) { this.change(""); e.stopPropagation(); } //this.focus({mouse:true}); } /*if (this.dispatchEvent("keydown", { keyCode : key, ctrlKey : ctrlKey, shiftKey : shiftKey, altKey : altKey, htmlEvent : e}) === false) return false; // @todo: revisit this IF statement - dead code? if (false && apf.isIE && (key == 86 && ctrlKey || key == 45 && shiftKey)) { var text = window.clipboardData.getData("Text"); if ((text = this.dispatchEvent("keydown", { text : this.onpaste(text)}) === false)) return false; if (!text) text = window.clipboardData.getData("Text"); this.$input.focus(); var range = document.selection.createRange(); range.text = ""; range.collapse(); range.pasteHTML(text.replace(/\n/g, "<br />").replace(/\t/g, "&nbsp;&nbsp;&nbsp;")); return false; }*/ }; this.$registerElement = function(oNode) { if (!oNode) return; if (oNode.localName == "autocomplete") this.$autoComplete = oNode; }; var fTimer; this.$focus = function(e){ if (!this.$ext || this.$ext.disabled) return; this.$setStyleClass(this.$ext, this.$baseCSSname + "Focus"); if (this["initial-message"] && this.$input.value == this["initial-message"]) { this.$propHandlers["value"].call(this, "", null, null, true); apf.setStyleClass(this.$ext, "", [this.$baseCSSname + "Initial"]); } var _self = this; function delay(){ try { if (!fTimer || document.activeElement != _self.$input) { _self.$input.focus(); } else { clearInterval(fTimer); return; } } catch(e) {} if (_self.$masking) _self.setPosition(); if (_self.focusselect) _self.select(); }; if ((!e || e.mouse) && apf.isIE) { clearInterval(fTimer); fTimer = setInterval(delay, 1); } else delay(); }; this.$blur = function(e){ if (!this.$ext) return; if (!this.realtime) this.change(this.getValue()); this.$setStyleClass(this.$ext, "", [this.$baseCSSname + "Focus", "capsLock"]); if (this["initial-message"] && this.$input.value == "") { this.$propHandlers["value"].call(this, this["initial-message"], null, null, true); apf.setStyleClass(this.$ext, this.$baseCSSname + "Initial"); } /*if (apf.hasMsRangeObject) { var r = this.$input.createTextRange(); r.collapse(); r.select(); }*/ try { if (apf.isIE || !e || e.srcElement != apf.window) this.$input.blur(); } catch(e) {} // check if we clicked on the oContainer. ifso dont hide it if (this.oContainer) { $setTimeout("var o = apf.lookup(" + this.$uniqueId + ");\ o.oContainer.style.display = 'none'", 100); } clearInterval(fTimer); }; /**** Init ****/ this.$draw = function(){ var _self = this, typedBefore = false; //#ifdef __AMLCODEEDITOR if (this.localName == "codeeditor") { this.skin = "textarea"; this.$loadSkin(); } //#endif //Build Main Skin this.$ext = this.$getExternal(null, null, function(oExt){ var mask = this.getAttribute("mask"); if ((typeof mask == "string" && mask.toLowerCase() == "password") || "secret|password".indexOf(this.localName) > -1) { this.type = "password"; this.$getLayoutNode("main", "input").setAttribute("type", "password"); } //#ifdef __WITH_HTML5 else if (this.localName == "email") { this.datatype = (this.prefix ? this.prefix + ":" : "") + "email"; this.$propHandlers["datatype"].call(this, this.datatype, "datatype"); } else if (this.localName == "url") { this.datatype = (this.prefix ? this.prefix + ":" : "") + "url"; this.$propHandlers["datatype"].call(this, this.datatype, "datatype"); } //#endif oExt.setAttribute("onmousedown", "if (!this.host.disabled) \ this.host.dispatchEvent('mousedown', {htmlEvent : event});"); oExt.setAttribute("onmouseup", "if (!this.host.disabled) \ this.host.dispatchEvent('mouseup', {htmlEvent : event});"); oExt.setAttribute("onclick", "if (!this.host.disabled) \ this.host.dispatchEvent('click', {htmlEvent : event});"); }); this.$input = this.$getLayoutNode("main", "input", this.$ext); this.$button = this.$getLayoutNode("main", "button", this.$ext); this.$inputInitFix = this.$getLayoutNode("main", "initialfix", this.$ext); if (this.type == "password") this.$propHandlers["type"].call(this, "password"); if (!apf.hasContentEditable && "input|textarea".indexOf(this.$input.tagName.toLowerCase()) == -1) { var node = this.$input; this.$input = node.parentNode.insertBefore(document.createElement("textarea"), node); node.parentNode.removeChild(node); this.$input.className = node.className; if (this.$ext == node) this.$ext = this.$input; } if (this.$button) { this.$button.onmousedown = function(){ _self.$clear(); //@todo why are both needed for doc filter _self.change(""); //@todo only this one should be needed _self.focus({mouse:true}); } } //@todo for skin switching this should be removed if (this.$input.tagName.toLowerCase() == "textarea") { this.addEventListener("focus", function(e){ //if (this.multiline != "optional") //e.returnValue = false }); } this.$input.onselectstart = function(e){ if (!e) e = event; e.cancelBubble = true; } this.$input.host = this; this.$input.onkeydown = function(e){ e = e || window.event; if (this.host.disabled) { e.returnValue = false; return false; } //Change if (!_self.realtime) { var value = _self.getValue(); if (e.keyCode == 13 && value != _self.value) _self.change(value); } else if (apf.isWebkit && _self.xmlRoot && _self.getValue() != _self.value) //safari issue (only old??) $setTimeout("var o = apf.lookup(" + _self.$uniqueId + ");\ o.change(o.getValue())"); if (_self.multiline == "optional" && e.keyCode == 13 && !e.shiftKey || e.ctrlKey && (e.keyCode == 66 || e.keyCode == 73 || e.keyCode == 85)) { e.returnValue = false; return false; } if (typedBefore && this.getAttribute("type") == "password" && this.value != "") { var hasClass = (_self.$ext.className.indexOf("capsLock") > -1), capsKey = (e.keyCode === 20); if (capsKey) // caps off apf.setStyleClass(_self.$ext, hasClass ? null : "capsLock", hasClass ? ["capsLock"] : null); } //Autocomplete if (_self.$autoComplete || _self.oContainer) { var keyCode = e.keyCode; $setTimeout(function(){ if (_self.$autoComplete) _self.$autoComplete.fillAutocomplete(keyCode); else _self.fillAutocomplete(keyCode); }); } //Non this.$masking if (!_self.mask) { return _self.$keyHandler(e.keyCode, e.ctrlKey, e.shiftKey, e.altKey, e); } }; this.$input.onkeyup = function(e){ if (!e) e = event; if (this.host.disabled) return false; var keyCode = e.keyCode; if (_self.$button) _self.$button.style.display = this.value ? "block" : "none"; if (_self.realtime) { $setTimeout(function(){ var v; if (!_self.mask && (v = _self.getValue()) != _self.value) _self.change(v); _self.dispatchEvent("keyup", {keyCode : keyCode});//@todo }); } else { _self.dispatchEvent("keyup", {keyCode : keyCode});//@todo } //#ifdef __WITH_VALIDATION if (_self.isValid && _self.isValid() && e.keyCode != 13 && e.keyCode != 17) _self.clearError(); //#endif }; //#ifdef __WITH_WINDOW_FOCUS if (apf.hasFocusBug) apf.sanitizeTextbox(this.$input); //#endif if (apf.hasAutocompleteXulBug) this.$input.setAttribute("autocomplete", "off"); if ("INPUT|TEXTAREA".indexOf(this.$input.tagName) == -1) { this.isHTMLBox = true; this.$input.unselectable = "Off"; this.$input.contentEditable = true; this.$input.style.width = "1px"; this.$input.select = function(){ var r = document.selection.createRange(); r.moveToElementText(this); r.select(); } }; this.$input.deselect = function(){ if (!document.selection) return; var r = document.selection.createRange(); r.collapse(); r.select(); }; var f; apf.addListener(this.$input, "keypress", f = function(e) { if (_self.$input.getAttribute("type") != "password") return apf.removeListener(_self.$input, "keypress", f); e = e || window.event; // get key pressed var which = -1; if (e.which) which = e.which; else if (e.keyCode) which = e.keyCode; // get shift status var shift_status = false; if (e.shiftKey) shift_status = e.shiftKey; else if (e.modifiers) shift_status = !!(e.modifiers & 4); if (((which >= 65 && which <= 90) && !shift_status) || ((which >= 97 && which <= 122) && shift_status)) { // uppercase, no shift key apf.setStyleClass(_self.$ext, "capsLock"); } else { apf.setStyleClass(_self.$ext, null, ["capsLock"]); } typedBefore = true; }); }; this.$loadAml = function() { if (typeof this["initial-message"] == "undefined") this.$setInheritedAttribute("initial-message"); if (typeof this.realtime == "undefined") this.$setInheritedAttribute("realtime"); } this.addEventListener("DOMNodeRemovedFromDocument", function(){ if (this.$button) this.$button.onmousedown = null; if (this.$input) { this.$input.onkeypress = this.$input.onmouseup = this.$input.onmouseout = this.$input.onmousedown = this.$input.onkeydown = this.$input.onkeyup = this.$input.onselectstart = null; } }); // #ifdef __WITH_DATABINDING }).call(apf.textbox.prototype = new apf.StandardBinding()); /* #else }).call(apf.textbox.prototype = new apf.Presentation()); #endif*/ apf.config.$inheritProperties["initial-message"] = 1; apf.config.$inheritProperties["realtime"] = 1; apf.input.prototype = apf.secret.prototype = apf.password.prototype = apf.textarea.prototype = apf.email.prototype = apf.textbox.prototype; apf.aml.setElement("input", apf.input); apf.aml.setElement("secret", apf.secret); apf.aml.setElement("password", apf.password); apf.aml.setElement("textarea", apf.textarea); apf.aml.setElement("textbox", apf.textbox); // #endif
tfe/cloud9
support/apf/elements/textbox.js
JavaScript
gpl-3.0
27,330
// -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // DESCRIPTION: Verilator: Add temporaries, such as for changed nodes // // Code available from: http://www.veripool.org/verilator // //************************************************************************* // // Copyright 2003-2013 by Wilson Snyder. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License // Version 2.0. // // Verilator 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. // //************************************************************************* // V3Changed's Transformations: // // Each module: // Each combo block // For each variable that comes from combo block and is generated AFTER a usage // Add __Vlast_{var} to local section, init to current value (just use array?) // Change = if any var != last. // If a signal is used as a clock in this module or any // module *below*, and it isn't a input to this module, // we need to indicate a new clock has been created. // //************************************************************************* #include "config_build.h" #include "verilatedos.h" #include <cstdio> #include <cstdarg> #include <unistd.h> #include <algorithm> #include <set> #include "V3Global.h" #include "V3Ast.h" #include "V3Changed.h" #include "V3EmitCBase.h" //###################################################################### // Changed state, as a visitor of each AstNode class ChangedVisitor : public AstNVisitor { private: // NODE STATE // Entire netlist: // AstVarScope::user1() -> bool. True indicates processed AstUser1InUse m_inuser1; // STATE AstNodeModule* m_topModp; // Top module AstScope* m_scopetopp; // Scope under TOPSCOPE AstCFunc* m_chgFuncp; // Change function we're building // CONSTANTS enum MiscConsts { DETECTARRAY_MAX_INDEXES = 256 // How many indexes before error // Ok to increase this, but may result in much slower model }; // METHODS static int debug() { static int level = -1; if (VL_UNLIKELY(level < 0)) level = v3Global.opt.debugSrcLevel(__FILE__); return level; } AstNode* aselIfNeeded(bool isArray, int index, AstNode* childp) { if (isArray) { return new AstArraySel(childp->fileline(), childp, new AstConst(childp->fileline(), index)); } else { return childp; } } void genChangeDet(AstVarScope* vscp) { #ifdef NEW_ORDERING vscp->v3fatalSrc("Not applicable\n"); #endif AstVar* varp = vscp->varp(); vscp->v3warn(IMPERFECTSCH,"Imperfect scheduling of variable: "<<vscp); AstUnpackArrayDType* arrayp = varp->dtypeSkipRefp()->castUnpackArrayDType(); AstStructDType *structp = varp->dtypeSkipRefp()->castStructDType(); bool isArray = arrayp; bool isStruct = structp && structp->packed(); int elements = isArray ? arrayp->elementsConst() : 1; if (isArray && (elements > DETECTARRAY_MAX_INDEXES)) { vscp->v3warn(E_DETECTARRAY, "Unsupported: Can't detect more than "<<cvtToStr(DETECTARRAY_MAX_INDEXES) <<" array indexes (probably with UNOPTFLAT warning suppressed): "<<varp->prettyName()<<endl <<vscp->warnMore() <<"... Could recompile with DETECTARRAY_MAX_INDEXES increased to at least "<<cvtToStr(elements)); } else if (!isArray && !isStruct && !varp->dtypeSkipRefp()->castBasicDType()) { if (debug()) varp->dumpTree(cout,"-DETECTARRAY-"); vscp->v3warn(E_DETECTARRAY, "Unsupported: Can't detect changes on complex variable (probably with UNOPTFLAT warning suppressed): "<<varp->prettyName()); } else { string newvarname = "__Vchglast__"+vscp->scopep()->nameDotless()+"__"+varp->shortName(); // Create: VARREF(_last) // ASSIGN(VARREF(_last), VARREF(var)) // ... // CHANGEDET(VARREF(_last), VARREF(var)) AstVar* newvarp = new AstVar (varp->fileline(), AstVarType::MODULETEMP, newvarname, varp); m_topModp->addStmtp(newvarp); AstVarScope* newvscp = new AstVarScope(vscp->fileline(), m_scopetopp, newvarp); m_scopetopp->addVarp(newvscp); for (int index=0; index<elements; ++index) { AstChangeDet* changep = new AstChangeDet (vscp->fileline(), aselIfNeeded(isArray, index, new AstVarRef(vscp->fileline(), vscp, false)), aselIfNeeded(isArray, index, new AstVarRef(vscp->fileline(), newvscp, false)), false); m_chgFuncp->addStmtsp(changep); AstAssign* initp = new AstAssign (vscp->fileline(), aselIfNeeded(isArray, index, new AstVarRef(vscp->fileline(), newvscp, true)), aselIfNeeded(isArray, index, new AstVarRef(vscp->fileline(), vscp, false))); m_chgFuncp->addFinalsp(initp); } } } // VISITORS virtual void visit(AstNodeModule* nodep, AstNUser*) { UINFO(4," MOD "<<nodep<<endl); if (nodep->isTop()) { m_topModp = nodep; } nodep->iterateChildren(*this); } virtual void visit(AstTopScope* nodep, AstNUser*) { UINFO(4," TS "<<nodep<<endl); // Clearing AstNode::user1ClearTree(); // Create the change detection function AstScope* scopep = nodep->scopep(); if (!scopep) nodep->v3fatalSrc("No scope found on top level, perhaps you have no statements?\n"); m_scopetopp = scopep; // Create change detection function m_chgFuncp = new AstCFunc(nodep->fileline(), "_change_request", scopep, "IData"); m_chgFuncp->argTypes(EmitCBaseVisitor::symClassVar()); m_chgFuncp->symProlog(true); m_chgFuncp->declPrivate(true); m_scopetopp->addActivep(m_chgFuncp); // We need at least one change detect so we know to emit the correct code m_chgFuncp->addStmtsp(new AstChangeDet(nodep->fileline(), NULL, NULL, false)); // nodep->iterateChildren(*this); } virtual void visit(AstVarScope* nodep, AstNUser*) { if (nodep->isCircular()) { UINFO(8," CIRC "<<nodep<<endl); if (!nodep->user1SetOnce()) { genChangeDet(nodep); } } } //-------------------- // Default: Just iterate virtual void visit(AstNode* nodep, AstNUser*) { nodep->iterateChildren(*this); } public: // CONSTUCTORS ChangedVisitor(AstNetlist* nodep) { m_topModp = NULL; m_chgFuncp = NULL; m_scopetopp = NULL; nodep->accept(*this); } virtual ~ChangedVisitor() {} }; //###################################################################### // Changed class functions void V3Changed::changedAll(AstNetlist* nodep) { UINFO(2,__FUNCTION__<<": "<<endl); ChangedVisitor visitor (nodep); }
rporter/verilator
src/V3Changed.cpp
C++
gpl-3.0
6,798
#region License Information (GPL v3) /* ShareX - A program that allows you to take screenshots and share any file type Copyright (c) 2007-2020 ShareX Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Optionally you can also view the license at <http://www.gnu.org/licenses/>. */ #endregion License Information (GPL v3) using ShareX.HelpersLib; using ShareX.ScreenCaptureLib; using System.Drawing; using System.Windows.Forms; namespace ShareX { public class CaptureRegion : CaptureBase { protected static RegionCaptureType lastRegionCaptureType = RegionCaptureType.Default; public RegionCaptureType RegionCaptureType { get; protected set; } public CaptureRegion() { } public CaptureRegion(RegionCaptureType regionCaptureType) { RegionCaptureType = regionCaptureType; } protected override ImageInfo Execute(TaskSettings taskSettings) { switch (RegionCaptureType) { default: case RegionCaptureType.Default: return ExecuteRegionCapture(taskSettings); case RegionCaptureType.Light: return ExecuteRegionCaptureLight(taskSettings); case RegionCaptureType.Transparent: return ExecuteRegionCaptureTransparent(taskSettings); } } protected ImageInfo ExecuteRegionCapture(TaskSettings taskSettings) { ImageInfo imageInfo = new ImageInfo(); RegionCaptureMode mode; if (taskSettings.AdvancedSettings.RegionCaptureDisableAnnotation) { mode = RegionCaptureMode.Default; } else { mode = RegionCaptureMode.Annotation; } Screenshot screenshot = TaskHelpers.GetScreenshot(taskSettings); screenshot.CaptureCursor = false; Bitmap bmp = screenshot.CaptureFullscreen(); CursorData cursorData = null; if (taskSettings.CaptureSettings.ShowCursor) { cursorData = new CursorData(); } using (RegionCaptureForm form = new RegionCaptureForm(mode, taskSettings.CaptureSettingsReference.SurfaceOptions, bmp)) { if (cursorData != null && cursorData.IsVisible) { form.AddCursor(cursorData.Handle, CaptureHelpers.ScreenToClient(cursorData.Position)); } form.ShowDialog(); imageInfo.Image = form.GetResultImage(); if (imageInfo.Image != null) { if (form.IsModified) { AllowAnnotation = false; } if (form.Result == RegionResult.Region && taskSettings.UploadSettings.RegionCaptureUseWindowPattern) { WindowInfo windowInfo = form.GetWindowInfo(); imageInfo.UpdateInfo(windowInfo); } lastRegionCaptureType = RegionCaptureType.Default; } } return imageInfo; } protected ImageInfo ExecuteRegionCaptureLight(TaskSettings taskSettings) { Bitmap bmp = null; using (RegionCaptureLightForm rectangleLight = new RegionCaptureLightForm(TaskHelpers.GetScreenshot(taskSettings))) { if (rectangleLight.ShowDialog() == DialogResult.OK) { bmp = rectangleLight.GetAreaImage(); if (bmp != null) { lastRegionCaptureType = RegionCaptureType.Light; } } } return new ImageInfo(bmp); } protected ImageInfo ExecuteRegionCaptureTransparent(TaskSettings taskSettings) { Bitmap bmp = null; using (RegionCaptureTransparentForm rectangleTransparent = new RegionCaptureTransparentForm()) { if (rectangleTransparent.ShowDialog() == DialogResult.OK) { bmp = rectangleTransparent.GetAreaImage(TaskHelpers.GetScreenshot(taskSettings)); if (bmp != null) { lastRegionCaptureType = RegionCaptureType.Transparent; } } } return new ImageInfo(bmp); } } }
Scrxtchy/ShareX
ShareX/CaptureHelpers/CaptureRegion.cs
C#
gpl-3.0
5,306
/* ------------------------------------------------------------- Copyright (c) MMXIII Atle Solbakken atle@goliathdns.no ------------------------------------------------------------- This file is part of P* (P-star). P* 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. P* 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 P*. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------- */ #include "program.h" #include "parser.h" #include "pragma.h" #include "types.h" #include "value.h" #include "value_array.h" #include "value_string.h" #include "value_int.h" #include "namespace_session.h" #include "io.h" #include <utility> #include <memory> static mutex init_lock; static bool initialized = false; #ifndef WIN32 static list<wpl_module_loader> modules; #endif wpl_program::wpl_program(wpl_io &io, int argc, char **argv) : parser(io, 0) { #ifndef WIN32 { lock_guard<mutex> lock(init_lock); if (!initialized) { char *dummy; modules.emplace_back(0, &dummy, "mysql"); initialized = true; } } #endif /* WIN32 */ wpl_types_add_all_to_namespace(this); wpl_pragma_add_all_to_namespace(this); unique_ptr<wpl_value_array> val_argv ( new wpl_value_array ( wpl_type_global_string, argc ) ); for (int i = 0; i < argc; i++) { val_argv->set (i, new wpl_value_string(argv[i])); } wpl_variable_holder new_variable ("argv", val_argv.release(), WPL_VARIABLE_ACCESS_PRIVATE); new_variable.setStatic(); register_identifier(&new_variable); #ifndef WIN32 for (wpl_module_loader &module : modules) { insert_parent_namespace(module.get_namespace()); } #endif } void wpl_program::parse_file (const char *filename) { parser.parse_file(this, filename); } int wpl_program::run(wpl_io &io) { int ret; wpl_value *value; wpl_value_return retval; wpl_namespace_session nss; copy_variables_to_namespace_session (&nss); wpl_scene *main; if (!(main = find_scene("main"))) { throw runtime_error("Could not find 'SCENE main'"); } wpl_value_int return_value; wpl_block_state program_state(NULL, &io, this); unique_ptr<wpl_state> main_state(main->new_state(&program_state, &io)); ret = main->run(main_state.get(), &return_value); return return_value.get(); }
geirda/P-star
src/libwpl/program.cpp
C++
gpl-3.0
2,689
package com.novaviper.tetracraft.common.init; import net.minecraft.item.Item; import com.novaviper.cryolib.lib.Registers; import com.novaviper.tetracraft.common.item.ItemContinousBow; import com.novaviper.tetracraft.common.item.ItemModGenericItem; import com.novaviper.tetracraft.lib.ModReference; /** * @author NovaViper <nova.gamez15@gmail.com> * @date 7/10/2016 * @purpose Main class for defining and loading all items */ public class ModItems { public static Item ballisticBow; public static Item triaxIngot; public static Item breedingBone; public static void load(){ ballisticBow = Registers.addItem(new ItemContinousBow("ballisticBow", ModCreativeTabs.tetraTab, "ballistic", 500, 10)); triaxIngot = Registers.addItem(new ItemModGenericItem("triaxIngot", ModCreativeTabs.tetraTab)); breedingBone = Registers.addItem(new ItemModGenericItem("breedingBone", ModCreativeTabs.tetraTab)); } public static void loadRenderersAndVariants(){ addItemRender(ballisticBow, 0, "ballisticBow"); addItemRender(triaxIngot, 0, "triaxIngot"); addItemRender(breedingBone, 0, "breedingBone"); } public static void addItemRender(Item item, int metadata, String itemString){ Registers.addItemRender(ModReference.MOD_ID, item, metadata, itemString); } }
NovaViper/TetraCraft
src-1.9.4/main/java/com/novaviper/tetracraft/common/init/ModItems.java
Java
gpl-3.0
1,268
package com.javalego.erp.model.editors; import java.util.Collection; import java.util.List; import com.javalego.erp.model.Icons; import com.javalego.erp.model.Texts; import com.javalego.erp.model.entity.CategoriaProfesional; import com.javalego.erp.model.entity.Departamento; import com.javalego.erp.model.entity.Empleado; import com.javalego.erp.model.entity.Empresa; import com.javalego.exception.LocalizedException; import com.javalego.security.annotation.PermitAll; import com.javalego.ui.UIContext; import com.javalego.ui.condition.ConditionType; import com.javalego.ui.field.impl.DateFieldModel; import com.javalego.ui.field.impl.EmailFieldModel; import com.javalego.ui.field.impl.ImageFieldModel; import com.javalego.ui.field.impl.PhoneNumberFieldModel; import com.javalego.ui.field.impl.TextFieldModel; import com.javalego.ui.filter.impl.FilterParam; import com.javalego.ui.filter.impl.FilterParamsService; import com.javalego.ui.mvp.beans.view.list.adapter.ListBeansViewAdapter; import com.javalego.ui.mvp.editor.rules.IEditionRulesListener.ValueChangeEvent; import com.javalego.ui.mvp.nestedbean.imp.NestedBeanListValues; import com.javalego.util.StringUtils; /** * Formulario de mantenimiento de Tarifas de Productos * * @author ROBERTO RANZ * */ @PermitAll public class EditorEmpleados extends BaseEditor<Empleado> { private static final long serialVersionUID = -8571636754447755369L; /** * Constructor para inicializar modelo. */ public EditorEmpleados() { setTitle(Texts.EMPLEADOS); setIcon(Icons.PEOPLE); setEditionTitle(Texts.EMPLEADO); // Campos addFieldModel(new TextFieldModel(EMPRESA_NOMBRE, Texts.EMPRESA, true).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(DEPARTAMENTO_NOMBRE, Texts.DEPARTAMENTO, true).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(CATEGORIA_NOMBRE, Texts.CATEGORIA, true).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(NOMBRE, Texts.NOMBRE).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(NIF, Texts.NIF).setMaxSize(20)); addFieldModel(new DateFieldModel(ALTA, Texts.FECHA_ALTA).setReadOnly(true)); addFieldModel(new PhoneNumberFieldModel(TELEFONO, Texts.TELEFONO).setMaxSize(15)); addFieldModel(new PhoneNumberFieldModel(MOVIL, Texts.MOVIL).setMaxSize(15)); addFieldModel(new EmailFieldModel(EMAIL, Texts.EMAIL).setMaxSize(130).setColumns(40)); addFieldModel(new TextFieldModel(DOMICILIO, Texts.DIRECCION)); addFieldModel(new ImageFieldModel(FOTO, Texts.FOTO)); // Filtros basado en campos del editor. Se crea el presenter para la // edición de los campos que constituyen los parámetros del filtro addFilterService(new FilterParamsService(Texts.NOMBRE, new FilterParam(NOMBRE, Texts.NOMBRE, ConditionType.CONTAINS))); addFilterService(new FilterParamsService(Texts.DIRECCION, new FilterParam(DOMICILIO, Texts.DIRECCION, ConditionType.CONTAINS))); addFilterService(new FilterParamsService(Texts.NIF, new FilterParam(NIF, Texts.NIF, ConditionType.CONTAINS))); addFilterService(new FilterParamsService(Texts.EMAIL, new FilterParam(EMAIL, Texts.EMAIL, ConditionType.CONTAINS))); // Servicios del editor para beans nested relacionados. EditorServices<Empleado> services = new EditorServices<Empleado>(); setEditorServices(services); services.addNestedFieldModel(DEPARTAMENTO_NOMBRE, new NestedBeanListValues<Empleado, Departamento>() { @Override public void valueChangeEvent(ValueChangeEvent event) throws LocalizedException { if (getDataProvider() != null) { Departamento e = (Departamento) getDataProvider().find(Departamento.class, "nombre = '" + event.getValue() + "'"); if (e != null) { event.getEditorRules().setValue(DEPARTAMENTO_ID, e.getId()); } else { event.getEditorRules().setValue(DEPARTAMENTO_ID, null); event.getEditorRules().setValue(DEPARTAMENTO_NOMBRE, null); } } } @SuppressWarnings("unchecked") @Override public Collection<String> getKeys(String constraint) throws LocalizedException { return getDataProvider() == null ? null : (Collection<String>) getDataProvider().propertyValues(Departamento.class, NOMBRE, constraint != null ? "nombre like'" + constraint + "%'" : null, NOMBRE); } @Override public boolean isAutoComplete() { return false; } }); services.addNestedFieldModel(CATEGORIA_NOMBRE, new NestedBeanListValues<Empleado, CategoriaProfesional>() { @Override public void valueChangeEvent(ValueChangeEvent event) throws LocalizedException { if (getDataProvider() != null) { CategoriaProfesional e = (CategoriaProfesional) getDataProvider().find(CategoriaProfesional.class, "nombre = '" + event.getValue() + "'"); if (e != null) { event.getEditorRules().setValue(CATEGORIA_ID, e.getId()); } else { event.getEditorRules().setValue(CATEGORIA_ID, null); event.getEditorRules().setValue(CATEGORIA_NOMBRE, null); } } } @SuppressWarnings("unchecked") @Override public Collection<String> getKeys(String constraint) throws LocalizedException { return getDataProvider() == null ? null : (Collection<String>) getDataProvider().propertyValues(CategoriaProfesional.class, NOMBRE, constraint != null ? "nombre like'" + constraint + "%'" : null, NOMBRE); } @Override public boolean isAutoComplete() { return false; } }); services.addNestedFieldModel(EMPRESA_NOMBRE, new NestedBeanListValues<Empleado, Empresa>() { @Override public void valueChangeEvent(ValueChangeEvent event) throws LocalizedException { if (getDataProvider() != null) { Empresa e = (Empresa) getDataProvider().find(Empresa.class, "nombre = '" + event.getValue() + "'"); if (e != null) { event.getEditorRules().setValue(EMPRESA_ID, e.getId()); } else { event.getEditorRules().setValue(EMPRESA_ID, null); event.getEditorRules().setValue(EMPRESA_NOMBRE, null); } } } @SuppressWarnings("unchecked") @Override public Collection<String> getKeys(String constraint) throws LocalizedException { return getDataProvider() == null ? null : (Collection<String>) getDataProvider().propertyValues(Empresa.class, NOMBRE, constraint != null ? "nombre like'" + constraint + "%'" : null, NOMBRE); } @Override public boolean isAutoComplete() { return false; } }); // Vistas de datos del bean addFormatView(new ListBeansViewAdapter<Empleado>(UIContext.getText(Texts.NOMBRE) + " + " + UIContext.getText(Texts.DEPARTAMENTO), FOTO) { @Override public String toHtml(Empleado bean) { return "<h2>" + bean.getNombre() + "</h2>" + (bean.getDepartamento() != null ? bean.getDepartamento().getNombre() : "") + "<br>" + (bean.getEmpresa() != null ? bean.getEmpresa().getNombre() : ""); } }); } @Override public Collection<Empleado> getBeans(String filter, String order) throws LocalizedException { Collection<Empleado> list = getDataServices().getEmpleados(filter, order); if (order != null && list != null && list.size() > 1) { StringUtils.sortList((List<?>) list, NOMBRE); } return list; } @Override public Class<Empleado> getBeanClass() { return Empleado.class; } }
rranz/meccano4j_vaadin
javalego/javalego-app-erp-model/src/main/java/com/javalego/erp/model/editors/EditorEmpleados.java
Java
gpl-3.0
7,451
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Carriers.cs" company="Allors bvba"> // Copyright 2002-2012 Allors bvba. // Dual Licensed under // a) the General Public Licence v3 (GPL) // b) the Allors License // The GPL License is included in the file gpl.txt. // The Allors License is an addendum to your contract. // Allors Applications 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. // For more information visit http://www.allors.com/legal // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Allors.Domain { using System; public partial class Carriers { public static readonly Guid GlsId = new Guid("69C1CD1D-4D4E-4F2D-AF3C-4E1F740C7F62"); public static readonly Guid UpsId = new Guid("74331516-5A0E-48F5-9166-75CC53E8B25D"); public static readonly Guid FedexId = new Guid("D626E669-6AA9-40D1-B18B-5B06564C59A4"); public static readonly Guid DhlId = new Guid("4901794C-B611-4DE4-8613-183B1C08E0AD"); private UniquelyIdentifiableSticky<Carrier> cache; public Carrier Gls => this.Cache[GlsId]; public Carrier Ups => this.Cache[UpsId]; public Carrier Fedex => this.Cache[FedexId]; public Carrier Dhl => this.Cache[DhlId]; private UniquelyIdentifiableSticky<Carrier> Cache => this.cache ?? (this.cache = new UniquelyIdentifiableSticky<Carrier>(this.Session)); protected override void AppsSetup(Setup setup) { base.AppsSetup(setup); new CarrierBuilder(this.Session).WithName("GLS").WithUniqueId(GlsId).Build(); new CarrierBuilder(this.Session).WithName("UPS").WithUniqueId(UpsId).Build(); new CarrierBuilder(this.Session).WithName("FEDEX").WithUniqueId(FedexId).Build(); new CarrierBuilder(this.Session).WithName("DHL").WithUniqueId(DhlId).Build(); } } }
Allors/allors
Domains/Apps/Database/Domain/Export/Apps/Relation/Carriers.cs
C#
gpl-3.0
2,218
import accounting from "accounting-js"; import _ from "lodash"; import { Meteor } from "meteor/meteor"; import $ from "jquery"; import { Template } from "meteor/templating"; import { ReactiveVar } from "meteor/reactive-var"; import { i18next, Logger, formatNumber, Reaction } from "/client/api"; import { NumericInput } from "/imports/plugins/core/ui/client/components"; import { Orders, Shops, Packages } from "/lib/collections"; import { ButtonSelect } from "../../../../ui/client/components/button"; import DiscountList from "/imports/plugins/core/discounts/client/components/list"; import InvoiceContainer from "../../containers/invoiceContainer.js"; import LineItemsContainer from "../../containers/lineItemsContainer.js"; import TotalActionsContainer from "../../containers/totalActionsContainer.js"; // helper to return the order payment object // the first credit paymentMethod on the order // returns entire payment method function orderCreditMethod(order) { return order.billing.filter(value => value.paymentMethod.method === "credit")[0]; } // // core order shipping invoice templates // Template.coreOrderShippingInvoice.onCreated(function () { this.state = new ReactiveDict(); this.refunds = new ReactiveVar([]); this.refundAmount = new ReactiveVar(0.00); this.state.setDefault({ isCapturing: false, isRefunding: false, isFetching: true }); this.autorun(() => { const currentData = Template.currentData(); const order = Orders.findOne(currentData.orderId); const shop = Shops.findOne({}); this.state.set("order", order); this.state.set("currency", shop.currencies[shop.currency]); if (order) { Meteor.call("orders/refunds/list", order, (error, result) => { if (error) Logger.warn(error); this.refunds.set(result); this.state.set("isFetching", false); }); } }); }); Template.coreOrderShippingInvoice.helpers({ isCapturing() { const instance = Template.instance(); if (instance.state.get("isCapturing")) { instance.$(":input").attr("disabled", true); instance.$("#btn-capture-payment").text("Capturing"); return true; } return false; }, isRefunding() { const instance = Template.instance(); if (instance.state.get("isRefunding")) { instance.$("#btn-refund-payment").text(i18next.t("order.refunding")); return true; } return false; }, isFetching() { const instance = Template.instance(); if (instance.state.get("isFetching")) { return true; } return false; }, DiscountList() { return DiscountList; }, InvoiceContainer() { return InvoiceContainer; }, buttonSelectComponent() { return { component: ButtonSelect, buttons: [ { name: "Approve", i18nKeyLabel: "order.approveInvoice", active: true, status: "info", eventAction: "approveInvoice", bgColor: "bg-info", buttonType: "submit" }, { name: "Cancel", i18nKeyLabel: "order.cancelInvoice", active: false, status: "danger", eventAction: "cancelOrder", bgColor: "bg-danger", buttonType: "button" } ] }; }, LineItemsContainer() { return LineItemsContainer; }, TotalActionsContainer() { return TotalActionsContainer; }, orderId() { const instance = Template.instance(); const state = instance.state; const order = state.get("order"); return order._id; } }); /** * coreOrderAdjustments events */ Template.coreOrderShippingInvoice.events({ /** * Click Start Cancel Order * @param {Event} event - Event Object * @param {Template} instance - Blaze Template * @return {void} */ "click [data-event-action=cancelOrder]": (event, instance) => { event.preventDefault(); const order = instance.state.get("order"); const invoiceTotal = order.billing[0].invoice.total; const currencySymbol = instance.state.get("currency").symbol; Meteor.subscribe("Packages"); const packageId = order.billing[0].paymentMethod.paymentPackageId; const settingsKey = order.billing[0].paymentMethod.paymentSettingsKey; // check if payment provider supports de-authorize const checkSupportedMethods = Packages.findOne({ _id: packageId, shopId: Reaction.getShopId() }).settings[settingsKey].support; const orderStatus = order.billing[0].paymentMethod.status; const orderMode = order.billing[0].paymentMethod.mode; let alertText; if (_.includes(checkSupportedMethods, "de-authorize") || (orderStatus === "completed" && orderMode === "capture")) { alertText = i18next.t("order.applyRefundDuringCancelOrder", { currencySymbol, invoiceTotal }); } Alerts.alert({ title: i18next.t("order.cancelOrder"), text: alertText, type: "warning", showCancelButton: true, showCloseButton: true, confirmButtonColor: "#98afbc", cancelButtonColor: "#98afbc", confirmButtonText: i18next.t("order.cancelOrderNoRestock"), cancelButtonText: i18next.t("order.cancelOrderThenRestock") }, (isConfirm, cancel)=> { let returnToStock; if (isConfirm) { returnToStock = false; return Meteor.call("orders/cancelOrder", order, returnToStock, err => { if (err) { $(".alert").removeClass("hidden").text(err.message); } }); } if (cancel === "cancel") { returnToStock = true; return Meteor.call("orders/cancelOrder", order, returnToStock, err => { if (err) { $(".alert").removeClass("hidden").text(err.message); } }); } }); }, /** * Submit form * @param {Event} event - Event object * @param {Template} instance - Blaze Template * @return {void} */ "submit form[name=capture]": (event, instance) => { event.preventDefault(); const state = instance.state; const order = state.get("order"); const paymentMethod = orderCreditMethod(order); const orderTotal = accounting.toFixed( paymentMethod.invoice.subtotal + paymentMethod.invoice.shipping + paymentMethod.invoice.taxes , 2); const discount = state.get("field-discount") || order.discount; // TODO: review Discount cannot be greater than original total price // logic is probably not valid any more. Discounts aren't valid below 0 order. if (discount > orderTotal) { Alerts.inline("Discount cannot be greater than original total price", "error", { placement: "coreOrderShippingInvoice", i18nKey: "order.invalidDiscount", autoHide: 10000 }); } else if (orderTotal === accounting.toFixed(discount, 2)) { Alerts.alert({ title: i18next.t("order.fullDiscountWarning"), showCancelButton: true, confirmButtonText: i18next.t("order.applyDiscount") }, (isConfirm) => { if (isConfirm) { Meteor.call("orders/approvePayment", order, (error) => { if (error) { Logger.warn(error); } }); } }); } else { Meteor.call("orders/approvePayment", order, (error) => { if (error) { Logger.warn(error); if (error.error === "orders/approvePayment.discount-amount") { Alerts.inline("Discount cannot be greater than original total price", "error", { placement: "coreOrderShippingInvoice", i18nKey: "order.invalidDiscount", autoHide: 10000 }); } } }); } }, /** * Submit form * @param {Event} event - Event object * @param {Template} instance - Blaze Template * @return {void} */ "click [data-event-action=applyRefund]": (event, instance) => { event.preventDefault(); const { state } = Template.instance(); const currencySymbol = state.get("currency").symbol; const order = instance.state.get("order"); const paymentMethod = orderCreditMethod(order).paymentMethod; const orderTotal = paymentMethod.amount; const discounts = paymentMethod.discounts; const refund = state.get("field-refund") || 0; const refunds = Template.instance().refunds.get(); let refundTotal = 0; _.each(refunds, function (item) { refundTotal += parseFloat(item.amount); }); let adjustedTotal; // TODO extract Stripe specific fullfilment payment handling out of core. // Stripe counts discounts as refunds, so we need to re-add the discount to not "double discount" in the adjustedTotal if (paymentMethod.processor === "Stripe") { adjustedTotal = accounting.toFixed(orderTotal + discounts - refundTotal, 2); } else { adjustedTotal = accounting.toFixed(orderTotal - refundTotal, 2); } if (refund > adjustedTotal) { Alerts.inline("Refund(s) total cannot be greater than adjusted total", "error", { placement: "coreOrderRefund", i18nKey: "order.invalidRefund", autoHide: 10000 }); } else { Alerts.alert({ title: i18next.t("order.applyRefundToThisOrder", { refund: refund, currencySymbol: currencySymbol }), showCancelButton: true, confirmButtonText: i18next.t("order.applyRefund") }, (isConfirm) => { if (isConfirm) { state.set("isRefunding", true); Meteor.call("orders/refunds/create", order._id, paymentMethod, refund, (error, result) => { if (error) { Alerts.alert(error.reason); } if (result) { Alerts.toast(i18next.t("mail.alerts.emailSent"), "success"); } $("#btn-refund-payment").text(i18next.t("order.applyRefund")); state.set("field-refund", 0); state.set("isRefunding", false); }); } }); } }, "click [data-event-action=makeAdjustments]": (event, instance) => { event.preventDefault(); Meteor.call("orders/makeAdjustmentsToInvoice", instance.state.get("order")); }, "click [data-event-action=capturePayment]": (event, instance) => { event.preventDefault(); instance.state.set("isCapturing", true); const order = instance.state.get("order"); Meteor.call("orders/capturePayments", order._id); if (order.workflow.status === "new") { Meteor.call("workflow/pushOrderWorkflow", "coreOrderWorkflow", "processing", order); Reaction.Router.setQueryParams({ filter: "processing", _id: order._id }); } }, "change input[name=refund_amount], keyup input[name=refund_amount]": (event, instance) => { instance.refundAmount.set(accounting.unformat(event.target.value)); } }); /** * coreOrderShippingInvoice helpers */ Template.coreOrderShippingInvoice.helpers({ NumericInput() { return NumericInput; }, numericInputProps(fieldName, value = 0, enabled = true) { const { state } = Template.instance(); const order = state.get("order"); const paymentMethod = orderCreditMethod(order); const status = paymentMethod.status; const isApprovedAmount = (status === "approved" || status === "completed"); return { component: NumericInput, numericType: "currency", value: value, disabled: !enabled, isEditing: !isApprovedAmount, // Dont allow editing if its approved format: state.get("currency"), classNames: { input: { amount: true }, text: { "text-success": status === "completed" } }, onChange(event, data) { state.set(`field-${fieldName}`, data.numberValue); } }; }, refundInputProps() { const { state } = Template.instance(); const order = state.get("order"); const paymentMethod = orderCreditMethod(order).paymentMethod; const refunds = Template.instance().refunds.get(); let refundTotal = 0; _.each(refunds, function (item) { refundTotal += parseFloat(item.amount); }); const adjustedTotal = paymentMethod.amount - refundTotal; return { component: NumericInput, numericType: "currency", value: state.get("field-refund") || 0, maxValue: adjustedTotal, format: state.get("currency"), classNames: { input: { amount: true } }, onChange(event, data) { state.set("field-refund", data.numberValue); } }; }, refundAmount() { return Template.instance().refundAmount; }, invoice() { const instance = Template.instance(); const order = instance.state.get("order"); const invoice = Object.assign({}, order.billing[0].invoice, { totalItems: _.sumBy(order.items, (o) => o.quantity) }); return invoice; }, money(amount) { return formatNumber(amount); }, disabled() { const instance = Template.instance(); const order = instance.state.get("order"); const status = orderCreditMethod(order).paymentMethod.status; if (status === "approved" || status === "completed") { return "disabled"; } return ""; }, paymentPendingApproval() { const instance = Template.instance(); const order = instance.state.get("order"); const status = orderCreditMethod(order).paymentMethod.status; return status === "created" || status === "adjustments" || status === "error"; }, canMakeAdjustments() { const instance = Template.instance(); const order = instance.state.get("order"); const status = orderCreditMethod(order).paymentMethod.status; if (status === "approved" || status === "completed") { return false; } return true; }, showAfterPaymentCaptured() { const instance = Template.instance(); const order = instance.state.get("order"); const orderStatus = orderCreditMethod(order).paymentMethod.status; return orderStatus === "completed"; }, paymentApproved() { const instance = Template.instance(); const order = instance.state.get("order"); return order.billing[0].paymentMethod.status === "approved"; }, paymentCaptured() { const instance = Template.instance(); const order = instance.state.get("order"); const orderStatus = orderCreditMethod(order).paymentMethod.status; const orderMode = orderCreditMethod(order).paymentMethod.mode; return orderStatus === "completed" || (orderStatus === "refunded" && orderMode === "capture"); }, refundTransactions() { const instance = Template.instance(); const order = instance.state.get("order"); const transactions = orderCreditMethod(order).paymentMethod.transactions; return _.filter(transactions, (transaction) => { return transaction.type === "refund"; }); }, refunds() { const refunds = Template.instance().refunds.get(); if (_.isArray(refunds)) { return refunds.reverse(); } return refunds; }, /** * Get the total after all refunds * @return {Number} the amount after all refunds */ adjustedTotal() { const instance = Template.instance(); const order = instance.state.get("order"); const paymentMethod = orderCreditMethod(order).paymentMethod; const discounts = orderCreditMethod(order).invoice.discounts; const refunds = Template.instance().refunds.get(); let refundTotal = 0; _.each(refunds, function (item) { refundTotal += parseFloat(item.amount); }); if (paymentMethod.processor === "Stripe") { return Math.abs(paymentMethod.amount + discounts - refundTotal); } return Math.abs(paymentMethod.amount - refundTotal); }, capturedDisabled() { const isLoading = Template.instance().state.get("isCapturing"); if (isLoading) { return "disabled"; } return null; }, refundSubmitDisabled() { const amount = Template.instance().state.get("field-refund") || 0; const isLoading = Template.instance().state.get("isRefunding"); if (amount === 0 || isLoading) { return "disabled"; } return null; }, /** * Order * @summary find a single order using the order id spplied with the template * data context * @return {Object} A single order */ order() { const instance = Template.instance(); const order = instance.state.get("order"); return order; }, shipment() { const instance = Template.instance(); const order = instance.state.get("order"); const shipment = _.filter(order.shipping, { _id: currentData.fulfillment._id })[0]; return shipment; }, discounts() { const enabledPaymentsArr = []; const apps = Reaction.Apps({ provides: "paymentMethod", enabled: true }); for (app of apps) { if (app.enabled === true) enabledPaymentsArr.push(app); } let discount = false; for (enabled of enabledPaymentsArr) { if (enabled.packageName === "discount-codes") { discount = true; break; } } return discount; }, items() { const instance = Template.instance(); const order = instance.state.get("order"); const currentData = Template.currentData(); const shipment = currentData.fulfillment; // returns order items with shipping detail const returnItems = _.map(order.items, (item) => { const shipping = shipment.shipmentMethod; return _.extend(item, { shipping }); }); let items; // if avalara tax has been enabled it adds a "taxDetail" field for every item if (order.taxes !== undefined) { const taxes = order.taxes.slice(0, -1); items = _.map(returnItems, (item) => { const taxDetail = _.find(taxes, { lineNumber: item._id }); return _.extend(item, { taxDetail }); }); } else { items = returnItems; } return items; } });
Sweetgrassbuffalo/ReactionSweeGrass-v2
imports/plugins/core/orders/client/templates/workflow/shippingInvoice.js
JavaScript
gpl-3.0
17,911
package org.sigmah.offline.js; /* * #%L * Sigmah * %% * Copyright (C) 2010 - 2016 URD * %% * 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/gpl-3.0.html>. * #L% */ import java.util.ArrayList; import java.util.List; import org.sigmah.shared.dto.layout.LayoutDTO; import org.sigmah.shared.dto.layout.LayoutGroupDTO; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; /** * * @author Raphaël Calabro (rcalabro@ideia.fr) */ public final class LayoutJS extends JavaScriptObject { protected LayoutJS() { } public static LayoutJS toJavaScript(LayoutDTO layoutDTO) { final LayoutJS layoutJS = (LayoutJS)JavaScriptObject.createObject(); layoutJS.setId(layoutDTO.getId()); layoutJS.setRowsCount(layoutDTO.getRowsCount()); layoutJS.setColumnsCount(layoutDTO.getColumnsCount()); layoutJS.setGroups(layoutDTO.getGroups()); return layoutJS; } public LayoutDTO toDTO() { final LayoutDTO layoutDTO = new LayoutDTO(); layoutDTO.setId(getId()); layoutDTO.setRowsCount(getRowsCount()); layoutDTO.setColumnsCount(getColumnsCount()); final JsArray<LayoutGroupJS> layoutGroups = getGroups(); if(layoutGroups != null) { final ArrayList<LayoutGroupDTO> list = new ArrayList<LayoutGroupDTO>(); final int length = layoutGroups.length(); for(int index = 0; index < length; index++) { list.add(layoutGroups.get(index).toDTO()); } layoutDTO.setGroups(list); } return layoutDTO; } public native int getId() /*-{ return this.id; }-*/; public native void setId(int id) /*-{ this.id = id; }-*/; public native int getRowsCount() /*-{ return this.rowsCount; }-*/; public native void setRowsCount(int rowsCount) /*-{ this.rowsCount = rowsCount; }-*/; public native int getColumnsCount() /*-{ return this.columnsCount; }-*/; public native void setColumnsCount(int columnsCount) /*-{ this.columnsCount = columnsCount; }-*/; public native JsArray<LayoutGroupJS> getGroups() /*-{ return this.groups; }-*/; public void setGroups(List<LayoutGroupDTO> groups) { if(groups != null) { final JsArray<LayoutGroupJS> array = (JsArray<LayoutGroupJS>) JavaScriptObject.createArray(); for(final LayoutGroupDTO layoutGroupDTO : groups) { array.push(LayoutGroupJS.toJavaScript(layoutGroupDTO)); } setGroups(array); } } public native void setGroups(JsArray<LayoutGroupJS> groups) /*-{ this.groups = groups; }-*/; }
Raphcal/sigmah
src/main/java/org/sigmah/offline/js/LayoutJS.java
Java
gpl-3.0
3,072
require_relative "core/workflow_plugin_base" require_relative "core/loaders/options_loader" require_relative "core/loaders/command_loader" require_relative "core/loaders/workflow_loader" module Radial # Entry point to the application class Radial < WorkflowPluginBase include OptionsLoader include CommandLoader include WorkflowLoader end end
imaginatelabs/cruxus
lib/radial.rb
Ruby
gpl-3.0
362
<?php /** Copyright 2011-2017 Nick Korbel This file is part of Booked Scheduler. Booked Scheduler 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. Booked Scheduler 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>. */ define('ROOT_DIR', '../../'); require(ROOT_DIR . 'Pages/Ajax/ReservationPopupPage.php'); $page = new ReservationPopupPage(); $page->PageLoad();
rafaelperazzo/ufca-web
booked/Web/ajax/respopup.php
PHP
gpl-3.0
856
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="nl"> <context> <name>AboutDialog</name> <message> <source>About Brewtarget</source> <translation>Over Brewtarget</translation> </message> </context> <context> <name>BrewDayScrollWidget</name> <message> <source>Style</source> <translation>Stijl</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Boil Time</source> <translation>Kooktijd</translation> </message> <message> <source>Efficiency</source> <translation>Efficiëntie</translation> </message> <message> <source>Boil Volume</source> <translation>Kookvolume</translation> </message> <message> <source>Preboil Gravity</source> <translation>SG voor het koken</translation> </message> <message> <source>Final Volume</source> <translation>Eind SG</translation> </message> <message> <source>Starting Gravity</source> <translation>Begin SG</translation> </message> <message> <source>IBU</source> <translation>IBU</translation> </message> <message> <source>Final Gravity</source> <translation>Eind SG</translation> </message> <message> <source>ABV</source> <translation>Alc (vol%)</translation> </message> <message> <source>Instructions</source> <translation>Instructies</translation> </message> <message> <source>Completed</source> <translation>Gereed</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Step</source> <translation>Stap</translation> </message> <message> <source>Actual PreBoil Volume</source> <translation>Actueel Volume voor het koken</translation> </message> <message> <source>Actual PreBoil Gravity</source> <translation>Actueel SG voor het koken</translation> </message> <message> <source>PostBoil Volume</source> <translation>Volume na het koken</translation> </message> <message> <source>PostBoil Gravity</source> <translation>SG na het koken</translation> </message> <message> <source>Volume into fermenter</source> <translation>Volume in het vergistingsvat</translation> </message> <message> <source>Print Document</source> <translation>Print Document</translation> </message> <message> <source>&lt;h2&gt;Notes&lt;/h2&gt;</source> <translation>&lt;h2&gt;Aantekeningen&lt;/h2&gt;</translation> </message> <message> <source>Step %1: %2</source> <translation>Stap %1: %2</translation> </message> <message> <source>Add grains</source> <translation>Graan toevoegen</translation> </message> <message> <source>Heat water</source> <translation>Verhit water</translation> </message> <message> <source>Estimated calories (per 33 cl)</source> <translation type="unfinished"></translation> </message> <message> <source>Estimated calories (per 12 oz)</source> <translation type="unfinished">Geschat aantal calorieën (per 340 g)</translation> </message> </context> <context> <name>BrewDayWidget</name> <message> <source>Style</source> <translation>Stijl</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Boil Volume</source> <translation>Kook Volume</translation> </message> <message> <source>Preboil Gravity</source> <translation>SG voor het koken</translation> </message> <message> <source>Final Volume</source> <translation>eind Volume</translation> </message> <message> <source>Starting Gravity</source> <translation>begin SG</translation> </message> <message> <source>Boil Time</source> <translation>Kook Tijd</translation> </message> <message> <source>IBU</source> <translation>IBU</translation> </message> <message> <source>Predicted Efficiency</source> <translation>Voorspeld rendement</translation> </message> <message> <source>Estimated calories (per 12 oz)</source> <translation>Geschat aantal calorieën (per 340 g)</translation> </message> <message> <source>Instructions</source> <translation>Instructies</translation> </message> <message> <source>Completed</source> <translation>Gereed</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Step</source> <translation>Stap</translation> </message> <message> <source>Actual Pre-boil Volume:</source> <translation>Actueel Volume voor het koken:</translation> </message> <message> <source>Actual Pre-boil Gravity:</source> <translation>Actueel SG voor het koken:</translation> </message> <message> <source>Post-boil Volume:</source> <translation>Volume voor het koken:</translation> </message> <message> <source>Post-boil Gravity:</source> <translation>SG voor het koken:</translation> </message> <message> <source>Volume in fermenter:</source> <translation>Volume in het vergistingsvat:</translation> </message> <message> <source>Print Document</source> <translation>Print Document</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> <message> <source>Step %1: %2</source> <translation>Stap %1: %2</translation> </message> <message> <source>Estimated calories (per 33 cl)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Brewtarget</name> <message> <source>Default</source> <translation>Standaard</translation> </message> <message> <source>EBC</source> <translation>EBC</translation> </message> <message> <source>SRM</source> <translation>SRM</translation> </message> <message> <source>Plato</source> <translation>Plato</translation> </message> <message> <source>Specific Gravity</source> <translation>Specifieke zwaartekracht</translation> </message> <message> <source>SI</source> <translation type="unfinished"></translation> </message> <message> <source>US Customary</source> <translation>Amerikaans maatsysteem</translation> </message> <message> <source>Milligrams</source> <translation>Milligram</translation> </message> <message> <source>Grams</source> <translation>Gram</translation> </message> <message> <source>Kilograms</source> <translation>Kilogram</translation> </message> <message> <source>Ounces</source> <translation>Ounce</translation> </message> <message> <source>Pounds</source> <translation>Pound</translation> </message> <message> <source>Celsius</source> <translation>Celsius</translation> </message> <message> <source>Fahrenheit</source> <translation>Fahrenheit</translation> </message> <message> <source>British Imperial</source> <translation>Brits maatsysteem</translation> </message> <message> <source>MilliLiters</source> <translation>Milliliter</translation> </message> <message> <source>Liters</source> <translation>Liter</translation> </message> <message> <source>Teaspoons</source> <translation>Theelepels</translation> </message> <message> <source>Tablespoons</source> <translation>Eetlepels</translation> </message> <message> <source>Cups</source> <translation>Kopjes</translation> </message> <message> <source>Quarts</source> <translation type="unfinished"></translation> </message> <message> <source>Gallons</source> <translation>Gallons</translation> </message> <message> <source>Unknown</source> <translation>Onbekend</translation> </message> <message> <source>YYYY-mm-dd</source> <translation type="unfinished"></translation> </message> <message> <source>dd-mm-YYYY</source> <translation type="unfinished"></translation> </message> <message> <source>mm-dd-YYYY</source> <translation type="unfinished"></translation> </message> <message> <source>Seconds</source> <translation>Seconden</translation> </message> <message> <source>Minutes</source> <translation>Minuten</translation> </message> <message> <source>Hours</source> <translation>Uur</translation> </message> <message> <source>Days</source> <translation>Dagen</translation> </message> <message> <source>Barrels</source> <translation>Barrels</translation> </message> <message> <source>Scale</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BtDigitWidget</name> <message> <source>Too low for style.</source> <translation>Te laag voor deze stijl</translation> </message> <message> <source>In range for style.</source> <translation>Conform stijl</translation> </message> <message> <source>Too high for style.</source> <translation>Te hoog voor deze stijl</translation> </message> </context> <context> <name>BtLabel</name> <message> <source>Color (%1)</source> <translation>Kleur (%1)</translation> </message> </context> <context> <name>BtSplashScreen</name> <message> <source>Loading...</source> <translation>Laden…</translation> </message> </context> <context> <name>BtTreeModel</name> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Brew Date</source> <translation>Brouwdatum</translation> </message> <message> <source>Style</source> <translation>Stijl</translation> </message> <message> <source>Boil Time</source> <translation>Kooktijd</translation> </message> <message> <source>Color</source> <translation>Kleur</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Use</source> <translation>Gebruik</translation> </message> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Category</source> <translation>Categorie</translation> </message> <message> <source>Number</source> <translation type="unfinished"></translation> </message> <message> <source>Letter</source> <translation type="unfinished"></translation> </message> <message> <source>Guide</source> <translation type="unfinished"></translation> </message> <message> <source>PATH</source> <translation type="unfinished"></translation> </message> <message> <source>FULLPATH</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BtTreeView</name> <message> <source>New</source> <translation>Nieuw</translation> </message> <message> <source>Recipe</source> <translation>Recept</translation> </message> <message> <source>Brew It!</source> <translation>Brouw het!</translation> </message> <message> <source>Brew Again</source> <translation>Brouw opnieuw</translation> </message> <message> <source>Change date</source> <translation>Datum veranderen</translation> </message> <message> <source>Recalculate eff</source> <translation type="unfinished"></translation> </message> <message> <source>Delete</source> <translation>Verwijderen</translation> </message> <message> <source>Equipment</source> <translation>Apparatuur</translation> </message> <message> <source>Fermentable</source> <translation type="unfinished"></translation> </message> <message> <source>Hop</source> <translation type="unfinished"></translation> </message> <message> <source>Misc</source> <translation>Diversen</translation> </message> <message> <source>Style</source> <translation>Stijl</translation> </message> <message> <source>Yeast</source> <translation>Gist</translation> </message> <message> <source>Folder</source> <translation>Map</translation> </message> <message> <source>Copy</source> <translation>Kopiëren</translation> </message> <message> <source>Export</source> <translation>Exporteren</translation> </message> <message> <source>Import</source> <translation>Importeren</translation> </message> <message> <source>Delete %1</source> <translation>%1 Verwijderen</translation> </message> <message> <source>Delete %1 %2?</source> <translation>%1 %2 Verwijderen?</translation> </message> <message> <source>BrewNote</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel All</source> <translation>Alles annuleren</translation> </message> <message> <source>Copy %1</source> <translation type="unfinished"></translation> </message> <message> <source>Enter a unique name for the copy of %1.</source> <translation type="unfinished"></translation> </message> <message> <source>An empty name will skip copying this %1.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ConverterTool</name> <message> <source>Converter Tool</source> <translation>Conversie Gereedschap</translation> </message> <message> <source>Input</source> <translation>Invoer</translation> </message> <message> <source>Output Units</source> <translation>Uitvoer Eenheden</translation> </message> <message> <source>Output</source> <translation>Uitvoer</translation> </message> <message> <source>Convert</source> <translation>Conversie</translation> </message> <message> <source>Amount and units to convert</source> <translation>Hoeveelheden en Eenheden om te converteren</translation> </message> <message> <source>Unit you want to convert to</source> <translation>Eenheid waar u naar toe wilt converteren</translation> </message> <message> <source>Output conversion</source> <translation>Uitvoer conversie</translation> </message> </context> <context> <name>Database</name> <message> <source>Merge Database</source> <translation>Database Samenvoegen</translation> </message> <message> <source>There may be new ingredients and recipes available. Would you like to add these to your database?</source> <translation>Er zijn mogelijk nieuwe ingrediënten en recepten verkrijgbaar. Wilt u deze toevoegen aan uw database?</translation> </message> </context> <context> <name>EquipmentEditor</name> <message> <source>Grain absorption (%1/%2)</source> <translation type="unfinished"></translation> </message> <message> <source>Tun Volume Warning</source> <translation>Vat Volume Waarschuwing</translation> </message> <message> <source>Batch Size Warning</source> <translation>Batch Grootte Waarschuwing</translation> </message> <message> <source>Equipment name</source> <translation>Apparatuur naam</translation> </message> <message> <source>Equipment name:</source> <translation>Apparatuur naam:</translation> </message> <message> <source>The tun volume you entered is 0. This may cause problems</source> <translation type="unfinished"></translation> </message> <message> <source>The batch size you entered is 0. This may cause problems</source> <translation type="unfinished"></translation> </message> <message> <source>Hop Utilization Warning</source> <translation type="unfinished"></translation> </message> <message> <source>The hop utilization percentage you entered is 0. This may cause problems</source> <translation type="unfinished"></translation> </message> <message> <source>Equipment Editor</source> <translation>Apparatuur Editor</translation> </message> <message> <source>Equipment</source> <translation>Apparatuur</translation> </message> <message> <source>Set as Default</source> <translation type="unfinished"></translation> </message> <message> <source>Required Fields</source> <translation>Vereiste Velden</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Pre-boil volume</source> <translation>Volume voor het koken</translation> </message> <message> <source>Calculate pre-boil volume</source> <translation>Bereken volume voor het koken</translation> </message> <message> <source>Batch size</source> <translation>Batch grootte</translation> </message> <message> <source>Boiling &amp;&amp; Water</source> <translation>Koken &amp;&amp; Water</translation> </message> <message> <source>Boil time</source> <translation>Kook tijd</translation> </message> <message> <source>Evaporation rate (per hr)</source> <translation>Verdampingssnelheid (per uur)</translation> </message> <message> <source>Kettle top-up water</source> <translation>Ketel top-up water</translation> </message> <message> <source>Final top-up water</source> <translation>Uiteindelijk top-up water</translation> </message> <message> <source>Grain Absorption (L/kg)</source> <translation>Graan absorbtie</translation> </message> <message> <source>Default Absorption</source> <translation>Staindaard Absorbtie</translation> </message> <message> <source>Hop Utilization </source> <translation type="unfinished"></translation> </message> <message> <source>Boiling Point of Water</source> <translation type="unfinished"></translation> </message> <message> <source>Mash Tun</source> <translation>Maisch Vat</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Mass</source> <translation>Gewicht</translation> </message> <message> <source>Remove equipment</source> <translation>Verwijder apparatuur</translation> </message> <message> <source>If checked, we will calculate your pre-boil volume based on your desired batch size, boil time, evaporation rate, losses, etc.</source> <translation>Indien aangevinkt wordt het volume voor het koken berekend, gebaseerd op uw gewenste batch grootte, kook tijd, verdampingssnelheid rate, verliezen, enz.</translation> </message> <message> <source>Automatically fill in pre-boil volume</source> <translation>Vul automatisch het volume voor het koken in</translation> </message> <message> <source>How much water boils off per hour</source> <translation>Hoeveel water verdampt er per uur</translation> </message> <message> <source>How much water is added to kettle immediately pre-boil</source> <translation>Hoeveel water wordt toegevoegd vlak voor het koken</translation> </message> <message> <source>Water added to fermenter</source> <translation>Water toegevoegd aan vergistingsvat</translation> </message> <message> <source>Volume of mash tun</source> <translation>Volume van het maisch vat</translation> </message> <message> <source>Mass or weight of mash tun</source> <translation>Massa of gewicht van het Maisch Vat</translation> </message> <message> <source>Wort lost between kettle and fermenter</source> <translation>Wort verlies tussen ketel en Vergistingsvat</translation> </message> <message> <source>Volume of wort lost to lauter deadspace</source> <translation>Verloren wortvolume door dode ruimten de klaringskuip</translation> </message> <message> <source>New equipment</source> <translation>Nieuwe apparatuur</translation> </message> <message> <source>Save</source> <translation>Opslaan</translation> </message> <message> <source>Cancel</source> <translation>Annuleren</translation> </message> </context> <context> <name>Fermentable</name> <message> <source>Mashed</source> <translation type="unfinished">Gemaischd</translation> </message> <message> <source>Steeped</source> <translation type="unfinished"></translation> </message> <message> <source>Not mashed</source> <translation type="unfinished"></translation> </message> <message> <source>Late</source> <translation type="unfinished">Late</translation> </message> <message> <source>Normal</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FermentableDialog</name> <message> <source>Fermentable name</source> <translation>naam vergistbare</translation> </message> <message> <source>Fermentable name:</source> <translation>naam vergistbare:</translation> </message> <message> <source>Fermentable Database</source> <translation>Database met vergistbaren</translation> </message> <message> <source>Add to Recipe</source> <translation type="unfinished"></translation> </message> <message> <source>New</source> <translation>Nieuw</translation> </message> <message> <source>Add selected ingredient to recipe</source> <translation type="unfinished"></translation> </message> <message> <source>Create new ingredient</source> <translation>Creëer nieuw ingrediënt</translation> </message> <message> <source>Edit selected ingredient</source> <translation>Edit geselecteerde ingrediënt</translation> </message> <message> <source>Remove selected ingredient</source> <translation>Verwijder geselecteerde ingrediënt</translation> </message> </context> <context> <name>FermentableItemDelegate</name> <message> <source>Grain</source> <translation>Graan</translation> </message> <message> <source>Sugar</source> <translation>Suiker</translation> </message> <message> <source>Extract</source> <translation>Extract</translation> </message> <message> <source>Dry Extract</source> <translation>Droog Extract</translation> </message> <message> <source>Adjunct</source> <translation>Aanvulling</translation> </message> <message> <source>Mashed</source> <translation type="unfinished">Gemaischd</translation> </message> <message> <source>Steeped</source> <translation type="unfinished"></translation> </message> <message> <source>Not mashed</source> <translation type="unfinished"></translation> </message> <message> <source>Normal</source> <translation type="unfinished"></translation> </message> <message> <source>Late</source> <translation type="unfinished">Late</translation> </message> </context> <context> <name>FermentableTableModel</name> <message> <source>Bad model index. row = %1</source> <translation>Bad model index. row = %1</translation> </message> <message> <source>Bad column: %1</source> <translation>Foute kolom: %1</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Yield %</source> <translation>Rendement %</translation> </message> <message> <source>Inventory</source> <translation type="unfinished"></translation> </message> <message> <source>Color</source> <translation>Kleur</translation> </message> <message> <source>Method</source> <translation type="unfinished"></translation> </message> <message> <source>Addition</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Hop</name> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>First Wort</source> <translation>Eerste Wort</translation> </message> <message> <source>Boil</source> <translation>Koken</translation> </message> <message> <source>Aroma</source> <translation>Aroma</translation> </message> <message> <source>Dry Hop</source> <translation>Dry Hop</translation> </message> <message> <source>Bittering</source> <translation>Bitterhop</translation> </message> <message> <source>Both</source> <translation>Beide</translation> </message> <message> <source>Leaf</source> <translation>Blad</translation> </message> <message> <source>Pellet</source> <translation>Pellet</translation> </message> <message> <source>Plug</source> <translation>Geperste hop</translation> </message> </context> <context> <name>HopDialog</name> <message> <source>Hop name</source> <translation>Hop naam</translation> </message> <message> <source>Hop name:</source> <translation>Hop naam:</translation> </message> <message> <source>Hop Database</source> <translation>Hop Database</translation> </message> <message> <source>Add to Recipe</source> <translation type="unfinished"></translation> </message> <message> <source>New</source> <translation>Nieuw</translation> </message> <message> <source>Add selected ingredient to recipe</source> <translation type="unfinished"></translation> </message> <message> <source>Create new ingredient</source> <translation>Creëer nieuw ingrediënt</translation> </message> <message> <source>Edit selected ingredient</source> <translation>Edit geselecteerde ingrediënt</translation> </message> <message> <source>Remove selected ingredient</source> <translation>Verwijder geselecteerde ingrediënt</translation> </message> </context> <context> <name>HopItemDelegate</name> <message> <source>Boil</source> <translation>Koken</translation> </message> <message> <source>Dry Hop</source> <translation>Dry Hop</translation> </message> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>First Wort</source> <translation>Eerste Wort</translation> </message> <message> <source>Aroma</source> <translation>Aroma</translation> </message> <message> <source>Leaf</source> <translation>Blad</translation> </message> <message> <source>Pellet</source> <translation>Pellet</translation> </message> <message> <source>Plug</source> <translation>Geperste hop</translation> </message> </context> <context> <name>HopTableModel</name> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Alpha %</source> <translation>Alpha %</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Use</source> <translation>Gebruik</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Inventory</source> <translation type="unfinished"></translation> </message> </context> <context> <name>IbuGuSlider</name> <message> <source>Cloying</source> <translation type="unfinished"></translation> </message> <message> <source>Extra Malty</source> <translation type="unfinished"></translation> </message> <message> <source>Slightly Malty</source> <translation type="unfinished"></translation> </message> <message> <source>Balanced</source> <translation type="unfinished"></translation> </message> <message> <source>Slightly Hoppy</source> <translation type="unfinished"></translation> </message> <message> <source>Extra Hoppy</source> <translation type="unfinished"></translation> </message> <message> <source>Way Hoppy</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainWindow</name> <message> <source>Open</source> <translation>Open</translation> </message> <message> <source>BeerXML files (*.xml)</source> <translation>BeerXML bestanden (*.xml)</translation> </message> <message> <source>Save</source> <translation>Opslaan</translation> </message> <message> <source>Equipment request</source> <translation>Apparatuur verzoek</translation> </message> <message> <source>Would you like to set the batch size, boil size and time to that requested by the equipment?</source> <translation type="unfinished"></translation> </message> <message> <source>HTML files (*.html)</source> <translation type="unfinished"></translation> </message> <message> <source>Database Update</source> <translation type="unfinished"></translation> </message> <message> <source>You are about to update the current database with another one. This may make changes to (but will not delete) some of your ingredients. It will not modify any of your recipes. Continue?</source> <translation type="unfinished"></translation> </message> <message> <source>Select Database File</source> <translation type="unfinished"></translation> </message> <message> <source>Brewtarget Database (*.sqlite)</source> <translation type="unfinished"></translation> </message> <message> <source>Recipe name</source> <translation>Recept naam</translation> </message> <message> <source>Recipe name:</source> <translation>Recept naam:</translation> </message> <message> <source>Backup Database</source> <translation>Backup Database</translation> </message> <message> <source>Oops!</source> <translation>Oeps!</translation> </message> <message> <source>Could not copy the files for some reason.</source> <translation>Kon de bestanden om de een of andere reden niet copiërenKon de bestanden om de een of andere reden niet copiëren.</translation> </message> <message> <source>A Warning</source> <translation>Een waarschuwing</translation> </message> <message> <source>This will obliterate your current set of recipes and ingredients. Do you want to continue?</source> <translation>Dit schoont uw huidige set recepten en ingrediënten. Doorgaan?</translation> </message> <message> <source>For some reason, the operation failed.</source> <translation>De opratie faalde om de een of andere reden.</translation> </message> <message> <source>Import %1?</source> <translation>%1 importeren?</translation> </message> <message> <source>No mash</source> <translation>Geen maisch</translation> </message> <message> <source>Trying to add a mash step without a mash. Please create a mash first.</source> <translation>Poging om een maisch stap toe te voegen zonder maisch. Maak a.u.b. eerst een maisch aan.</translation> </message> <message> <source>Copy Recipe</source> <translation>Copiëer Recept</translation> </message> <message> <source>Enter a unique name for the copy.</source> <translation>Geef een unieke naam voor de copie.</translation> </message> <message> <source>Please give your mash a name before saving.</source> <translation>Geef uw maisch een naam a.u.b. voor het opslaan.</translation> </message> <message> <source>Restart</source> <translation type="unfinished"></translation> </message> <message> <source>Please restart Brewtarget.</source> <translation type="unfinished"></translation> </message> <message> <source>No equipment</source> <translation type="unfinished"></translation> </message> <message> <source>You must select or define an equipment profile first.</source> <translation type="unfinished"></translation> </message> <message> <source>No style</source> <translation type="unfinished"></translation> </message> <message> <source>You must select a style first.</source> <translation type="unfinished"></translation> </message> <message> <source>Choose File</source> <translation type="unfinished"></translation> </message> <message> <source>SQLite (*.sqlite)</source> <translation type="unfinished"></translation> </message> <message> <source>The database has been converted/upgraded.</source> <translation type="unfinished"></translation> </message> <message> <source>The original XML files can be found in </source> <translation type="unfinished"></translation> </message> <message> <source>The import contained invalid beerXML. It has been imported, but please make certain it makes sense.</source> <translation type="unfinished"></translation> </message> <message> <source>Folder name</source> <translation type="unfinished"></translation> </message> <message> <source>Folder name:</source> <translation type="unfinished"></translation> </message> <message> <source>Bad Name</source> <translation type="unfinished"></translation> </message> <message> <source>A folder name must have at least one non-whitespace character in it</source> <translation type="unfinished"></translation> </message> <message> <source>A folder name must have at least one non-/ character in it</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MashDesigner</name> <message> <source>No Fermentables</source> <translation type="unfinished"></translation> </message> <message> <source>Your recipe must have fermentables to design a mash.</source> <translation type="unfinished"></translation> </message> <message> <source>No Equipment</source> <translation>Geen apparatuur</translation> </message> <message> <source>You have not set an equipment for this recipe. We really cannot continue without one.</source> <translation>U hebt geen apparatuur opgegeven voor dit recept. Zonder apparatuur kunnen we niet doorgaan.</translation> </message> <message> <source>Tun Temp</source> <translation>Vat Temperatuur</translation> </message> <message> <source>Enter the temperature of the tun before your first infusion.</source> <translation>Voer de temperatuur van het vat in voorafgaande aan uw eerste infusie</translation> </message> <message> <source>Decoction error</source> <translation>Decoctie fout</translation> </message> <message> <source>The first mash step cannot be a decoction.</source> <translation>De eerste maisch stap kan geen decoctie zijn.</translation> </message> </context> <context> <name>MashStepTableModel</name> <message> <source>Bad model index. row = %1</source> <translation>Bad model index. row = %1</translation> </message> <message> <source>Bad column: %1</source> <translation>Bad column: %1</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Infusion Temp</source> <translation>Infusie Temperatuur</translation> </message> <message> <source>Target Temp</source> <translation>Streef Temp</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> </context> <context> <name>MashWizard</name> <message> <source>Mash thickness (%1/%2)</source> <translation>Maisch dichtheid (%1/%2)</translation> </message> <message> <source>Bad thickness</source> <translation>Foute dichtheid</translation> </message> <message> <source>You must have a positive mash thickness.</source> <translation>U moet een positieve maisch dichtheid ingeven.</translation> </message> <message> <source>No steps</source> <translation>Geen stappen</translation> </message> <message> <source>There must be at least one mash step to run the wizard.</source> <translation type="unfinished"></translation> </message> <message> <source>First step</source> <translation>Eerste stap</translation> </message> <message> <source>Your first mash step must be an infusion.</source> <translation>De eerste maisch stap moet een infusie zijn.</translation> </message> <message> <source>Mash too thick</source> <translation>Maisch is te dik</translation> </message> <message> <source>Your mash is too thick for desired temp. at first step.</source> <translation>Uw maisch is te dik voor de gewenste temperatuur tijdens de eerste stap.</translation> </message> <message> <source>Decoction error</source> <translation>Decoctie fout</translation> </message> <message> <source>Something went wrong in decoction calculation.</source> <translation>Er is een fout opgetreden in de decoctie berekeningen.</translation> </message> <message> <source>Sparge temp.</source> <translation>Spoel temp.</translation> </message> <message> <source>In order to hit your sparge temp, the sparge water must be above boiling. Lower your sparge temp, or allow for more sparge water.</source> <translation>Om uw spoel temp te bereiken, moet het spoelwater boven hetkookpunt zijn. Verlaag de spoeltemperatuur of gebruik meer spoelwater.</translation> </message> <message> <source>Too much wort</source> <translation>Te veel wort</translation> </message> <message> <source>You have too much wort from the mash for your boil size. I suggest increasing the boil size by increasing the boil time, or reducing your mash thickness.</source> <translation>U heeft te veel wort van de maisch voor uw kook grootte. Ik stel voor om de kook grootte te vergroten door de kooktijd te vergroten, of om de maisch dikte te reduceren.</translation> </message> </context> <context> <name>Misc</name> <message> <source>Spice</source> <translation type="unfinished">Specerij</translation> </message> <message> <source>Fining</source> <translation type="unfinished">Fining</translation> </message> <message> <source>Water Agent</source> <translation type="unfinished">Waterbehandeling</translation> </message> <message> <source>Herb</source> <translation type="unfinished">Kruid</translation> </message> <message> <source>Flavor</source> <translation type="unfinished">Smaak</translation> </message> <message> <source>Other</source> <translation type="unfinished">Overig</translation> </message> <message> <source>Boil</source> <translation type="unfinished">Koken</translation> </message> <message> <source>Mash</source> <translation type="unfinished">Maisch</translation> </message> <message> <source>Primary</source> <translation type="unfinished"></translation> </message> <message> <source>Secondary</source> <translation type="unfinished"></translation> </message> <message> <source>Bottling</source> <translation type="unfinished">Bottelen</translation> </message> <message> <source>Weight</source> <translation type="unfinished">Gewicht</translation> </message> <message> <source>Volume</source> <translation type="unfinished">Volume</translation> </message> </context> <context> <name>MiscDialog</name> <message> <source>Misc name</source> <translation>naam Diversen</translation> </message> <message> <source>Misc name:</source> <translation>naam Diversen:</translation> </message> <message> <source>Misc Database</source> <translation>Database Diversen</translation> </message> <message> <source>Add to Recipe</source> <translation type="unfinished"></translation> </message> <message> <source>New</source> <translation>Nieuw</translation> </message> <message> <source>Add selected ingredient to recipe</source> <translation type="unfinished"></translation> </message> <message> <source>Create new ingredient</source> <translation>Creëer nieuw ingrediënt</translation> </message> <message> <source>Edit selected ingredient</source> <translation>Edit geselecteerde ingrediënt</translation> </message> <message> <source>Remove selected ingredient</source> <translation>Verwijder geselecteerde ingrediënt</translation> </message> </context> <context> <name>MiscItemDelegate</name> <message> <source>Spice</source> <translation>Specerij</translation> </message> <message> <source>Fining</source> <translation>Fining</translation> </message> <message> <source>Water Agent</source> <translation>Waterbehandeling</translation> </message> <message> <source>Herb</source> <translation>Kruid</translation> </message> <message> <source>Flavor</source> <translation>Smaak</translation> </message> <message> <source>Other</source> <translation>Overig</translation> </message> <message> <source>Boil</source> <translation>Koken</translation> </message> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>Primary</source> <translation>Hoofdvergisting</translation> </message> <message> <source>Secondary</source> <translation>Secundaire</translation> </message> <message> <source>Bottling</source> <translation>Bottelen</translation> </message> <message> <source>Weight</source> <translation type="unfinished">Gewicht</translation> </message> <message> <source>Volume</source> <translation type="unfinished">Volume</translation> </message> </context> <context> <name>MiscTableModel</name> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Use</source> <translation>Gebruik</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Amount Type</source> <translation type="unfinished"></translation> </message> <message> <source>Inventory</source> <translation type="unfinished"></translation> </message> </context> <context> <name>OptionDialog</name> <message> <source>Open Directory</source> <translation type="unfinished"></translation> </message> <message> <source>Copy Data</source> <translation type="unfinished"></translation> </message> <message> <source>There do not seem to be any data files in this directory, so we will copy your old data here.</source> <translation type="unfinished"></translation> </message> <message> <source>Restart</source> <translation type="unfinished"></translation> </message> <message> <source>Please restart Brewtarget.</source> <translation type="unfinished"></translation> </message> <message> <source>Catalan</source> <translation type="unfinished"></translation> </message> <message> <source>Czech</source> <translation type="unfinished"></translation> </message> <message> <source>German</source> <translation type="unfinished"></translation> </message> <message> <source>English</source> <translation type="unfinished"></translation> </message> <message> <source>Greek</source> <translation type="unfinished"></translation> </message> <message> <source>Spanish</source> <translation type="unfinished"></translation> </message> <message> <source>French</source> <translation type="unfinished"></translation> </message> <message> <source>Italian</source> <translation type="unfinished"></translation> </message> <message> <source>Dutch</source> <translation type="unfinished"></translation> </message> <message> <source>Polish</source> <translation type="unfinished"></translation> </message> <message> <source>Portuguese</source> <translation type="unfinished"></translation> </message> <message> <source>Russian</source> <translation type="unfinished"></translation> </message> <message> <source>Chinese</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QObject</name> <message> <source>Invalid color formula type: %1</source> <translation>Ongeldige kleur formule type: %1</translation> </message> <message> <source>Unrecognized IBU formula type. %1</source> <translation type="unfinished"></translation> </message> <message> <source>Directory Problem</source> <translation>Directory Probleem</translation> </message> <message> <source>&quot;%1&quot; cannot be read.</source> <translation>&quot;%1&quot; kan niet gelezen worden.</translation> </message> <message> <source>New Version</source> <translation>Nieuwe Versie</translation> </message> <message> <source>Version %1 is now available. Download it?</source> <translation>Versie %1 is nu verkrijgbaar. Downloaden?</translation> </message> <message> <source>Stop bothering you about new versions?</source> <translation>Niet meer lastigvallen over nieuwe versies?</translation> </message> <message> <source>Database Failure</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to open the database &apos;%1&apos;.</source> <translation type="unfinished"></translation> </message> <message> <source>Save Database Changes</source> <translation type="unfinished"></translation> </message> <message> <source>Would you like to save the changes you made?</source> <translation type="unfinished"></translation> </message> <message> <source>Multiple Databases Found</source> <translation type="unfinished"></translation> </message> <message> <source>Multiple databases were found. Do you want to restore the changes you made during your last Brewtarget session, or rollback to before last session&apos;s changes?</source> <translation type="unfinished"></translation> </message> <message> <source>Restore</source> <translation type="unfinished"></translation> </message> <message> <source>Rollback</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to remove the temporary backup database. Navigate to &apos;%1&apos; and remove &apos;tempBackupDatabase.sqlite&apos;.</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to rollback to the backup database. Navigate to &apos;%1&apos;, remove &apos;database.sqlite&apos; if it exists, and rename &apos;tempBackupDatabase.sqlite&apos; to &apos;database.sqlite&apos;.</source> <translation type="unfinished"></translation> </message> <message> <source>Database Restore Failure</source> <translation type="unfinished"></translation> </message> <message> <source>Failed to restore the backup database. Navigate to &apos;%1&apos; and rename &apos;tempBackupDatabase.sqlite&apos; to &apos;database.sqlite&apos;.</source> <translation type="unfinished"></translation> </message> <message> <source>Grain</source> <translation>Graan</translation> </message> <message> <source>Sugar</source> <translation>Suiker</translation> </message> <message> <source>Extract</source> <translation>Extract</translation> </message> <message> <source>Dry Extract</source> <translation>Gedroogd Extract</translation> </message> <message> <source>Adjunct</source> <translation>Aanvulling</translation> </message> <message> <source>Infusion</source> <translation>Infusie</translation> </message> <message> <source>Temperature</source> <translation>Temperatuur</translation> </message> <message> <source>Decoction</source> <translation>Decoctie</translation> </message> <message> <source>Ale</source> <translation>Ale</translation> </message> <message> <source>Lager</source> <translation>Pils</translation> </message> <message> <source>Wheat</source> <translation>Tarwe</translation> </message> <message> <source>Wine</source> <translation>Wijn</translation> </message> <message> <source>Champagne</source> <translation>Champagne</translation> </message> <message> <source>Liquid</source> <translation>Vloeistof</translation> </message> <message> <source>Dry</source> <translation>Droog</translation> </message> <message> <source>Slant</source> <translation>Opgekweekt</translation> </message> <message> <source>Culture</source> <translation>Cultuur</translation> </message> <message> <source>Low</source> <translation>Laag</translation> </message> <message> <source>Medium</source> <translation>Gemiddeld</translation> </message> <message> <source>High</source> <translation>Hoog</translation> </message> <message> <source>Very High</source> <translation>Erg Hoog</translation> </message> <message> <source>Recipes</source> <translation>Recepten</translation> </message> <message> <source>Equipment</source> <translation>Apparatuur</translation> </message> <message> <source>Fermentables</source> <translation>Mout</translation> </message> <message> <source>Hops</source> <translation>Hop</translation> </message> <message> <source>Miscellaneous</source> <translation>Diversen</translation> </message> <message> <source>Yeast</source> <translation>Gist</translation> </message> <message> <source>Style</source> <translation>Stijl</translation> </message> <message> <source>Folder</source> <translation type="unfinished">Map</translation> </message> <message> <source>Failed to update the database</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Recipe</name> <message> <source>Add grains</source> <translation>Graan toevoegen</translation> </message> <message> <source>Add </source> <translation>Toevoegen </translation> </message> <message> <source>to the mash tun.</source> <translation>aan het maisch vat.</translation> </message> <message> <source>Heat water</source> <translation>Verhit water</translation> </message> <message> <source>Bring </source> <translation>Breng </translation> </message> <message> <source>%1 water to %2, </source> <translation>%1 water naar %2, </translation> </message> <message> <source>for upcoming infusions.</source> <translation>voor aanstaande infusies.</translation> </message> <message> <source>Add %1 water at %2 to mash to bring it to %3.</source> <translation>Voeg %1 water van %2 toe aan de maisch om het op %3 te brengen.</translation> </message> <message> <source>Heat mash to %1.</source> <translation>Verwarm maisch naar %1.</translation> </message> <message> <source>Bring %1 of the mash to a boil and return to the mash tun to bring it to %2.</source> <translation>Breng %1 van de maisch aan het koken en voeg het wwer terug aan het maisch vat om het naar %2 te brengen.</translation> </message> <message> <source> Hold for %1.</source> <translation> %1 aanhouden.</translation> </message> <message> <source>Put %1 %2 into boil for %3.</source> <translation>Stop %1 %2 in het kookvat voor %3.</translation> </message> <message> <source>Put %1 %2 into fermenter for %3.</source> <translation>Stop %1 %2 in het vergistingsvat voor %3.</translation> </message> <message> <source>Put %1 %2 into first wort for %3.</source> <translation>Stop %1 %2 in de eerste wort voor %3.</translation> </message> <message> <source>Put %1 %2 into mash for %3.</source> <translation>Stop %1 %2 in de maisch voor %3.</translation> </message> <message> <source>Steep %1 %2 in wort for %3.</source> <translation type="unfinished"></translation> </message> <message> <source>Use %1 %2 for %3</source> <translation>Gebruik %1 %2 voor %3</translation> </message> <message> <source>Hop addition</source> <translation>Hop gift</translation> </message> <message> <source>Use %1 %2 at bottling for %3.</source> <translation>Gebruik %1 %2 tijdens het bottelen voor %3.</translation> </message> <message> <source>Put %1 %2 into primary for %3.</source> <translation>Stop %1 %2 in de hoofdvergisting voor %3.</translation> </message> <message> <source>Put %1 %2 into secondary for %3.</source> <translation>Stop %1 %2 in het nagistingsvat voor %3.</translation> </message> <message> <source>Use %1 %2 for %3.</source> <translation>Gebruik %1 %2 voor %3.</translation> </message> <message> <source>Misc addition</source> <translation>Overige toevoegingen</translation> </message> <message> <source>Do first wort hopping with </source> <translation>Doe de eerste hopgift met </translation> </message> <message> <source>First wort hopping</source> <translation>Eerste hopgift</translation> </message> <message> <source>You should now have %1 wort.</source> <translation>U dient nu %1 wort te hebben.</translation> </message> <message> <source> Add %1 water to the kettle, bringing pre-boil volume to %2.</source> <translation> Voeg %1 water toe aan de ketel om het volume voor het koken op %2 te brengen.</translation> </message> <message> <source>Pre-boil</source> <translation>Voor het koken</translation> </message> <message> <source>Boil or steep </source> <translation>Koken of weken </translation> </message> <message> <source>Boil/steep fermentables</source> <translation>Koken/weken mout</translation> </message> <message> <source>to the boil at knockout.</source> <translation>aan het koken aan het eind.</translation> </message> <message> <source>Knockout additions</source> <translation>Toevoegingen aan het eind</translation> </message> <message> <source>You should have %1 wort post-boil.</source> <translation>U zou %1 wort moeten hebben na het koken.</translation> </message> <message> <source> You anticipate losing %1 to trub and chiller loss.</source> <translation> U anticipeert om %1 te verliezen aan eiwitafscheiding en koeler verlies.</translation> </message> <message> <source> Add %1 top up water into primary.</source> <translation> Voeg %1 top-up water toe aan hoofdvergisting.</translation> </message> <message> <source> The final volume in the primary is %1.</source> <translation> Het uiteindelijke volume in de hoofdvergisting is %1.</translation> </message> <message> <source>Post boil</source> <translation>Na het koken</translation> </message> <message> <source>Boil time</source> <translation>Kook tijd</translation> </message> <message> <source>You did not configure an equipment (which you really should), so tell me the boil time.</source> <translation>U heeft geen apparatuur geconfigureerd (wat zou moeten), dus vertel mij de kooktijd.</translation> </message> <message> <source>Bring the wort to a boil and hold for %1.</source> <translation>Breng de wort aan de kook en houd dit aan voor %1.</translation> </message> <message> <source>Start boil</source> <translation>Start het koken</translation> </message> <message> <source>Flameout</source> <translation type="unfinished"></translation> </message> <message> <source>Stop boiling the wort.</source> <translation type="unfinished"></translation> </message> <message> <source>Cool wort and pitch </source> <translation>Koel de wort en voeg gist toe </translation> </message> <message> <source>%1 %2 yeast, </source> <translation>%1 %2 gist, </translation> </message> <message> <source>to the primary.</source> <translation>aan de hoofdvergisting.</translation> </message> <message> <source>Pitch yeast</source> <translation>Voeg gist toe</translation> </message> <message> <source>Let ferment until FG is %1.</source> <translation>Laat vergisten totdat het eind SG %1 is.</translation> </message> <message> <source>Ferment</source> <translation>Vergisting</translation> </message> <message> <source>Transfer beer to secondary.</source> <translation>Hevel het bier naar het nagistingsvat.</translation> </message> <message> <source>Transfer to secondary</source> <translation>Hevel naar het nagistingsvat</translation> </message> <message> <source>Add %1 %2 to boil at %3.</source> <translation>Voeg %1 %2 toe aan het kookvat op %3.</translation> </message> <message> <source>Raise water to boil and then remove from heat. Stir in </source> <translation type="unfinished"></translation> </message> <message> <source>Add Extracts to water</source> <translation type="unfinished"></translation> </message> <message> <source>%1 water to %2 </source> <translation type="unfinished"></translation> </message> </context> <context> <name>RecipeFormatter</name> <message> <source>unknown style</source> <translation>onbekende stijl</translation> </message> <message> <source>N/A</source> <translation>Niet beschikbaar</translation> </message> <message> <source>Brewer</source> <translation>Brouwer</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Batch Size</source> <translation>Batch Grootte</translation> </message> <message> <source>Boil Size</source> <translation>Kook Volume</translation> </message> <message> <source>Boil Time</source> <translation>Kook Tijd</translation> </message> <message> <source>Efficiency</source> <translation>Efficiëntie</translation> </message> <message> <source>OG</source> <translation>Oorspronkelijk SG</translation> </message> <message> <source>FG</source> <translation>eind SG</translation> </message> <message> <source>ABV</source> <translation>Alc (vol%)</translation> </message> <message> <source>Color</source> <translation>Kleur</translation> </message> <message> <source>Fermentables</source> <translation>Mout</translation> </message> <message> <source>Total grain:</source> <translation>Totaal granen:</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Mashed</source> <translation>Gemaischd</translation> </message> <message> <source>Late</source> <translation>Late</translation> </message> <message> <source>Yield</source> <translation>Rendement</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>No</source> <translation>Nee</translation> </message> <message> <source>Hops</source> <translation>Hop</translation> </message> <message> <source>Alpha</source> <translation>Alpha</translation> </message> <message> <source>Use</source> <translation>Gebruik</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>IBU</source> <translation>IBU</translation> </message> <message> <source>Misc</source> <translation>Diversen</translation> </message> <message> <source>Yeast</source> <translation>Gist</translation> </message> <message> <source>Stage</source> <translation>Fase</translation> </message> <message> <source>Secondary</source> <translation>nagistingsvat</translation> </message> <message> <source>Primary</source> <translation>Hoofdvergisting</translation> </message> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>Temp</source> <translation>Temperatuur</translation> </message> <message> <source>Target Temp</source> <translation>Streef Temp</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> <message> <source>Instructions</source> <translation>Instructies</translation> </message> <message> <source>Brew Date</source> <translation type="unfinished">Brouwdatum</translation> </message> <message> <source>Preboil</source> <translation type="unfinished"></translation> </message> <message> <source>SG</source> <translation>SG</translation> </message> <message> <source>Volume into BK</source> <translation type="unfinished"></translation> </message> <message> <source>Strike Temp</source> <translation type="unfinished"></translation> </message> <message> <source>Final Temp</source> <translation type="unfinished"></translation> </message> <message> <source>Eff into BK</source> <translation type="unfinished"></translation> </message> <message> <source>Projected OG</source> <translation type="unfinished"></translation> </message> <message> <source>Postboil</source> <translation type="unfinished"></translation> </message> <message> <source>Postboil Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Volume Into Fermenter</source> <translation type="unfinished"></translation> </message> <message> <source>Brewhouse Eff</source> <translation type="unfinished"></translation> </message> <message> <source>Projected ABV</source> <translation type="unfinished"></translation> </message> <message> <source>Postferment</source> <translation type="unfinished"></translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Print Document</source> <translation>Print Document</translation> </message> <message> <source>Category</source> <translation>Categorie</translation> </message> <message> <source>Code</source> <translation type="unfinished"></translation> </message> <message> <source>Guide</source> <translation type="unfinished"></translation> </message> <message> <source>BoilTime</source> <translation type="unfinished"></translation> </message> <message> <source>Beta</source> <translation type="unfinished"></translation> </message> <message> <source>Lab</source> <translation>Lab</translation> </message> <message> <source>Attenuation</source> <translation type="unfinished"></translation> </message> <message> <source>Id</source> <translation type="unfinished"></translation> </message> <message> <source>Flocculation</source> <translation>Flocculatie</translation> </message> <message> <source>Miscs</source> <translation type="unfinished">Diversen</translation> </message> <message> <source>Yeasts</source> <translation type="unfinished">Gist</translation> </message> <message> <source>Estimated calories (per 33 cl)</source> <translation type="unfinished"></translation> </message> <message> <source>Estimated calories (per 12 oz)</source> <translation type="unfinished">Geschat aantal calorieën (per 340 g)</translation> </message> <message> <source>Bitterness</source> <translation type="unfinished"></translation> </message> <message> <source>Target</source> <translation type="unfinished"></translation> </message> </context> <context> <name>RefractoDialog</name> <message> <source>OG Mismatch</source> <translation>Onjuiste combinatie oorspronkelijk SG</translation> </message> <message> <source>Based on the given original plato, the OG should be %1, but you have entered %2. Continuing with the calculated OG.</source> <translation>Gebaseerd op de opgegeven oorspronkelijke plato zou het oorspronkelijk SG %1 moeten zijn, maar u heeft %2 ingevoerd. Het programma gaat door met het berekende oorspronkelijke SG.</translation> </message> </context> <context> <name>ScaleRecipeEquipmentPage</name> <message> <source>Select Equipment</source> <translation type="unfinished"></translation> </message> <message> <source>The recipe will be scaled to match the batch size and efficiency of the selected equipment</source> <translation type="unfinished"></translation> </message> <message> <source>New Equipment</source> <translation type="unfinished"></translation> </message> <message> <source>New Efficiency (%)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ScaleRecipeIntroPage</name> <message> <source>Scale Recipe</source> <translation type="unfinished"></translation> </message> <message> <source>This wizard will help you scale a recipe to another size or efficiency.Select another equipment with the new batch size and/or efficiency andthe wizard will scale the recipe ingredients automatically.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ScaleRecipeTool</name> <message> <source>Recipe Scaled</source> <translation>Recept Geschaald</translation> </message> <message> <source>The equipment and mash have been reset due to the fact that mash temperatures do not scale easily. Please re-run the mash wizard.</source> <translation>Deapparatuur en maisch zijn gereset omdat de maisch temperatuur niet eenvoudig schaalt. Draai de maisch wizard opnieuw a.u.b.</translation> </message> </context> <context> <name>StyleEditor</name> <message> <source>Style name</source> <translation>Stijl naam</translation> </message> <message> <source>Style name:</source> <translation>Stijl naam:</translation> </message> </context> <context> <name>TimerWidget</name> <message> <source>Open Sound</source> <translation>Open Geluid</translation> </message> <message> <source>Audio Files (*.wav *.ogg *.mp3 *.aiff)</source> <translation>Audio Files (*.wav *.ogg *.mp3 *.aiff)</translation> </message> <message> <source>Stop</source> <translation>Stop</translation> </message> <message> <source>Start</source> <translation>Start</translation> </message> <message> <source>Set the timer to the specified value</source> <translation>Zet de timer op de gespecificeerde waarde</translation> </message> <message> <source>HH:MM:SS</source> <translation type="unfinished"></translation> </message> <message> <source>Start/Stop timer</source> <translation>Start/Stop timer</translation> </message> <message> <source>Set a sound as the alarm</source> <translation>Zet een geluid als alarm</translation> </message> <message> <source>Set</source> <translation>Instellen</translation> </message> <message> <source>Sound</source> <translation>Geluid</translation> </message> </context> <context> <name>WaterTableModel</name> <message> <source>Bad model index. row = %1</source> <translation>Bad model index. row = %1</translation> </message> <message> <source>Bad column: %1</source> <translation>Bad column: %1</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Calcium (ppm)</source> <translation>Calcium (ppm)</translation> </message> <message> <source>Bicarbonate (ppm)</source> <translation>Bicarbonaat (ppm)</translation> </message> <message> <source>Sulfate (ppm)</source> <translation>Sulfaat (ppm)</translation> </message> <message> <source>Chloride (ppm)</source> <translation>Chloor (ppm)</translation> </message> <message> <source>Sodium (ppm)</source> <translation>Soda (ppm)</translation> </message> <message> <source>Magnesium (ppm)</source> <translation>Magnesium (ppm)</translation> </message> </context> <context> <name>YeastDialog</name> <message> <source>Yeast name</source> <translation>Gist naam</translation> </message> <message> <source>Yeast name:</source> <translation>Gist naam:</translation> </message> <message> <source>Yeast Database</source> <translation>Gist Databank</translation> </message> <message> <source>Add to Recipe</source> <translation type="unfinished"></translation> </message> <message> <source>New</source> <translation>Nieuw</translation> </message> <message> <source>Add selected ingredient to recipe</source> <translation type="unfinished"></translation> </message> <message> <source>Create new ingredient</source> <translation>Creëer nieuw ingrediënt</translation> </message> <message> <source>Edit selected ingredient</source> <translation>Edit geselecteerde ingrediënt</translation> </message> <message> <source>Remove selected ingredient</source> <translation>Verwijder geselecteerde ingrediënt</translation> </message> </context> <context> <name>YeastItemDelegate</name> <message> <source>Ale</source> <translation>Ale</translation> </message> <message> <source>Lager</source> <translation>Pils</translation> </message> <message> <source>Wheat</source> <translation>Tarwe</translation> </message> <message> <source>Wine</source> <translation>Wijn</translation> </message> <message> <source>Champagne</source> <translation>Champagne</translation> </message> <message> <source>Liquid</source> <translation>Vloeistof</translation> </message> <message> <source>Dry</source> <translation>Droog</translation> </message> <message> <source>Slant</source> <translation>Opgekweekt</translation> </message> <message> <source>Culture</source> <translation>Cultuur</translation> </message> </context> <context> <name>YeastTableModel</name> <message> <source>Bad model index. row = %1</source> <translation>Bad model index. row = %1</translation> </message> <message> <source>Bad column: %1</source> <translation>Bad column: %1</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Laboratory</source> <translation>Laboratorium</translation> </message> <message> <source>Product ID</source> <translation>Product ID</translation> </message> <message> <source>Inventory</source> <translation type="unfinished"></translation> </message> </context> <context> <name>brewDayScrollWidget</name> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Generate Instructions</source> <translation>Genereer Instructies</translation> </message> <message> <source>Insert step</source> <translation>Voeg stap toe</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Name of new step</source> <translation>Naam van de nieuwe stap</translation> </message> <message> <source>Step #</source> <translation>Stap #</translation> </message> <message> <source>The number where the new step should be placed</source> <translation>Het nummer waar de nieuwe staop geplaatst moet worden</translation> </message> <message> <source>Insert the new step</source> <translation>Voer de nieuwe stap in</translation> </message> <message> <source>Move steps</source> <translation>Verplaats stappen</translation> </message> <message> <source>Move currently selected step up</source> <translation>Verplaats de geselecteerde stap omhoog</translation> </message> <message> <source>Move currently selected step down</source> <translation>Verplaats de geselecteerde stap omlaag</translation> </message> <message> <source>Remove currently selected step</source> <translation>Verwijder geselecteerde stap</translation> </message> </context> <context> <name>brewDayWidget</name> <message> <source>Brewday Mode</source> <translation>Brouwdag Modus</translation> </message> <message> <source>Instructions</source> <translation>Instructies</translation> </message> <message> <source>Move currently selected step up</source> <translation>Verplaats de geselecteerde stap omhoog</translation> </message> <message> <source>Up</source> <translation>Omhoog</translation> </message> <message> <source>Move currently selected step down</source> <translation>Verplaats de geselecteerde stap omlaag</translation> </message> <message> <source>Down</source> <translation>naar Beneden</translation> </message> <message> <source>Remove currently selected step</source> <translation>Verwijder geselecteerde stap</translation> </message> <message> <source>Remove</source> <translation>Verwijder</translation> </message> <message> <source>Insert step</source> <translation>Voer stap in</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Name of new step</source> <translation>Naam van de nieuwe stap</translation> </message> <message> <source>Step #</source> <translation>Stap #</translation> </message> <message> <source>The number where the new step should be placed</source> <translation>Het nummer waar de nieuwe stap geplaatst moet worden</translation> </message> <message> <source>Insert the new step</source> <translation>Voer de nieuwe stap in</translation> </message> <message> <source>Insert</source> <translation>Voer in</translation> </message> </context> <context> <name>brewNoteWidget</name> <message> <source>Preboil</source> <translation type="unfinished"></translation> </message> <message> <source>SG</source> <translation>SG</translation> </message> <message> <source>Preboil gravity</source> <translation type="unfinished"></translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Volume of wort collected</source> <translation type="unfinished"></translation> </message> <message> <source>Strike Temp</source> <translation type="unfinished"></translation> </message> <message> <source>Temperature of mash after dough in</source> <translation type="unfinished"></translation> </message> <message> <source>Final Temp</source> <translation type="unfinished"></translation> </message> <message> <source>Temperature of mash before mash out</source> <translation type="unfinished"></translation> </message> <message> <source>Postboil</source> <translation type="unfinished"></translation> </message> <message> <source>OG</source> <translation>Oorspronkelijk SG</translation> </message> <message> <source>Post boil gravity</source> <translation type="unfinished"></translation> </message> <message> <source>Postboil Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Volume of wort in BK after boil</source> <translation type="unfinished"></translation> </message> <message> <source>Volume of wort transferred to fermenter</source> <translation type="unfinished"></translation> </message> <message> <source>Volume into fermenter</source> <translation>Volume in het vergistingsvat</translation> </message> <message> <source> Pitch Temp</source> <translation type="unfinished"></translation> </message> <message> <source>Temperature of wort when yeast is pitched</source> <translation type="unfinished"></translation> </message> <message> <source>Postferment</source> <translation type="unfinished"></translation> </message> <message> <source>Final gravity</source> <translation type="unfinished"></translation> </message> <message> <source>Volume of beer into serving keg/bottles</source> <translation type="unfinished"></translation> </message> <message> <source>percent efficiency into boil kettle</source> <translation type="unfinished"></translation> </message> <message> <source>Eff into BK</source> <translation type="unfinished"></translation> </message> <message> <source>Expected OG, based on measure fg</source> <translation type="unfinished"></translation> </message> <message> <source>Projected OG</source> <translation type="unfinished"></translation> </message> <message> <source>Brewhouse efficiency</source> <translation type="unfinished"></translation> </message> <message> <source>Brewhouse Eff</source> <translation type="unfinished"></translation> </message> <message> <source>Expected ABV based on OG</source> <translation type="unfinished"></translation> </message> <message> <source>Projected ABV</source> <translation type="unfinished"></translation> </message> <message> <source>ABV based on FG</source> <translation type="unfinished"></translation> </message> <message> <source>ABV</source> <translation>Alc (vol%)</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> <message> <source>brewNote</source> <translation type="unfinished"></translation> </message> <message> <source>yyyy-dd-MM</source> <translation type="unfinished"></translation> </message> </context> <context> <name>equipmentEditor</name> <message> <source>Specific heat (cal/(g*K))</source> <translation>Specifieke hitte (cal/(g*K))</translation> </message> <message> <source>Losses</source> <translation>Verliezen</translation> </message> <message> <source>Kettle to fermenter</source> <translation>Ketel naar Vergistingsvat</translation> </message> <message> <source>Lauter deadspace</source> <translation>Dode ruimte Klaring</translation> </message> <message> <source>equipmentEditor</source> <translation type="unfinished"></translation> </message> </context> <context> <name>fermentableEditor</name> <message> <source>Fermentable Editor</source> <translation>Vergistbaren Editor</translation> </message> <message> <source>Required Fields</source> <translation>Vereiste Velden</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Grain</source> <translation>Graan</translation> </message> <message> <source>Sugar</source> <translation>Suiker</translation> </message> <message> <source>Extract</source> <translation>Extract</translation> </message> <message> <source>Dry Extract</source> <translation>Droog Extract</translation> </message> <message> <source>Adjunct</source> <translation>Aanvulling</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Yield (%)</source> <translation>Rendement (%)</translation> </message> <message> <source>Yield as compared to glucose</source> <translation>Rendement in vergelijking met glucose</translation> </message> <message> <source>Lovibond rating</source> <translation>Lovibond waarde</translation> </message> <message> <source>Add After Boil</source> <translation>Toevoegen na het koken</translation> </message> <message> <source>This ingredient is added post boil.</source> <translation>Dit ingrediënt is na het koken toegevoegd.</translation> </message> <message> <source>Origin</source> <translation>Origine</translation> </message> <message> <source>Supplier</source> <translation>Leverancier</translation> </message> <message> <source>Coarse/Fine Diff (%)</source> <translation>Grof/Fijn Verschil (%)</translation> </message> <message> <source>Yield difference between coarse and fine grind</source> <translation>Rendement verschil tussen grof en fijn geschrootte mout</translation> </message> <message> <source>Moisture (%)</source> <translation>Vleostof (%1)</translation> </message> <message> <source>Moisture percentage by mass</source> <translation>Vocht percentage bij massa</translation> </message> <message> <source>DP (Lintner)</source> <translation>DP (Lintner)</translation> </message> <message> <source>Diastatic power in Lintner</source> <translation>Diastatische kracht in Lintner</translation> </message> <message> <source>Protein (%)</source> <translation>Proteïne (%1)</translation> </message> <message> <source>Protein percentage by mass</source> <translation>Eiwit percentage bij massa</translation> </message> <message> <source>Max In Batch (%)</source> <translation>Max In Batch (%)</translation> </message> <message> <source>Maximum recommended percentage of total grist</source> <translation>Maximum aanbevolen percentage van totale schrootsel</translation> </message> <message> <source>Recommend Mash</source> <translation>Aanbevolen maisch</translation> </message> <message> <source>Recommend this be mashed</source> <translation>Aanbevolen om te maischen</translation> </message> <message> <source>Is Mashed</source> <translation>is gemaischt</translation> </message> <message> <source>Checked if it is present in mash</source> <translation>Gecontroleerd op aanwezigheid in maisch</translation> </message> <message> <source>Bitterness (IBU*gal/lb)</source> <translation>Bitterheid (IBU*gal/lb)</translation> </message> <message> <source>Bitterness of pre-hopped extracts</source> <translation>Bitterheid van voorgehopte extracten</translation> </message> <message> <source>Notes:</source> <translation>Aantekeningen:</translation> </message> <message> <source>Default Amount</source> <translation type="unfinished"></translation> </message> <message> <source>Amount in Inventory</source> <translation type="unfinished"></translation> </message> <message> <source>Amount in inventory</source> <translation type="unfinished"></translation> </message> <message> <source>Color</source> <translation>Kleur</translation> </message> </context> <context> <name>hopEditor</name> <message> <source>Hop Editor</source> <translation>Hop Editor</translation> </message> <message> <source>Required Fields</source> <translation>Vereiste Velden</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Alpha (%)</source> <translation>Alpha (%)</translation> </message> <message> <source>Alpha acids as percent by mass</source> <translation>Alpha ziir als percentage van de massa</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Use</source> <translation>Gebruik</translation> </message> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>First Wort</source> <translation>Eerste Wort</translation> </message> <message> <source>Boil</source> <translation>Koken</translation> </message> <message> <source>Aroma</source> <translation>Aroma</translation> </message> <message> <source>Dry Hop</source> <translation>Dry Hop</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Bittering</source> <translation>Bitterhop</translation> </message> <message> <source>Both</source> <translation>Beide</translation> </message> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Leaf</source> <translation>Blad</translation> </message> <message> <source>Pellet</source> <translation>Pellet</translation> </message> <message> <source>Plug</source> <translation>Geperste hop</translation> </message> <message> <source>Beta (%)</source> <translation>Beta (%)</translation> </message> <message> <source>Beta acids as percent by mass</source> <translation>Beta zuur als percentage van de massa</translation> </message> <message> <source>HSI</source> <translation>HSI</translation> </message> <message> <source>Hop Stability/Storage index</source> <translation>Hop Stabiliteit/Opslag index</translation> </message> <message> <source>Origin</source> <translation>Origine</translation> </message> <message> <source>Humulene (%)</source> <translation>Humuleen (%)</translation> </message> <message> <source>Humulene</source> <translation>Humuleen</translation> </message> <message> <source>Caryophyllene (%)</source> <translation>Caryophylleen (%)</translation> </message> <message> <source>Caryophyllene</source> <translation>Caryophylleen</translation> </message> <message> <source>Cohumulone (%)</source> <translation>Cohumuloon (%)</translation> </message> <message> <source>Cohumulone</source> <translation>Cohumuloon</translation> </message> <message> <source>Myrcene (%)</source> <translation>Myrceen (%)</translation> </message> <message> <source>Myrcene</source> <translation>Myrceen</translation> </message> <message> <source>Substitutes:</source> <translation>Vervangingen:</translation> </message> <message> <source>Notes:</source> <translation>Aantekeningen:</translation> </message> <message> <source>Default Amount </source> <translation type="unfinished"></translation> </message> <message> <source>Amount in Inventory</source> <translation type="unfinished"></translation> </message> <message> <source>Amount in inventory</source> <translation type="unfinished"></translation> </message> </context> <context> <name>instructionWidget</name> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Show a timer</source> <translation>Toon een timer</translation> </message> <message> <source>Show timer</source> <translation>Toon timer</translation> </message> <message> <source>Mark this step completed</source> <translation>Markeer deze stap als compleet</translation> </message> <message> <source>Step completed</source> <translation>Stap compleet</translation> </message> </context> <context> <name>mainWindow</name> <message> <source>Recipes</source> <translation>Recepten</translation> </message> <message> <source>Styles</source> <translation type="unfinished"></translation> </message> <message> <source>Fermentables</source> <translation>Mout</translation> </message> <message> <source>Hops</source> <translation>Hop</translation> </message> <message> <source>Miscs</source> <translation>Diversen</translation> </message> <message> <source>Yeasts</source> <translation>Gist</translation> </message> <message> <source>Recipe</source> <translation>Recept</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Name of recipe</source> <translation>Naam van het recept</translation> </message> <message> <source>Target boil size</source> <translation>Streef Kook grootte</translation> </message> <message> <source>Efficiency (%)</source> <translation>Efficiëntie (%)</translation> </message> <message> <source>Calculated Boil Size</source> <translation>Berekende Kook grootte</translation> </message> <message> <source>Calculated Batch Size</source> <translation>Berekende Batch grootte</translation> </message> <message> <source>The extraction efficiency you expect</source> <translation>Verwachtte brouwzaal rendement</translation> </message> <message> <source>Style</source> <translation>Stijl</translation> </message> <message> <source>Boil Time</source> <translation>Kooktijd</translation> </message> <message> <source>Target batch size</source> <translation>Streef Batch grootte</translation> </message> <message> <source>Target Batch Size</source> <translation>Streef Batch grootte</translation> </message> <message> <source>Equipment</source> <translation>Apparatuur</translation> </message> <message> <source>Target Boil Size</source> <translation>Streef Kook grootte</translation> </message> <message> <source>OG</source> <translation>Oorspronkelijke SG</translation> </message> <message> <source>Boil SG</source> <translation>Kook SG</translation> </message> <message> <source>FG</source> <translation>Eind SG</translation> </message> <message> <source>ABV</source> <translation>Alc (vol%)</translation> </message> <message> <source>Bitterness (IBU)</source> <translation>Bitterheid (IBU)</translation> </message> <message> <source>Color</source> <translation>Kleur</translation> </message> <message> <source>IBU/GU</source> <translation>IBU/GU</translation> </message> <message> <source>Calories/12oz</source> <translation type="unfinished"></translation> </message> <message> <source>Extras</source> <translation>Extras</translation> </message> <message> <source>Brewday</source> <translation>Brouwdag</translation> </message> <message> <source>Add a fermentable</source> <translation>Voeg een vergistbare toe</translation> </message> <message> <source>Remove selected fermentable</source> <translation>Verwijder geselecteerde vergistbare</translation> </message> <message> <source>Edit selected fermentable</source> <translation>Edit geselecteerde vergistbare</translation> </message> <message> <source>Add hop</source> <translation>Voeg Hop toe</translation> </message> <message> <source>Remove selected hop</source> <translation>Verwijder geselecteerde hop</translation> </message> <message> <source>Edit selected hop</source> <translation>Edit geselecteerde hop</translation> </message> <message> <source>Miscellaneous</source> <translation>Diversen</translation> </message> <message> <source>Add misc</source> <translation>Voeg diversen toe</translation> </message> <message> <source>Remove selected misc</source> <translation>Verwijder geselecteerde diversen</translation> </message> <message> <source>Edit selected misc</source> <translation>Edit geselecteerde Diversen</translation> </message> <message> <source>Yeast</source> <translation>Gist</translation> </message> <message> <source>Add yeast</source> <translation>Voeg Gist toe</translation> </message> <message> <source>Remove selected yeast</source> <translation>Verwijder geselecteerde gist</translation> </message> <message> <source>Edit selected yeast</source> <translation>Edit geselecteerde gist</translation> </message> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>Add mash step</source> <translation>Voeg maisch stap toe</translation> </message> <message> <source>Remove selected mash step</source> <translation>Verwijder geselecteerde maisch stap</translation> </message> <message> <source>Edit selected mash step</source> <translation>Edit geselecteerde maisch stap</translation> </message> <message> <source>Edit mash properties</source> <translation>Edit maisch eigenschappen</translation> </message> <message> <source>Edit mash</source> <translation>Edit maisch</translation> </message> <message> <source>Mash Des</source> <translation>Maisch bestemming</translation> </message> <message> <source>Invoke the mash wizard</source> <translation>Draai de maisch wizard</translation> </message> <message> <source>Mash wiz</source> <translation>Maisch wizard</translation> </message> <message> <source>Mashs</source> <translation>Maisch</translation> </message> <message> <source>Mash step up</source> <translation>Maisch stap omhoog</translation> </message> <message> <source>Mash step down</source> <translation>Maisch stap omlaag</translation> </message> <message> <source>Save this mash profile</source> <translation>Sla dit maisch profiel op</translation> </message> <message> <source>Save Mash</source> <translation>Opslaan Maisch</translation> </message> <message> <source>&amp;About</source> <translation>Over</translation> </message> <message> <source>&amp;File</source> <translation>Bestand</translation> </message> <message> <source>&amp;Brewday</source> <translation>Brouwdag</translation> </message> <message> <source>&amp;Recipe</source> <translation>Recept</translation> </message> <message> <source>&amp;Database</source> <translation>Database</translation> </message> <message> <source>&amp;View</source> <translation>Bekijk</translation> </message> <message> <source>&amp;Tools</source> <translation>Gereedschap</translation> </message> <message> <source>toolBar</source> <translation>gereedschapsBalk</translation> </message> <message> <source>About &amp;BrewTarget</source> <translation>Over Brewtarget</translation> </message> <message> <source>About Brewtarget</source> <translation>Over Brewtarget</translation> </message> <message> <source>&amp;Export Recipe</source> <translation>Exporteer recept</translation> </message> <message> <source>&amp;Fermentables</source> <translation>Mout</translation> </message> <message> <source>Ctrl+F</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Hops</source> <translation>Hop</translation> </message> <message> <source>Ctrl+H</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Miscs</source> <translation>Diversen</translation> </message> <message> <source>Ctrl+M</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Yeasts</source> <translation>Gist</translation> </message> <message> <source>Ctrl+Y</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Equipments</source> <translation>Apparatuur</translation> </message> <message> <source>Ctrl+E</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Styles</source> <translation>Stijlen</translation> </message> <message> <source>Ctrl+T</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Exit</source> <translation>Einde</translation> </message> <message> <source>Ctrl+Q</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Import Recipes</source> <translation>Importeer Recepten</translation> </message> <message> <source>&amp;Options</source> <translation>Opties</translation> </message> <message> <source>&amp;Manual</source> <translation>Handleiding</translation> </message> <message> <source>&amp;Scale Recipe</source> <translation>Schaal Recept</translation> </message> <message> <source>Recipe to Clipboard as &amp;Text</source> <translation>Recept naar Klembord als Tekst</translation> </message> <message> <source>&amp;OG Correction Help</source> <translation>Hulp bij correctie oorspronkelijk SG</translation> </message> <message> <source>&amp;Convert Units</source> <translation>Conversie Eenheden</translation> </message> <message> <source>Backup Database</source> <translation>Backup Database</translation> </message> <message> <source>Restore Database</source> <translation>Restore Database</translation> </message> <message> <source>&amp;Copy Recipe</source> <translation>Copiëer Recept</translation> </message> <message> <source>Pr&amp;iming Calculator</source> <translation>Rekenhulp suiker toevoeging</translation> </message> <message> <source>&amp;Refractometer Tools</source> <translation>Refractometer Gereedschap</translation> </message> <message> <source>&amp;Pitch Rate Calculator</source> <translation>Gistgift rekenhulp</translation> </message> <message> <source>Merge Databases</source> <translation>Database Samenvoegen</translation> </message> <message> <source>Select another database to merge into the current one.</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Print</source> <translation>Print</translation> </message> <message> <source>Print Pre&amp;view</source> <translation>Print Preview</translation> </message> <message> <source>&amp;Export To HTML</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Export to HTML</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Backup</source> <translation type="unfinished"></translation> </message> <message> <source>Save all recipes, ingredients, etc. to a backup folder</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Restore</source> <translation type="unfinished"></translation> </message> <message> <source>Restore recipes, ingredients, etc. from a previous backup</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Merge</source> <translation type="unfinished"></translation> </message> <message> <source>Merge another set of recipes, ingredients, etc. into the current set</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;New Recipe</source> <translation>Nieuw recept</translation> </message> <message> <source>Timers</source> <translation>Timers</translation> </message> <message> <source>Show timers</source> <translation>Toon timer</translation> </message> <message> <source>Save</source> <translation>Opslaan</translation> </message> <message> <source>Delete selected</source> <translation type="unfinished"></translation> </message> <message> <source>Delete recipe</source> <translation>Verwijder recept</translation> </message> <message> <source>&amp;Mashs</source> <translation type="unfinished"></translation> </message> <message> <source>Mashes</source> <translation type="unfinished"></translation> </message> <message> <source>1.0</source> <translation>1.0</translation> </message> <message> <source>Strike Water Calculator</source> <translation type="unfinished"></translation> </message> <message> <source>tab_recipe</source> <translation type="unfinished"></translation> </message> <message> <source>Export to &amp;BBCode</source> <translation type="unfinished"></translation> </message> </context> <context> <name>mashDesigner</name> <message> <source>Mash Designer</source> <translation>Maisch Ontwerper</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Target temp.</source> <translation>Beoogde temp.</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Batch Sparge</source> <translation>Batch uitspoelen</translation> </message> <message> <source>Next</source> <translation>Volgende</translation> </message> <message> <source>Finish</source> <translation>Beëindigen</translation> </message> <message> <source>Infusion/Decoction Amount</source> <translation>Infusie/Decoctie Hoeveelheid</translation> </message> <message> <source>min</source> <translation>min</translation> </message> <message> <source>max</source> <translation>max</translation> </message> <message> <source>0</source> <translation>0</translation> </message> <message> <source>Infusion Temp</source> <translation>Infusie Temp</translation> </message> <message> <source>Total Collected Wort</source> <translation>Totaal Verzamelde Wort</translation> </message> <message> <source>vol</source> <translation>vol</translation> </message> <message> <source>Tun Fullness</source> <translation>Volheid van het vat</translation> </message> <message> <source>tunVol</source> <translation>Vat Volume</translation> </message> <message> <source>thickness</source> <translation>Dikte</translation> </message> </context> <context> <name>mashEditor</name> <message> <source>Mash Editor</source> <translation>Maisch Editor</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Initial grain temp</source> <translation>Initiële graan temp</translation> </message> <message> <source>Sparge temp</source> <translation>Spoel temp</translation> </message> <message> <source>Sparge temp target</source> <translation>Beoogde Spoel temp</translation> </message> <message> <source>Sparge pH</source> <translation>Spoel pH</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> <message> <source>Tun</source> <translation>Vat</translation> </message> <message> <source>Initial tun temp</source> <translation>Initiële vat temp</translation> </message> <message> <source>Get following parameters from the recipe&apos;s equipment.</source> <translation>Verkrijg de volgende parameters van de apparatuur van het recept.</translation> </message> <message> <source>From Equipment</source> <translation>Van Apparatuur</translation> </message> <message> <source>Tun mass</source> <translation>Vat massa</translation> </message> <message> <source>Tun sp. heat</source> <translation>Vat spec. hitte</translation> </message> <message> <source>Tun specific heat (cal/(g*K))</source> <translation>Vat specifieke hitte (cal/g*K)</translation> </message> </context> <context> <name>mashStepEditor</name> <message> <source>Mash Step Editor</source> <translation>Maisch Stap Editor</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Infusion</source> <translation>Infusie</translation> </message> <message> <source>Temperature</source> <translation>Temeratuur</translation> </message> <message> <source>Decoction</source> <translation>Decoctie</translation> </message> <message> <source>Target temp.</source> <translation>Beoogde temp.</translation> </message> <message> <source>Target temp. of this step</source> <translation>Beoogde temp van deze stap</translation> </message> <message> <source>Infuse Amount</source> <translation>Infusie Hoeveelheid</translation> </message> <message> <source>Amount of water to infuse</source> <translation>Hoeveelheid water voor infusie</translation> </message> <message> <source>Infuse temp.</source> <translation>Infusie temp.</translation> </message> <message> <source>Temperature of infusion water</source> <translation>Temperatuur van infusie water</translation> </message> <message> <source>Decoction Amount</source> <translation>Decoctie Hoeveelheid</translation> </message> <message> <source>Amount of mash to decoct</source> <translation>Hoeveelheid maisch voor decoctie</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Time to conduct the step</source> <translation>Tijd om stap uit te voeren</translation> </message> <message> <source>Temp. lag time</source> <translation>Temp. lagfase</translation> </message> <message> <source>Lag time</source> <translation>lagfase</translation> </message> <message> <source>End temp.</source> <translation>Eind temp.</translation> </message> <message> <source>Final temp. of this step</source> <translation>Eind temp. van deze stap</translation> </message> </context> <context> <name>mashWizard</name> <message> <source>Mash Wizard</source> <translation>Maisch wizard</translation> </message> <message> <source>Mash thickness (L/kg)</source> <translation>Maisch dikte (L/kg)</translation> </message> <message> <source>Mash thickness (do not enter any units)</source> <translation>Maisch dikte (voer geen eenheden in)</translation> </message> </context> <context> <name>miscEditor</name> <message> <source>Misc Editor</source> <translation>Diversen Editor</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Spice</source> <translation>Specerij</translation> </message> <message> <source>Fining</source> <translation>Fining</translation> </message> <message> <source>Water Agent</source> <translation>Waterbehandeling</translation> </message> <message> <source>Herb</source> <translation>Kruid</translation> </message> <message> <source>Flavor</source> <translation>Smaak</translation> </message> <message> <source>Other</source> <translation>Overig</translation> </message> <message> <source>Use</source> <translation>Gebruik</translation> </message> <message> <source>Boil</source> <translation>Koken</translation> </message> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>Primary</source> <translation>Hoofdvergististing</translation> </message> <message> <source>Secondary</source> <translation>Secundair</translation> </message> <message> <source>Bottling</source> <translation>Bottelen</translation> </message> <message> <source>Time</source> <translation>Tijd</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Check it if the amount listed is in kg instead of L.</source> <translation>Controleer of de hoeveelheid vermeld staat in kg i.p.v. L.</translation> </message> <message> <source>Amount is weight?</source> <translation>Hoeveelheid is gewicht?</translation> </message> <message> <source>Checked if the given amount is weight instead of volume</source> <translation>Controleer of de opgegeven hoeveelheid gewicht is i.p.v. volume</translation> </message> <message> <source>Use for:</source> <translation>Gebruik voor:</translation> </message> <message> <source>Notes:</source> <translation>Aantekeningen:</translation> </message> <message> <source>Default Amount</source> <translation type="unfinished"></translation> </message> <message> <source>Amount in Inventory</source> <translation type="unfinished"></translation> </message> <message> <source>Amount in inventory</source> <translation type="unfinished"></translation> </message> </context> <context> <name>namedMashEditor</name> <message> <source>Named Mash Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Mash</source> <translation>Maisch</translation> </message> <message> <source>Delete selected style</source> <translation>Verwijder geselecteerde stijl</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Initial grain temp</source> <translation>Initiële graan temp</translation> </message> <message> <source>Sparge temp</source> <translation>Spoel temp</translation> </message> <message> <source>Sparge temp target</source> <translation>Beoogde Spoel temp</translation> </message> <message> <source>Sparge pH</source> <translation>Spoel pH</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> <message> <source>Tun</source> <translation>Vat</translation> </message> <message> <source>Initial tun temp</source> <translation>Initiële vat temp</translation> </message> <message> <source>From Equipment</source> <translation>Van Apparatuur</translation> </message> <message> <source>Tun mass</source> <translation>Vat massa</translation> </message> <message> <source>Tun sp. heat</source> <translation>Vat spec. hitte</translation> </message> <message> <source>Tun specific heat (cal/(g*K))</source> <translation>Vat specifieke hitte (cal/g*K)</translation> </message> <message> <source>Add mash step</source> <translation>Voeg maisch stap toe</translation> </message> <message> <source>Remove selected mash step</source> <translation>Verwijder geselecteerde maisch stap</translation> </message> <message> <source>Mash step up</source> <translation>Maisch stap omhoog</translation> </message> <message> <source>Mash step down</source> <translation>Maisch stap omlaag</translation> </message> </context> <context> <name>ogAdjuster</name> <message> <source>Adjust Volume to Hit OG</source> <translation>Coorigeer volume om met OG te matchen</translation> </message> <message> <source>Input</source> <translation>Invoer</translation> </message> <message> <source>SG</source> <translation>SG</translation> </message> <message> <source>Measured gravity pre-boil</source> <translation>Gemeten SG voor het koken</translation> </message> <message> <source>Temp</source> <translation>Temp</translation> </message> <message> <source>Temperature of SG reading</source> <translation>Temperatuur van het afgelezen SG</translation> </message> <message> <source>Calibration Temp</source> <translation>Calibratie Temp</translation> </message> <message> <source>Temp to which the hydrometer is calibrated</source> <translation>Temp waar op de hydrometer is gecaibreerd</translation> </message> <message> <source>-or-</source> <translation>-of-</translation> </message> <message> <source>Plato</source> <translation>Plato</translation> </message> <message> <source>Plato (percent by mass of equivalent sucrose)</source> <translation>Plato(massa percentage van sucrose equivalent)</translation> </message> <message> <source>Pre-Boil Volume</source> <translation>Volume voor het koken</translation> </message> <message> <source>Measured pre-boil volume</source> <translation>Gemeten volume voor het koken</translation> </message> <message> <source>Output</source> <translation>Uitvoer</translation> </message> <message> <source>OG w/o Correction</source> <translation>Oorspronkelijk SG zonder correctie</translation> </message> <message> <source>OG if you boil as planned</source> <translation>Oorspronkelijk SG bij koken volgens planning</translation> </message> <message> <source>Add to Boil</source> <translation>Toevoegen bij het koken</translation> </message> <message> <source>Amount of water you need to add to hit planned OG (or boil off if negative)</source> <translation>Benodigde hoeveelheid water om toe te voegen om eht geplande oorspronkelijk SG te halen (of verdampen indien negatief)</translation> </message> <message> <source>Final Batch Size</source> <translation>Uiteindelijke Batch Grootte</translation> </message> <message> <source>Estimated batch size after correction</source> <translation>Geschatte batch grootte na correctie</translation> </message> <message> <source>Calculate</source> <translation>Bereken</translation> </message> </context> <context> <name>optionsDialog</name> <message> <source>Options</source> <translation>Opties</translation> </message> <message> <source>Units</source> <translation>Eenheden</translation> </message> <message> <source>Weight</source> <translation>Gewicht</translation> </message> <message> <source>Use SI units</source> <translation>Gebruik SI eenheden</translation> </message> <message> <source>Use US traditional units</source> <translation>Gebruik US traditional units</translation> </message> <message> <source>Use British imperial units</source> <translation>Gebruik British imperial units</translation> </message> <message> <source>Temperature</source> <translation>Temperatuur</translation> </message> <message> <source>Celsius</source> <translation>Celsius</translation> </message> <message> <source>Fahrenheit</source> <translation>Fahrenheit</translation> </message> <message> <source>Volume</source> <translation>Volume</translation> </message> <message> <source>Gravity</source> <translation>SG</translation> </message> <message> <source>20C/20C Specific Gravity</source> <translation>20°C/20°C SG</translation> </message> <message> <source>Plato/Brix/Balling</source> <translation>Plato/Brix/Balling</translation> </message> <message> <source>Color</source> <translation>Kleur</translation> </message> <message> <source>Use SRM</source> <translation>Gebruik SRM</translation> </message> <message> <source>Use EBC</source> <translation>Gebruik EBC</translation> </message> <message> <source>Formulas</source> <translation>Formules</translation> </message> <message> <source>Mosher&apos;s approximation</source> <translation>Mosher&apos;s approximation</translation> </message> <message> <source>Daniels&apos; approximation</source> <translation>Daniels&apos; approximation</translation> </message> <message> <source>Morey&apos;s approximation</source> <translation>Morey&apos;s approximation</translation> </message> <message> <source>IBU</source> <translation>IBU</translation> </message> <message> <source>Tinseth&apos;s approximation</source> <translation>Tinseth&apos;s approximation</translation> </message> <message> <source>Rager&apos;s approximation</source> <translation>Rager&apos;s approximation</translation> </message> <message> <source>IBU Adjustments</source> <translation type="unfinished"></translation> </message> <message> <source>% IBU adjustment</source> <translation type="unfinished"></translation> </message> <message> <source>Mash Hop</source> <translation type="unfinished"></translation> </message> <message> <source>First Wort</source> <translation>Eerste Wort</translation> </message> <message> <source>Directories</source> <translation>Directories</translation> </message> <message> <source>Database Directory</source> <translation>Directory van de database</translation> </message> <message> <source>Where your brewtarget .xml files are.</source> <translation type="unfinished"></translation> </message> <message> <source>Browse</source> <translation>Zoeken</translation> </message> <message> <source>Default</source> <translation>Standaard</translation> </message> <message> <source>Language</source> <translation>Taal</translation> </message> <message> <source>&lt;qt&gt; &lt;b&gt;Know another language?&lt;/b&gt; &lt;br&gt;&lt;br&gt; Or, would you like to improve a translation? Help us out and &lt;a href=&quot;https://sourceforge.net/sendmessage.php?touser=938941&quot;&gt; provide a translation&lt;/a&gt; so that your friends can use brewtarget! &lt;/qt&gt;</source> <translation>&lt;qt&gt; &lt;b&gt;Beheerst u een andere taal?&lt;/b&gt; &lt;br&gt;&lt;br&gt; Of, zou u een vertaling willen verbeteren? Help ons en &lt;a href=&quot;https://sourceforge.net/sendmessage.php?touser=938941&quot;&gt; lever een vertaling&lt;/a&gt; zo dat uw vrienden brewtarget kunnen gebruiken! &lt;/qt&gt;</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>mm-dd-YYYY</source> <translation type="unfinished"></translation> </message> <message> <source>dd-mm-YYYY</source> <translation type="unfinished"></translation> </message> <message> <source>YYYY-dd-mm</source> <translation type="unfinished"></translation> </message> <message> <source>Noonan&apos;s approximation</source> <translation type="unfinished"></translation> </message> </context> <context> <name>pitchDialog</name> <message> <source>Pitch Rate Calculator</source> <translation>Rekenhulp Gistgift</translation> </message> <message> <source>Input</source> <translation>Invoer</translation> </message> <message> <source>Wort Volume</source> <translation>Wort Volume</translation> </message> <message> <source>OG</source> <translation>Oorspronkelijkl SG</translation> </message> <message> <source>For ales, 0.75-1. For lagers, 1.5-2.</source> <translation>0.75-1 voor ales. 1.5-2 voor pils</translation> </message> <message> <source>Pitch Rate (M cells)/(mL*P)</source> <translation type="unfinished"></translation> </message> <message> <source>Aeration Method</source> <translation type="unfinished"></translation> </message> <message> <source>Yeast Production Date</source> <translation type="unfinished"></translation> </message> <message> <source>Yeast Viability</source> <translation type="unfinished"></translation> </message> <message> <source>None</source> <translation type="unfinished"></translation> </message> <message> <source>O2 At Start</source> <translation type="unfinished"></translation> </message> <message> <source>Stir Plate</source> <translation type="unfinished"></translation> </message> <message> <source>MM/dd/yyyy</source> <translation type="unfinished"></translation> </message> <message> <source>%</source> <translation type="unfinished"></translation> </message> <message> <source>TextLabel</source> <translation>TekstLabel</translation> </message> <message> <source>Calculate Viability From Date</source> <translation type="unfinished"></translation> </message> <message> <source># Vials/Smack Packs Pitched</source> <translation type="unfinished"></translation> </message> <message> <source>Output</source> <translation>Uitvoer</translation> </message> <message> <source>Billions of Yeast Cells Required</source> <translation>Miljoenen Benodigde Gist Cellen</translation> </message> <message> <source># Vials/Smack Packs w/o Starter</source> <translation type="unfinished"></translation> </message> <message> <source>Dry Yeast</source> <translation>Gedroogde Gist</translation> </message> <message> <source>Starter Volume</source> <translation>Starter Volume</translation> </message> <message> <source>Volume of wort</source> <translation type="unfinished"></translation> </message> <message> <source>Starting gravity of the wort</source> <translation type="unfinished"></translation> </message> <message> <source>Aeration method</source> <translation type="unfinished"></translation> </message> <message> <source>Production date (Best By date less three months)</source> <translation type="unfinished"></translation> </message> <message> <source>Estimated viability of the yeast</source> <translation type="unfinished"></translation> </message> <message> <source>Desired pitch rate</source> <translation type="unfinished"></translation> </message> <message> <source>Number of vials/smack packs added to starter</source> <translation type="unfinished"></translation> </message> <message> <source>How much yeast you will need</source> <translation type="unfinished"></translation> </message> <message> <source>How many smack packs or vials required to reach pitch rate</source> <translation type="unfinished"></translation> </message> <message> <source>Amount of dry yeast needed to reach pitch rate</source> <translation type="unfinished"></translation> </message> <message> <source>Starter size to reach pitch rate</source> <translation type="unfinished"></translation> </message> </context> <context> <name>primingDialog</name> <message> <source>Priming Calculator</source> <translation>Gistgift Rekenhulp</translation> </message> <message> <source>Input</source> <translation>Invoer</translation> </message> <message> <source>Collected Beer Volume</source> <translation>Verzamelde Bier Volume</translation> </message> <message> <source>Amount of beer to prime</source> <translation>Hoeveelheid bier om gist toe te voegen</translation> </message> <message> <source>Beer Temperature</source> <translation>Bier Temperatuur</translation> </message> <message> <source>Temp of the beer</source> <translation>Temp van het bier</translation> </message> <message> <source>Desired Volumes</source> <translation>Gewenste Volumes</translation> </message> <message> <source>How many volumes of CO2 you want (1 L CO2 @ STP per L beer)</source> <translation>Hoeveel volumes CO2 u wilt ((1 liter CO2 @ STP per liter bier)</translation> </message> <message> <source>Glucose Monohydrate (corn sugar)</source> <translation>Glucose Monohydrate (mais suiker)</translation> </message> <message> <source>Anhydrous Glucose</source> <translation>Watervrije Glucose</translation> </message> <message> <source>Sucrose (table sugar)</source> <translation>Sucrose (kristalsuiker)</translation> </message> <message> <source>Dry Malt Extract</source> <translation>Gedroogd Mout Extract</translation> </message> <message> <source>Output</source> <translation>Uitvoer</translation> </message> <message> <source>Prime with</source> <translation>Gistgift met</translation> </message> <message> <source>How much priming ingredient to use</source> <translation>Hoeveel gist ingrediënt te gebruiken</translation> </message> <message> <source>Calculate</source> <translation>Bereken</translation> </message> </context> <context> <name>recipeExtrasWidget</name> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Brewer</source> <translation>Brouwer</translation> </message> <message> <source>Asst. Brewer</source> <translation>Assistent Brouwer</translation> </message> <message> <source>Taste Rating</source> <translation>Smaak waardering</translation> </message> <message> <source>Primary Age (days)</source> <translation>Hoofdvergisting duur (dagen)</translation> </message> <message> <source>Primary Temp</source> <translation>Temp hoofdvergisting</translation> </message> <message> <source>Secondary Age (days)</source> <translation>Duur navergisting (dagen)</translation> </message> <message> <source>Secondary Temp</source> <translation>Temp navergisting</translation> </message> <message> <source>Tertiary Age (days)</source> <translation>Duur hergisting (dagen)</translation> </message> <message> <source>Tertiary Temp</source> <translation>Temp hergisting</translation> </message> <message> <source>Bottle/Keg Age (days)</source> <translation>Duur Fles/Vat (dagen)</translation> </message> <message> <source>Bottle/Keg Temp</source> <translation>Temp Fles/Vat (dagen)</translation> </message> <message> <source>Date First Brewed</source> <translation>Datum Eerste Brouwsel</translation> </message> <message> <source>dd MMM yyyy</source> <translation>dd MMM yyyy</translation> </message> <message> <source>Carbonation Volumes</source> <translation>Koolzuur Volumes</translation> </message> <message> <source>Taste Notes</source> <translation>Proef Aantekeningen</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> </context> <context> <name>refractoDialog</name> <message> <source>Refractometer Tools</source> <translation>Refractometer Gereedschap</translation> </message> <message> <source>Inputs</source> <translation>Invoer</translation> </message> <message> <source>Original Plato</source> <translation>Oorspronkelijke Plato</translation> </message> <message> <source>OG (20 C)</source> <translation>Oorspronkelijk SG (20 °C)</translation> </message> <message> <source>Current Plato</source> <translation>Huidige Plato</translation> </message> <message> <source>Calculate</source> <translation>Bereken</translation> </message> <message> <source>Outputs</source> <translation>Uitvoer</translation> </message> <message> <source>SG (20C)</source> <translation>SG (20°C)</translation> </message> <message> <source>ABV</source> <translation>Alc (vol%)</translation> </message> <message> <source>ABW</source> <translation>Alc (gew%)</translation> </message> <message> <source>Refractive Index</source> <translation>Refractieve index</translation> </message> <message> <source>Real Extract (Plato)</source> <translation>Werkelijk Extract (Plato)</translation> </message> <message> <source>OG (20C)</source> <translation>Oorspronkelijk SG (20 °C)</translation> </message> <message> <source>Measured original plato</source> <translation type="unfinished"></translation> </message> <message> <source>Measured original gravity</source> <translation type="unfinished"></translation> </message> <message> <source>Current measured plato</source> <translation type="unfinished"></translation> </message> </context> <context> <name>strikeWaterDialog</name> <message> <source>Strike Water Calculator</source> <translation type="unfinished"></translation> </message> <message> <source>Initial Infusion</source> <translation type="unfinished"></translation> </message> <message> <source>Original Grain Temperature</source> <translation type="unfinished"></translation> </message> <message> <source>Target Mash Temperature</source> <translation type="unfinished"></translation> </message> <message> <source>Weight of Grain</source> <translation type="unfinished"></translation> </message> <message> <source>Volume of Water</source> <translation type="unfinished"></translation> </message> <message> <source>Mash Infusion</source> <translation type="unfinished"></translation> </message> <message> <source>Total Volume of Water</source> <translation type="unfinished"></translation> </message> <message> <source>Grain Weight</source> <translation type="unfinished"></translation> </message> <message> <source>Actual Mash Temperature</source> <translation type="unfinished"></translation> </message> <message> <source>Infusion Water Temperature</source> <translation type="unfinished"></translation> </message> <message> <source>Calculate</source> <translation>Bereken</translation> </message> <message> <source>Strike Water Temperature</source> <translation type="unfinished"></translation> </message> <message> <source>Volume to add</source> <translation type="unfinished"></translation> </message> <message> <source>Note: This calculator assumes a preheated mash tun.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>styleEditor</name> <message> <source>Style Editor</source> <translation>Stijl Editor</translation> </message> <message> <source>Style</source> <translation>Stijl</translation> </message> <message> <source>Delete selected style</source> <translation>Verwijder geselecteerde stijl</translation> </message> <message> <source>Basic Information</source> <translation type="unfinished"></translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Category</source> <translation>Categorie</translation> </message> <message> <source>Category number</source> <translation>Categorie nummer</translation> </message> <message> <source>Style letter</source> <translation>Stijl letter</translation> </message> <message> <source>Style guide</source> <translation>Stijl gids</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Type of beverage</source> <translation>Type drank</translation> </message> <message> <source>Lager</source> <translation>Pils</translation> </message> <message> <source>Ale</source> <translation>Ale</translation> </message> <message> <source>Mead</source> <translation>Mede</translation> </message> <message> <source>Wheat</source> <translation>Tarwe</translation> </message> <message> <source>Mixed</source> <translation>Gemengd</translation> </message> <message> <source>Cider</source> <translation>Cider</translation> </message> <message> <source>Vital Statistics</source> <translation type="unfinished"></translation> </message> <message> <source>Max</source> <translation type="unfinished"></translation> </message> <message> <source>Min</source> <translation type="unfinished"></translation> </message> <message> <source>OG</source> <translation>Oorspronkelijk SG</translation> </message> <message> <source>FG</source> <translation>eind SG</translation> </message> <message> <source>IBUs</source> <translation type="unfinished"></translation> </message> <message> <source>Color (SRM)</source> <translation>Kleur (SRM)</translation> </message> <message> <source>Carb (vols)</source> <translation type="unfinished"></translation> </message> <message> <source>ABV (pct)</source> <translation type="unfinished"></translation> </message> <message> <source>Profile</source> <translation>Profiel</translation> </message> <message> <source>Ingredients</source> <translation>Ingrediënten</translation> </message> <message> <source>Examples</source> <translation>Voorbeelden</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> <message> <source>New</source> <translation>Nieuw</translation> </message> <message> <source>Save</source> <translation>Opslaan</translation> </message> <message> <source>Cancel</source> <translation>Annuleren</translation> </message> </context> <context> <name>timerListDialog</name> <message> <source>Timers</source> <translation>Timers</translation> </message> </context> <context> <name>waterEditor</name> <message> <source>Dialog</source> <translation>Dialoog</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Notes</source> <translation>Aantekeningen</translation> </message> </context> <context> <name>yeastEditor</name> <message> <source>Yeast Editor</source> <translation>Gist Editor</translation> </message> <message> <source>Required Fields</source> <translation>Vereiste Velden</translation> </message> <message> <source>Name</source> <translation>Naam</translation> </message> <message> <source>Type</source> <translation>Type</translation> </message> <message> <source>Ale</source> <translation>Ale</translation> </message> <message> <source>Lager</source> <translation>Pils</translation> </message> <message> <source>Wheat</source> <translation>Tarwe</translation> </message> <message> <source>Wine</source> <translation>Wijn</translation> </message> <message> <source>Champagne</source> <translation>Champagne</translation> </message> <message> <source>Form</source> <translation>Vorm</translation> </message> <message> <source>Liquid</source> <translation>Vloeistof</translation> </message> <message> <source>Dry</source> <translation>Gedroogd</translation> </message> <message> <source>Slant</source> <translation>Opgekweekt</translation> </message> <message> <source>Culture</source> <translation>Cultuur</translation> </message> <message> <source>Amount</source> <translation>Hoeveelheid</translation> </message> <message> <source>Check it if the amount given is in kg instead of L.</source> <translation>Controleer of de opgegeven hoeveelheid in kg is i.p.v.in L.</translation> </message> <message> <source>Amount is weight?</source> <translation>Hoeveelheid is gewicht?</translation> </message> <message> <source>Checked if the given amount is weight instead of volume</source> <translation>Controleer of de opgegeven hoeveelheid een gewicht is i.p.v. een volume</translation> </message> <message> <source>Lab</source> <translation>Lab</translation> </message> <message> <source>Product ID</source> <translation>Product ID</translation> </message> <message> <source>Min Temp</source> <translation>Min Temp</translation> </message> <message> <source>Min temp</source> <translation>Min temp</translation> </message> <message> <source>Max Temp</source> <translation>Max Temp</translation> </message> <message> <source>Max temp</source> <translation>Max temp</translation> </message> <message> <source>Flocculation</source> <translation>Flocculatie</translation> </message> <message> <source>Low</source> <translation>Laag</translation> </message> <message> <source>Medium</source> <translation>Gemiddeld</translation> </message> <message> <source>High</source> <translation>Hoog</translation> </message> <message> <source>Very High</source> <translation>Erg Hoog</translation> </message> <message> <source>Attenuation (%)</source> <translation>Vergisting (%)</translation> </message> <message> <source>Apparent attenuation as percentage of OG points</source> <translation>Schijnbare Vergisting als percentage van het oorspronkelijke SG</translation> </message> <message> <source>Times Recultured</source> <translation>Aantal keren opgekweekt</translation> </message> <message> <source>Times this yeast has been recultured</source> <translation>Aantal keren dat deze gist is opgekweekt</translation> </message> <message> <source>Max Recultures</source> <translation>Max keren opkweken</translation> </message> <message> <source>Max recultures</source> <translation>Max keren opkweken</translation> </message> <message> <source>Add to Secondary</source> <translation>Voeg toe aan navergisting</translation> </message> <message> <source>Checked means add this yeast to secondary instead of primary</source> <translation>Aangevinkt betekent: voeg gist toe aan navergisting i.p.v. hoofdvergisting</translation> </message> <message> <source>Best For:</source> <translation>Houdbaar tot:</translation> </message> <message> <source>Notes:</source> <translation>Aantekeningen:</translation> </message> <message> <source>Default Amount</source> <translation type="unfinished"></translation> </message> <message> <source>Quanta in Inventory</source> <translation type="unfinished"></translation> </message> <message> <source>Quanta in inventory</source> <translation type="unfinished"></translation> </message> </context> </TS>
danielm5/brewtarget
translations/bt_nl.ts
TypeScript
gpl-3.0
155,311