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
Bitrix 16.5 Business Demo = ea7587a817bea036305172b8333d43ef
gohdan/DFC
known_files/hashes/bitrix/modules/main/lang/ru/admin/short_uri_edit.php
PHP
gpl-3.0
61
from math import ceil import numpy as np from ipywidgets import widgets from tqdm.notebook import tqdm from matplotlib import pyplot as plt import lib.iq_mixer_calibration from drivers import IQAWG from lib.data_management import load_IQMX_calibration_database, \ save_IQMX_calibration from lib.iq_mixer_calibration import IQCalibrator class IQVectorGenerator: def __init__(self, name, lo, iq_awg: IQAWG, sa, calibration_db_name="IQVG", default_calibration_power=-30, marker_period_divisor=None, slave_iqvgs=None, calibration_step=10e6): """ Parameters ---------- lo iq_awg sa calibration_db_name default_calibration_power marker_period_divisor: int, ns by default, the marker period should be divisible by the if_period however, in some cases other divisor may be required, i.e. when m3202 is used with PXICLK10 trigger sync mode this divisor should be set to 100 """ self._name = name self._lo = lo self._iqawg = iq_awg self._sa = sa self._cal_db_name = calibration_db_name self._default_calibration_power = default_calibration_power self._calibration_widget = widgets.HTML() self._recalibrate_mixer = False self._frequency = 5e9 self.set_if_frequency(100e6) if marker_period_divisor is not None: self._marker_period_divisor = marker_period_divisor else: self._marker_period_divisor = self._if_period # for marker period synchronization when iqvgs are on the same AWG self._slave_iqvgs = slave_iqvgs if slave_iqvgs is not None else [] self._power = default_calibration_power self._dac_overridden = False self._current_cal = None self._requested_cal: lib.iq_mixer_calibration.IQCalibrationData = None self._cal_db = None self._marker_period = None self._requested_marker_period = None self.set_marker_period(1000) self._calibration_initial_guess = {"dc_offsets": np.random.uniform(.03, 0.1, size=2), "if_amplitudes": (.1, .1), "if_phase": -np.pi * 0.54} self._calibration_step = calibration_step self._calibration_test_data = [] self._load_cal_db() def get_calibration_widget(self): return self._calibration_widget def set_parameters(self, parameters_dict): if "power" in parameters_dict: self.set_power(parameters_dict["power"]) if "freq" in parameters_dict: self.set_frequency(parameters_dict["freq"]) if "dac_overridden" in parameters_dict: self._dac_overridden = parameters_dict["dac_overridden"] else: self._dac_overridden = False def get_iqawg(self): self._iqawg.set_parameters( {'calibration': self._current_cal}) # ensure return self._iqawg def set_if_frequency(self, if_frequency): self._if_frequency = if_frequency self._if_period = 1 / if_frequency * 1e9 # ns def get_if_frequency(self): return self._if_frequency def set_output_state(self, state): self._lo.set_output_state(state) def set_frequency(self, freq): self._frequency = freq self._lo.set_frequency(self._frequency + self._if_frequency) self._requested_cal = self.get_calibration(self._frequency, self._power) self._output_SSB() def set_power(self, power): if power > self._default_calibration_power + 10: raise ValueError("Power can be % dBm max, requested %d dBm" % ( self._default_calibration_power + 10, power)) self._power = power self._requested_cal = self.get_calibration(self._frequency, self._power) self._lo.set_power(self._requested_cal.get_lo_power()) self._output_SSB() def get_power(self): return self._power def set_marker_period(self, marker_period): ''' For some applications there is need to control the length of the interval between triggers output by the AWG of the IQVectorGenerator. Parameters ---------- marker_period: ns, float real trigger period will be recalculated to be not shorter than <marker_period> ns, but still divisible by the IF period ''' self._requested_marker_period = marker_period correct_marker_period = ceil( marker_period / self._marker_period_divisor) * \ self._marker_period_divisor if correct_marker_period != self._marker_period: self._marker_period = correct_marker_period if self._requested_cal is not None: self._current_cal = None self._output_SSB() for slave_iqvg in self._slave_iqvgs: slave_iqvg.set_marker_period(self._marker_period) def _output_SSB(self): if self._requested_cal != self._current_cal: # print(f"IQVG {self._name}: outputting pulse sequence to update calibration for frequency: {self._frequency/1e9:.4f} GHz" # f", power: {self._power} dBm.") self._iqawg.set_parameters({"calibration": self._requested_cal}) pb = self._iqawg.get_pulse_builder() if_freq = self._requested_cal.get_radiation_parameters()[ "if_frequency"] resolution = self._requested_cal.get_radiation_parameters()[ "waveform_resolution"] if_period = 1 / if_freq * 1e9 if (if_period * 1e9) % resolution != 0: print( f"IQVectorGenerator {self._name} warning: IF period is not divisible by " "calibration waveform resolution. Phase coherence will be bad.") seq = pb.add_sine_pulse(self._marker_period).build() self._iqawg.output_pulse_sequence(seq) self._current_cal = self._requested_cal # time.sleep(1) def _load_cal_db(self): self._cal_db = load_IQMX_calibration_database(self._cal_db_name, 0) def _around_frequency(self, frequency): # return ceil(frequency/self._calibration_step)*self._calibration_step return round(frequency / self._calibration_step) * self._calibration_step def get_calibration(self, frequency, power): frequency = self._around_frequency(frequency) # frequency = round(frequency/self._calibration_step)*self._calibration_step if self._cal_db is None: self._load_cal_db() cal = \ self._cal_db.get(frozenset(dict(lo_power=14, ssb_power=self._default_calibration_power, lo_frequency=self._if_frequency + frequency, if_frequency=self._if_frequency, waveform_resolution=1, sideband_to_maintain='left').items())) if (cal is None) or self._recalibrate_mixer: calibrator = IQCalibrator(self._iqawg, self._sa, self._lo, self._cal_db_name, 0, sidebands_to_suppress=6, output_widget=self._calibration_widget) ig = self._calibration_initial_guess cal = calibrator.calibrate( lo_frequency=frequency + self._if_frequency, if_frequency=self._if_frequency, lo_power=14, ssb_power=self._default_calibration_power, waveform_resolution=1, iterations=3, minimize_iterlimit=100, sa_res_bandwidth=300, initial_guess=ig) save_IQMX_calibration(cal) self._load_cal_db() # make sure to include new calibration into cache cal._ssb_power = power cal._if_amplitudes = cal._if_amplitudes / np.sqrt( 10 ** ((self._default_calibration_power - power) / 10)) # self._calibration_initial_guess["if_amplitudes"] = cal._if_amplitudes self._calibration_initial_guess["if_phase"] = cal._if_phase return cal else: cal = cal.copy() cal._if_amplitudes = cal._if_amplitudes / np.sqrt( 10 ** ((self._default_calibration_power - power) / 10)) return cal def calibrate_mixer(self, fstart, fstop, recalibrate=False): """ Performs calibration of the mixer in a frequency range Parameters ---------- fstart: float start of the frequency range fstop : float stop of the frequency range recalibrate : bool Whether or not to calibrate from scratch and override previous calibration in this interval. """ fstart = self._around_frequency(fstart) fstop = self._around_frequency(fstop) self._recalibrate_mixer = recalibrate pb = tqdm(np.arange(fstart, fstop + self._calibration_step, self._calibration_step), smoothing=0) for frequency in pb: pb.set_description("%.3f GHz" % (frequency / 1e9)) for counter in range(3): try: self.set_frequency(frequency) break except ValueError: print("Poor calibration at %.3f GHz, retry count " "%d" % (frequency / 1e9, counter)) self._calibration_initial_guess["dc_offest"] = \ np.random.uniform(.03, 0.1, size=2) self._recalibrate_mixer = False def test_calibration(self, fstart, fstop, step=1e6, sidebands_to_plot=[-1, 0, 1], remeasure=False): """ Tests the saved calibrations by monitoring all the sidebands throughout the specified frequency range Parameters ---------- fstart: float, Hz start of the frequency range fstop: float, Hz stop of the frequency range step: float, Hz step of the scan remeasure : bool remeasure or just replot the data from the previous run """ sideband_shifts = np.linspace(-3, 3, 7) * self._if_frequency freqs = np.arange(fstart, fstop + step, step) if remeasure or len(self._calibration_test_data) == 0: self._calibration_test_data = [] for frequency in tqdm(freqs, smoothing=0): self.set_frequency(frequency) sa_freqs = sideband_shifts + self._frequency self._sa.setup_list_sweep(list(sa_freqs), [1000] * 3) self._sa.prepare_for_stb() self._sa.sweep_single() self._sa.wait_for_stb() self._calibration_test_data.append(self._sa.get_tracedata()) self._calibration_test_data = np.array( self._calibration_test_data).T sidebands_to_plot_idcs = np.array(sidebands_to_plot, dtype=int) + 3 sideband_shifts = sideband_shifts[sidebands_to_plot_idcs] data = self._calibration_test_data[sidebands_to_plot_idcs] for row, sideband_shift in zip(data, sideband_shifts): plt.plot(freqs, row, label=f"{(sideband_shift / 1e6):.2f} MHz") plt.legend() self._sa.setup_swept_sa(-self._if_frequency + self._frequency, 10 * self._if_frequency, nop=1001, rbw=1e4) self._sa.set_continuous()
vdrhtc/Measurement-automation
drivers/IQVectorGenerator.py
Python
gpl-3.0
12,060
/* Copyright 2012-2016 Michael Pozhidaev <michael.pozhidaev@gmail.com> This file is part of LUWRAIN. LUWRAIN 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. LUWRAIN is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package org.luwrain.core; import java.util.*; class ShortcutManager { class Entry { String name = ""; Shortcut shortcut; Entry(String name, Shortcut shortcut) { NullCheck.notNull(name, "name"); NullCheck.notNull(shortcut, "shortcut"); if (name.trim().isEmpty()) throw new IllegalArgumentException("name may not be empty"); this.name = name; this.shortcut = shortcut; } } private final TreeMap<String, Entry> shortcuts = new TreeMap<String, Entry>(); boolean add(Shortcut shortcut) { NullCheck.notNull(shortcut, "shortcut"); final String name = shortcut.getName(); if (name == null || name.trim().isEmpty()) return false; if (shortcuts.containsKey(name)) return false; shortcuts.put(name, new Entry(name, shortcut)); return true; } Application[] prepareApp(String name, String[] args) { NullCheck.notNull(name, "name"); NullCheck.notNullItems(args, "args"); if (name.trim().isEmpty()) throw new IllegalArgumentException("name may not be empty"); if (!shortcuts.containsKey(name)) return null; return shortcuts.get(name).shortcut.prepareApp(args); } String[] getShortcutNames() { final Vector<String> res = new Vector<String>(); for(Map.Entry<String, Entry> e: shortcuts.entrySet()) res.add(e.getKey()); String[] str = res.toArray(new String[res.size()]); Arrays.sort(str); return str; } void addBasicShortcuts() { add(new Shortcut(){ @Override public String getName() { return "registry"; } @Override public Application[] prepareApp(String[] args) { Application[] res = new Application[1]; res[0] = new org.luwrain.app.registry.RegistryApp(); return res; } }); } void addOsShortcuts(Luwrain luwrain, Registry registry) { NullCheck.notNull(luwrain, "luwrain"); NullCheck.notNull(registry, "registry"); registry.addDirectory(Settings.OS_SHORTCUTS_PATH); for(String s: registry.getDirectories(Settings.OS_SHORTCUTS_PATH)) { if (s.trim().isEmpty()) continue; final OsCommands.OsShortcut shortcut = new OsCommands.OsShortcut(luwrain); if (shortcut.init(Settings.createOsShortcut(registry, Registry.join(Settings.OS_SHORTCUTS_PATH, s)))) add(shortcut); } } }
rPman/luwrain
src/main/java/org/luwrain/core/ShortcutManager.java
Java
gpl-3.0
2,884
#include "tool_move.hpp" #include "document/idocument_board.hpp" #include "board/board.hpp" #include "document/idocument_package.hpp" #include "pool/package.hpp" #include "document/idocument_padstack.hpp" #include "pool/padstack.hpp" #include "document/idocument_schematic.hpp" #include "schematic/schematic.hpp" #include "document/idocument_symbol.hpp" #include "pool/symbol.hpp" #include "imp/imp_interface.hpp" #include "util/accumulator.hpp" #include "util/util.hpp" #include <iostream> #include "core/tool_id.hpp" namespace horizon { ToolMove::ToolMove(IDocument *c, ToolID tid) : ToolBase(c, tid), ToolHelperMove(c, tid), ToolHelperMerge(c, tid) { } void ToolMove::expand_selection() { std::set<SelectableRef> pkgs_fixed; std::set<SelectableRef> new_sel; for (const auto &it : selection) { switch (it.type) { case ObjectType::LINE: { Line *line = doc.r->get_line(it.uuid); new_sel.emplace(line->from.uuid, ObjectType::JUNCTION); new_sel.emplace(line->to.uuid, ObjectType::JUNCTION); } break; case ObjectType::POLYGON_EDGE: { Polygon *poly = doc.r->get_polygon(it.uuid); auto vs = poly->get_vertices_for_edge(it.vertex); new_sel.emplace(poly->uuid, ObjectType::POLYGON_VERTEX, vs.first); new_sel.emplace(poly->uuid, ObjectType::POLYGON_VERTEX, vs.second); } break; case ObjectType::NET_LABEL: { auto &la = doc.c->get_sheet()->net_labels.at(it.uuid); new_sel.emplace(la.junction->uuid, ObjectType::JUNCTION); } break; case ObjectType::BUS_LABEL: { auto &la = doc.c->get_sheet()->bus_labels.at(it.uuid); new_sel.emplace(la.junction->uuid, ObjectType::JUNCTION); } break; case ObjectType::POWER_SYMBOL: { auto &ps = doc.c->get_sheet()->power_symbols.at(it.uuid); new_sel.emplace(ps.junction->uuid, ObjectType::JUNCTION); } break; case ObjectType::BUS_RIPPER: { auto &rip = doc.c->get_sheet()->bus_rippers.at(it.uuid); new_sel.emplace(rip.junction->uuid, ObjectType::JUNCTION); } break; case ObjectType::LINE_NET: { auto line = &doc.c->get_sheet()->net_lines.at(it.uuid); for (auto &it_ft : {line->from, line->to}) { if (it_ft.is_junc()) { new_sel.emplace(it_ft.junc.uuid, ObjectType::JUNCTION); } } } break; case ObjectType::TRACK: { auto track = &doc.b->get_board()->tracks.at(it.uuid); for (auto &it_ft : {track->from, track->to}) { if (it_ft.is_junc()) { new_sel.emplace(it_ft.junc.uuid, ObjectType::JUNCTION); } } } break; case ObjectType::VIA: { auto via = &doc.b->get_board()->vias.at(it.uuid); new_sel.emplace(via->junction->uuid, ObjectType::JUNCTION); } break; case ObjectType::POLYGON: { auto poly = doc.r->get_polygon(it.uuid); int i = 0; for (const auto &itv : poly->vertices) { (void)sizeof itv; new_sel.emplace(poly->uuid, ObjectType::POLYGON_VERTEX, i); i++; } } break; case ObjectType::ARC: { Arc *arc = doc.r->get_arc(it.uuid); new_sel.emplace(arc->from.uuid, ObjectType::JUNCTION); new_sel.emplace(arc->to.uuid, ObjectType::JUNCTION); new_sel.emplace(arc->center.uuid, ObjectType::JUNCTION); } break; case ObjectType::SCHEMATIC_SYMBOL: { auto sym = doc.c->get_schematic_symbol(it.uuid); for (const auto &itt : sym->texts) { new_sel.emplace(itt->uuid, ObjectType::TEXT); } } break; case ObjectType::BOARD_PACKAGE: { BoardPackage *pkg = &doc.b->get_board()->packages.at(it.uuid); if (pkg->fixed) { pkgs_fixed.insert(it); } else { for (const auto &itt : pkg->texts) { new_sel.emplace(itt->uuid, ObjectType::TEXT); } } } break; default:; } } selection.insert(new_sel.begin(), new_sel.end()); if (pkgs_fixed.size() && imp) imp->tool_bar_flash("can't move fixed package"); for (auto it = selection.begin(); it != selection.end();) { if (pkgs_fixed.count(*it)) it = selection.erase(it); else ++it; } } Coordi ToolMove::get_selection_center() { Accumulator<Coordi> accu; std::set<SelectableRef> items_ignore; for (const auto &it : selection) { if (it.type == ObjectType::BOARD_PACKAGE) { const auto &pkg = doc.b->get_board()->packages.at(it.uuid); for (auto &it_txt : pkg.texts) { items_ignore.emplace(it_txt->uuid, ObjectType::TEXT); } } else if (it.type == ObjectType::SCHEMATIC_SYMBOL) { const auto &sym = doc.c->get_sheet()->symbols.at(it.uuid); for (auto &it_txt : sym.texts) { items_ignore.emplace(it_txt->uuid, ObjectType::TEXT); } } } for (const auto &it : selection) { if (items_ignore.count(it)) continue; switch (it.type) { case ObjectType::JUNCTION: accu.accumulate(doc.r->get_junction(it.uuid)->position); break; case ObjectType::HOLE: accu.accumulate(doc.r->get_hole(it.uuid)->placement.shift); break; case ObjectType::BOARD_HOLE: accu.accumulate(doc.b->get_board()->holes.at(it.uuid).placement.shift); break; case ObjectType::SYMBOL_PIN: accu.accumulate(doc.y->get_symbol_pin(it.uuid).position); break; case ObjectType::SCHEMATIC_SYMBOL: accu.accumulate(doc.c->get_schematic_symbol(it.uuid)->placement.shift); break; case ObjectType::BOARD_PACKAGE: accu.accumulate(doc.b->get_board()->packages.at(it.uuid).placement.shift); break; case ObjectType::PAD: accu.accumulate(doc.k->get_package().pads.at(it.uuid).placement.shift); break; case ObjectType::TEXT: accu.accumulate(doc.r->get_text(it.uuid)->placement.shift); break; case ObjectType::POLYGON_VERTEX: accu.accumulate(doc.r->get_polygon(it.uuid)->vertices.at(it.vertex).position); break; case ObjectType::DIMENSION: if (it.vertex < 2) { auto dim = doc.r->get_dimension(it.uuid); accu.accumulate(it.vertex == 0 ? dim->p0 : dim->p1); } break; case ObjectType::POLYGON_ARC_CENTER: accu.accumulate(doc.r->get_polygon(it.uuid)->vertices.at(it.vertex).arc_center); break; case ObjectType::SHAPE: accu.accumulate(doc.a->get_padstack().shapes.at(it.uuid).placement.shift); break; case ObjectType::BOARD_PANEL: accu.accumulate(doc.b->get_board()->board_panels.at(it.uuid).placement.shift); break; case ObjectType::PICTURE: accu.accumulate(doc.r->get_picture(it.uuid)->placement.shift); break; case ObjectType::BOARD_DECAL: accu.accumulate(doc.b->get_board()->decals.at(it.uuid).placement.shift); break; default:; } } if (doc.c || doc.y) return (accu.get() / 1.25_mm) * 1.25_mm; else return accu.get(); } ToolResponse ToolMove::begin(const ToolArgs &args) { std::cout << "tool move\n"; move_init(args.coords); Coordi selection_center; if (tool_id == ToolID::ROTATE_CURSOR || tool_id == ToolID::MIRROR_CURSOR) selection_center = args.coords; else selection_center = get_selection_center(); collect_nets(); if (tool_id == ToolID::ROTATE || tool_id == ToolID::MIRROR_X || tool_id == ToolID::MIRROR_Y || tool_id == ToolID::ROTATE_CURSOR || tool_id == ToolID::MIRROR_CURSOR) { move_mirror_or_rotate(selection_center, tool_id == ToolID::ROTATE || tool_id == ToolID::ROTATE_CURSOR); if (tool_id == ToolID::MIRROR_Y) { move_mirror_or_rotate(selection_center, true); move_mirror_or_rotate(selection_center, true); } finish(); return ToolResponse::commit(); } if (tool_id == ToolID::MOVE_EXACTLY) { if (auto r = imp->dialogs.ask_datum_coord("Move exactly")) { move_do(*r); finish(); return ToolResponse::commit(); } else { return ToolResponse::end(); } } imp->tool_bar_set_actions({ {InToolActionID::LMB}, {InToolActionID::RMB}, {InToolActionID::ROTATE, InToolActionID::MIRROR, "rotate/mirror"}, {InToolActionID::ROTATE_CURSOR, InToolActionID::MIRROR_CURSOR, "rotate/mirror around cursor"}, {InToolActionID::RESTRICT}, }); update_tip(); for (const auto &it : selection) { if (it.type == ObjectType::POLYGON_VERTEX || it.type == ObjectType::POLYGON_EDGE) { auto poly = doc.r->get_polygon(it.uuid); if (auto plane = dynamic_cast<Plane *>(poly->usage.ptr)) { planes.insert(plane); } } } for (auto plane : planes) { plane->fragments.clear(); plane->revision++; } InToolActionID action = InToolActionID::NONE; switch (tool_id) { case ToolID::MOVE_KEY_FINE_UP: action = InToolActionID::MOVE_UP_FINE; break; case ToolID::MOVE_KEY_UP: action = InToolActionID::MOVE_UP; break; case ToolID::MOVE_KEY_FINE_DOWN: action = InToolActionID::MOVE_DOWN_FINE; break; case ToolID::MOVE_KEY_DOWN: action = InToolActionID::MOVE_DOWN; break; case ToolID::MOVE_KEY_FINE_LEFT: action = InToolActionID::MOVE_LEFT_FINE; break; case ToolID::MOVE_KEY_LEFT: action = InToolActionID::MOVE_LEFT; break; case ToolID::MOVE_KEY_FINE_RIGHT: action = InToolActionID::MOVE_RIGHT_FINE; break; case ToolID::MOVE_KEY_RIGHT: action = InToolActionID::MOVE_RIGHT; break; default:; } if (action != InToolActionID::NONE) { is_key = true; ToolArgs args2; args2.type = ToolEventType::ACTION; args2.action = action; update(args2); } if (tool_id == ToolID::MOVE_KEY) is_key = true; imp->tool_bar_set_tool_name("Move"); return ToolResponse(); } void ToolMove::collect_nets() { for (const auto &it : selection) { switch (it.type) { case ObjectType::BOARD_PACKAGE: { BoardPackage *pkg = &doc.b->get_board()->packages.at(it.uuid); for (const auto &itt : pkg->package.pads) { if (itt.second.net) nets.insert(itt.second.net->uuid); } } break; case ObjectType::JUNCTION: { auto ju = doc.r->get_junction(it.uuid); if (ju->net) nets.insert(ju->net->uuid); } break; default:; } } } bool ToolMove::can_begin() { expand_selection(); return selection.size() > 0; } void ToolMove::update_tip() { auto delta = get_delta(); std::string s = coord_to_string(delta + key_delta, true) + " "; if (!is_key) { s += restrict_mode_to_string(); } imp->tool_bar_set_tip(s); } void ToolMove::do_move(const Coordi &d) { move_do_cursor(d); if (doc.b && update_airwires && nets.size()) { doc.b->get_board()->update_airwires(true, nets); } update_tip(); } void ToolMove::finish() { for (const auto &it : selection) { if (it.type == ObjectType::SCHEMATIC_SYMBOL) { auto sym = doc.c->get_schematic_symbol(it.uuid); doc.c->get_schematic()->autoconnect_symbol(doc.c->get_sheet(), sym); if (sym->component->connections.size() == 0) { doc.c->get_schematic()->place_bipole_on_line(doc.c->get_sheet(), sym); } } } if (doc.c) { merge_selected_junctions(); } if (doc.b) { auto brd = doc.b->get_board(); brd->expand_flags = static_cast<Board::ExpandFlags>(Board::EXPAND_AIRWIRES); brd->airwires_expand = nets; for (auto plane : planes) { brd->update_plane(plane); } } } ToolResponse ToolMove::update(const ToolArgs &args) { if (args.type == ToolEventType::MOVE) { if (!is_key) do_move(args.coords); return ToolResponse(); } else if (args.type == ToolEventType::ACTION) { if (any_of(args.action, {InToolActionID::LMB, InToolActionID::COMMIT}) || (is_transient && args.action == InToolActionID::LMB_RELEASE)) { finish(); return ToolResponse::commit(); } else if (any_of(args.action, {InToolActionID::RMB, InToolActionID::CANCEL})) { return ToolResponse::revert(); } else if (args.action == InToolActionID::RESTRICT) { cycle_restrict_mode(); do_move(args.coords); } else if (any_of(args.action, {InToolActionID::ROTATE, InToolActionID::MIRROR})) { bool rotate = args.action == InToolActionID::ROTATE; const auto selection_center = get_selection_center(); move_mirror_or_rotate(selection_center, rotate); } else if (any_of(args.action, {InToolActionID::ROTATE_CURSOR, InToolActionID::MIRROR_CURSOR})) { bool rotate = args.action == InToolActionID::ROTATE_CURSOR; move_mirror_or_rotate(args.coords, rotate); } else { const auto [dir, fine] = dir_from_action(args.action); if (dir.x || dir.y) { auto sp = imp->get_grid_spacing(); if (fine) sp = sp / 10; key_delta += dir * sp; move_do(dir * sp); update_tip(); } } } return ToolResponse(); } } // namespace horizon
carrotIndustries/horizon
src/core/tools/tool_move.cpp
C++
gpl-3.0
14,465
#include <cstdlib> // srand() #include <ctime> // time() #include "StateManager.hpp" #include "SDL.hpp" #include "Log.hpp" #include "Config.hpp" #include "GameStateMainMenu.hpp" #include "GameStateGame.hpp" #include "GameStateGameOver.hpp" #include "Window.hpp" #include "Graphics.hpp" StateManager::StateManager(int width, int height) { SDL::init(30); Window::init(width, height, "Prototype", "yes"); Graphics::init(Window::screen); Config::load("config.ini"); if (Config::debugMode) Log::debugMode(true); // Here we start the game! this->currentState = new GameStateMainMenu(); this->currentState->load(); this->sharedInfo = 0; srand(time(NULL)); } StateManager::~StateManager() { SDL::exit(); if (this->currentState) { this->currentState->unload(); delete this->currentState; } } void StateManager::run() { bool letsQuit = false; while (!letsQuit) { // The delta time from the last frame uint32_t delta = SDL::getDelta(); // Normally i'd refresh input right here, but // each state must do it individually int whatToDoNow = this->currentState->update(delta); switch (whatToDoNow) { case GameState::CONTINUE: break; case GameState::QUIT: letsQuit = true; break; case GameState::GAME_START: this->sharedInfo = this->currentState->unload(); delete (this->currentState); this->currentState = new GameStateGame(); this->currentState->load(this->sharedInfo); break; case GameState::GAME_OVER: this->sharedInfo = this->currentState->unload(); delete (this->currentState); this->currentState = new GameStateGameOver(); this->currentState->load(this->sharedInfo); break; default: break; } Window::clear(); this->currentState->render(); Window::refresh(); // Let's wait a bit if the framerate is too low. SDL::framerateWait(); } }
alexdantas/idj
src/StateManager.cpp
C++
gpl-3.0
2,154
ace.require("ace/ext/language_tools"); var editor = ace.edit("editor"); editor.setOptions({ enableBasicAutocompletion: true }); editor.setTheme("ace/theme/eclipse"); editor.getSession().setMode("ace/mode/java"); document.getElementById('editor').style.fontSize = '18px'; editor.setAutoScrollEditorIntoView(true); var codeTemplates = {}; var viewConfig = { showOutput: false, showInput: false }; var prevLang; function showOutput(output) { var stdout = ''; var stderr = ''; if (output.status === 0) { stdout = output.output; } else if (output.status === 1) { stderr = '<p class="error">Compiler error !</p>'; stderr += output.error; } else if (output.status === 2) { stderr = '<p class="error">Runtime error !</p>'; stderr += output.error; } else if (output.status === 3) { stderr = '<p class="error">Timeout !</p>'; stderr += output.error; } var out = ''; if (stderr) { out += '<b>Stderror</b>\n' + stderr; } if (stdout) { out += stdout; } if (!viewConfig.showOutput) { $('#btn-show-output').click(); } $('#output-p').html(out); // $('#output-data').show(); // if (!$('#bottom-pane').hasClass('opened')) { // $('#bottom-pane').addClass('opened'); // } windowResized(); } function loadLangs() { $('#btn-run').prop('disabled', true); $.ajax({ type: "GET", url: '/apis/langs' }).done(function (data) { showLangs(data); $('#btn-run').prop('disabled', false); }).fail(function (data) { alert("error"); $('#btn-run').prop('disabled', false); }); } function showLangs(langs) { for (var i = 0; i < langs.supportedLangs.length; i++) { var supportedLang = langs.supportedLangs[i]; $('#lang').append($('<option>', { value: supportedLang.id, text: supportedLang.name })); codeTemplates[supportedLang.id] = supportedLang.template; } $('#lang').val(langs.supportedLangs[0].id); onLangChanged(); } $(document).ready(function () { $('#btn-output').click(function () { $('#output-data').toggle(); $('#bottom-pane').toggleClass('opened'); windowResized(); }); $('#btn-run').click(function () { onRunning(); var codeRunRequest = { lang: $('#lang').find(":selected").val(), code: editor.getValue(), input: $('#text-input').val() }; runCode(codeRunRequest); // $.ajax({ // type: "POST", // url: '/apis/run', // data: JSON.stringify(codeRunRequest), // contentType: 'application/json' // }).done(function (data) { // showOutput(data); // $('#btn-run').prop('disabled', false); // }).fail(function (data) { // alert("error"); // $('#btn-run').prop('disabled', false); // }); }); $('#btn-hide-output').click(function () { $('#btn-hide-output').hide(); $('#btn-show-output').show(); viewConfig.showOutput = false; windowResized(); }); $('#btn-show-output').click(function () { $('#btn-hide-output').show(); $('#btn-show-output').hide(); viewConfig.showOutput = true; windowResized(); }); $('#btn-hide-input').click(function () { $('#btn-hide-input').hide(); $('#btn-show-input').show(); viewConfig.showInput = false; windowResized(); }); $('#btn-show-input').click(function () { $('#btn-hide-input').show(); $('#btn-show-input').hide(); viewConfig.showInput = true; windowResized(); }); loadLangs(); $(window).resize(function () { windowResized(); }); windowResized(); }); $('#lang').change(function () { onLangChanged(); }); function onLangChanged() { var lang = $('#lang').find(":selected").val(); if (prevLang) { codeTemplates[prevLang] = editor.getValue(); } editor.setValue(codeTemplates[lang], -1); prevLang = lang; if (lang === 'java7') { editor.getSession().setMode("ace/mode/java"); } else if (lang === 'python3') { editor.getSession().setMode("ace/mode/python"); } else if (lang === 'c' || lang === 'c++') { editor.getSession().setMode("ace/mode/c_cpp"); } else if (lang === 'c#') { editor.getSession().setMode("ace/mode/csharp"); } } function windowResized() { var aceWrapper = $('#ace_wrapper'); var aceEditor = $('#editor'); var outputWrapper = $('#output-wrapper'); var outputData = $('#output-data'); var inputWrapper = $('#input-wrapper'); var textInput = $('#text-input'); var rightDiff; var inputHeight; var outputHeight; var textInputWidth; var textInputHeight; if (viewConfig.showInput || viewConfig.showOutput) { rightDiff = outputWrapper.width() + 4; } else { rightDiff = 0; } var aceHeight = window.innerHeight - aceWrapper.position().top;// - bottomPane.height(); var aceWidth = window.innerWidth - rightDiff; if (viewConfig.showOutput) { outputWrapper.show(); outputHeight = aceHeight; } else { outputWrapper.hide(); outputHeight = 0; } if (viewConfig.showInput) { inputWrapper.show(); inputHeight = 225; if (viewConfig.showOutput) { outputHeight -= inputHeight; } else { inputHeight = aceHeight; } textInputHeight = inputHeight - 62; textInputWidth = rightDiff - 23; } else { inputWrapper.hide(); inputHeight = 0; } // var bottomPane = $('#bottom-pane'); // var outputWrapperHeight = aceHeight - inputWrapper.height() - 2; var outputTextHeight = outputHeight - 52; aceWrapper.css('height', aceHeight + 'px'); aceWrapper.css('width', aceWidth + 'px'); aceEditor.css('height', aceHeight + 'px'); aceEditor.css('width', aceWidth + 'px'); editor.resize(); if (viewConfig.showOutput) { outputWrapper.css('height', outputHeight + 'px'); outputData.css('max-height', outputTextHeight + 'px'); } if (viewConfig.showInput) { inputWrapper.css('height', inputHeight + 'px'); textInput.css('width', textInputWidth + 'px'); textInput.css('height', textInputHeight + 'px'); // outputData.css('max-height', outputTextHeight + 'px'); } } var stompClient; function connect() { var socket = new SockJS('/coderun'); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { // window.alert("connected !"); stompClient.subscribe('/user/queue/reply', function (reply) { showOutput(JSON.parse(reply.body)); onFinished(); }); }); } function runCode(codeRunRequest) { stompClient.send('/iapis/run', {}, JSON.stringify(codeRunRequest)); } function onRunning() { $('#btn-run').prop('disabled', true); $('#icon-running').show(); $('#icon-run').hide(); } function onFinished() { $('#btn-run').prop('disabled', false); $('#icon-running').hide(); $('#icon-run').show(); } connect();
AbdallaMahmoud/codeyard
src/main/resources/webapp/js/main.js
JavaScript
gpl-3.0
7,360
import {Component, OnInit} from '@angular/core'; import {FundDataService} from '../funddata/funddata.service'; @Component({ selector: 'app-fund-table', templateUrl: './fund-table.component.html', styleUrls: ['./fund-table.component.css'] }) export class FundTableComponent implements OnInit { private colShow: string[] = ['link_linkDisplay', 'fundResult_morningstarRating', 'oneQuarterAgoChange']; private columns: string[]; private funds: Object[]; private fundsShow: Object[]; private error: any; constructor(private fundDataService: FundDataService) { } ngOnInit() { this.fundDataService.loadFunds().subscribe((datas) => { this.funds = datas; this.fundsShow = datas; this.columns = Object.keys(datas[0]); // console.log('columns: ' + this.columns); // console.log(JSON.stringify(datas)); }, (err) => {// error console.log(err); this.error = err; }, () => {// complete }); } toggleColumn(col: string) { if (this.colShow.indexOf(col) === -1) { this.colShow.push(col); } else { this.colShow.splice(this.colShow.indexOf(col), 1); } } }
jensim/fundscreener
src/app/fund-table/fund-table.component.ts
TypeScript
gpl-3.0
1,096
/* * Copyright appNativa Inc. All Rights Reserved. * * This file is part of the Real-time Application Rendering Engine (RARE). * * RARE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.appnativa.rare.platform.swing.ui.view; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import javax.swing.Icon; import javax.swing.JRadioButton; import com.appnativa.rare.Platform; import com.appnativa.rare.iConstants; import com.appnativa.rare.iPlatformAppContext; import com.appnativa.rare.platform.swing.ui.util.SwingGraphics; import com.appnativa.rare.ui.ColorUtils; import com.appnativa.rare.ui.FontUtils; import com.appnativa.rare.ui.UIColor; import com.appnativa.rare.ui.UIDimension; import com.appnativa.rare.ui.iPlatformIcon; import com.appnativa.rare.ui.painter.iPainter; import com.appnativa.rare.ui.painter.iPainterSupport; import com.appnativa.rare.ui.painter.iPlatformComponentPainter; import com.appnativa.util.CharArray; import com.appnativa.util.XMLUtils; public class RadioButtonView extends JRadioButton implements iPainterSupport, iView { protected static iPlatformIcon deselectedIconDisabled_; protected static iPlatformIcon deselectedIcon_; protected static iPlatformIcon deselectedPressedIcon_; protected static iPlatformIcon selectedIconDisabled_; protected static iPlatformIcon selectedIcon_; protected static iPlatformIcon selectedPressedIcon_; private String originalText; private boolean wordWrap; public RadioButtonView() { super(); initialize(); } public RadioButtonView(Icon icon) { super(icon); initialize(); } public RadioButtonView(String text) { super(text); initialize(); } public RadioButtonView(String text, Icon icon) { super(text, icon); initialize(); } AffineTransform transform; protected SwingGraphics graphics; private iPlatformComponentPainter componentPainter; @Override public boolean isOpaque() { return ((componentPainter != null) && componentPainter.isBackgroundPaintEnabled()) ? false : super.isOpaque(); } @Override public void setTransformEx(AffineTransform tx) { transform = tx; } @Override public Color getForeground() { Color c=super.getForeground(); if(c instanceof UIColor && !isEnabled()) { c=((UIColor)c).getDisabledColor(); } return c; } @Override public AffineTransform getTransformEx() { return transform; } @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; AffineTransform tx = g2.getTransform(); if (transform != null) { g2.transform(transform); } graphics = SwingGraphics.fromGraphics(g2, this, graphics); super.paint(g2); if (tx != null) { g2.setTransform(tx); } graphics.clear(); } @Override protected void paintBorder(Graphics g) { if (componentPainter == null) { super.paintBorder(g); } } @Override protected void paintChildren(Graphics g) { super.paintChildren(graphics.getGraphics()); iPlatformComponentPainter cp = getComponentPainter(); if (cp != null) { float height = getHeight(); float width = getWidth(); cp.paint(graphics, 0, 0, width, height, iPainter.HORIZONTAL, true); } } @Override protected void paintComponent(Graphics g) { graphics = SwingGraphics.fromGraphics(g, this, graphics); iPlatformComponentPainter cp = getComponentPainter(); if (cp != null) { float height = getHeight(); float width = getWidth(); cp.paint(graphics, 0, 0, width, height, iPainter.HORIZONTAL, false); } super.paintComponent(g); } @Override public void setComponentPainter(iPlatformComponentPainter cp) { componentPainter = cp; } @Override public iPlatformComponentPainter getComponentPainter() { return componentPainter; } @Override public void getMinimumSize(UIDimension size, int maxWidth) { Dimension d = getMinimumSize(); size.width = d.width; size.height = d.height; } @Override public void setText(String text) { if (text == null) { text = ""; } originalText = text; int len = text.length(); if (wordWrap && (len > 0) &&!text.startsWith("<html>")) { CharArray ca = new CharArray(text.length() + 20); ca.append("<html>"); XMLUtils.escape(text.toCharArray(), 0, len, true, ca); ca.append("</html>"); text = ca.toString(); } super.setText(text); } public void setWordWrap(boolean wordWrap) { this.wordWrap = wordWrap; } @Override public String getText() { return originalText; } public boolean isWordWrap() { return wordWrap; } protected void initialize() { setOpaque(false); setFont(FontUtils.getDefaultFont()); setForeground(ColorUtils.getForeground()); if (selectedIcon_ == null) { iPlatformAppContext app = Platform.getAppContext(); if (ColorUtils.getForeground().isDarkColor()) { selectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.light"); deselectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.light"); selectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.pressed.light"); deselectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.pressed.light"); selectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.disabled.light"); deselectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.disabled.light"); } else { selectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.dark"); deselectedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.dark"); selectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.pressed.dark"); deselectedPressedIcon_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.pressed.dark"); selectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.on.disabled.dark"); deselectedIconDisabled_ = app.getResourceAsIcon("Rare.icon.radiobutton.off.disabled.dark"); } } setSelectedIcon(selectedIcon_); setDisabledIcon(deselectedIconDisabled_); setPressedIcon(deselectedPressedIcon_); setIcon(deselectedIcon_); setDisabledSelectedIcon(selectedIconDisabled_); } @Override public Icon getDisabledIcon() { Icon icon = super.getDisabledIcon(); if (icon == null) { icon = getIcon(); if (icon instanceof iPlatformIcon) { return ((iPlatformIcon) icon).getDisabledVersion(); } } return icon; } public Icon getDisabledSelectedIcon() { Icon icon = super.getDisabledSelectedIcon(); if (icon == null) { icon = getSelectedIcon(); if (icon == null) { icon = getIcon(); } if (icon instanceof iPlatformIcon) { return ((iPlatformIcon) icon).getDisabledVersion(); } } return icon; } private static UIDimension size = new UIDimension(); @Override public Dimension getPreferredSize() { if (size == null) { size = new UIDimension(); } Number num = (Number) getClientProperty(iConstants.RARE_WIDTH_FIXED_VALUE); int maxWidth = 0; if ((num != null) && (num.intValue() > 0)) { maxWidth = num.intValue(); } getPreferredSize(size, maxWidth); return new Dimension(size.intWidth(), size.intHeight()); } @Override public void getPreferredSize(UIDimension size, int maxWidth) { Dimension d = super.getPreferredSize(); size.width = d.width; size.height = d.height; if (isFontSet() && getFont().isItalic()) { if (getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey) == null) { size.width += 4; } } } }
appnativa/rare
source/rare/swingx/com/appnativa/rare/platform/swing/ui/view/RadioButtonView.java
Java
gpl-3.0
8,918
package de.roskenet.simplecms.repository; import org.springframework.data.repository.PagingAndSortingRepository; import de.roskenet.simplecms.entity.Attribute; public interface AttributeRepository extends PagingAndSortingRepository<Attribute, Integer> { }
roskenet/simple-cms
src/main/java/de/roskenet/simplecms/repository/AttributeRepository.java
Java
gpl-3.0
260
/** * * Copyright (C) 2004-2008 FhG Fokus * * This file is part of the FhG Fokus UPnP stack - an open source UPnP implementation * with some additional features * * You can redistribute the FhG Fokus UPnP stack and/or modify it * under the terms of the GNU General Public License Version 3 as published by * the Free Software Foundation. * * For a license to use the FhG Fokus UPnP stack software under conditions * other than those described here, or to purchase support for this * software, please contact Fraunhofer FOKUS by e-mail at the following * addresses: * upnpstack@fokus.fraunhofer.de * * The FhG Fokus UPnP stack is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package de.fraunhofer.fokus.upnp.core; import java.util.Hashtable; import java.util.Vector; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import de.fraunhofer.fokus.upnp.util.SAXTemplateHandler; /** * This class is used to parse UPnPDoc messages. * * @author Alexander Koenig * * */ public class UPnPDocParser extends SAXTemplateHandler { /** Doc entries for the current service type */ private Vector currentDocEntryList = new Vector(); private boolean isAction = false; private boolean isStateVariable = false; private String currentServiceType = null; private String currentArgumentName = null; private String currentArgumentDescription = null; private UPnPDocEntry currentDocEntry = null; /** Hashtable containing the UPnP doc entry list for one service type */ private Hashtable docEntryFromServiceTypeTable = new Hashtable(); /* * (non-Javadoc) * * @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processStartElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void processStartElement(String uri, String name, String name2, Attributes atts) throws SAXException { if (getTagCount() == 2) { for (int i = 0; i < atts.getLength(); i++) { if (atts.getQName(i).equalsIgnoreCase("serviceType")) { currentServiceType = atts.getValue(i); currentDocEntryList = new Vector(); } } } if (getTagCount() == 3 && currentServiceType != null) { isAction = getCurrentTag().equalsIgnoreCase("actionList"); isStateVariable = getCurrentTag().equalsIgnoreCase("serviceStateTable"); } if (getTagCount() == 4 && currentServiceType != null) { currentDocEntry = new UPnPDocEntry(currentServiceType); } } /* * (non-Javadoc) * * @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processEndElement(java.lang.String, * java.lang.String, java.lang.String) */ public void processEndElement(String uri, String localName, String name) throws SAXException { if (getTagCount() == 6 && isAction && currentDocEntry != null && currentArgumentName != null && currentArgumentDescription != null) { currentDocEntry.addArgumentDescription(currentArgumentName, currentArgumentDescription); currentArgumentName = null; currentArgumentDescription = null; } if (getTagCount() == 4) { if (currentDocEntry != null && currentDocEntry.getActionName() != null && isAction) { // TemplateService.printMessage(" Add doc entry for action " + // currentDocEntry.getActionName()); currentDocEntryList.add(currentDocEntry); } if (currentDocEntry != null && currentDocEntry.getStateVariableName() != null && isStateVariable) { // TemplateService.printMessage(" Add doc entry for state variable " + // currentDocEntry.getStateVariableName()); currentDocEntryList.add(currentDocEntry); } currentDocEntry = null; } if (getTagCount() == 3) { isAction = false; isStateVariable = false; } if (getTagCount() == 2) { // store list with doc entries for one service type docEntryFromServiceTypeTable.put(currentServiceType, currentDocEntryList); currentServiceType = null; currentDocEntryList = null; } } /* * (non-Javadoc) * * @see de.fraunhofer.fokus.upnp.util.SAXTemplateHandler#processContentElement(java.lang.String) */ public void processContentElement(String content) throws SAXException { if (getTagCount() == 5 && currentDocEntry != null) { if (getCurrentTag().equalsIgnoreCase("name") && isAction) { currentDocEntry.setActionName(content.trim()); } if (getCurrentTag().equalsIgnoreCase("name") && isStateVariable) { currentDocEntry.setStateVariableName(content.trim()); } if (getCurrentTag().equalsIgnoreCase("description")) { currentDocEntry.setDescription(content.trim()); } } if (getTagCount() == 7 && currentDocEntry != null) { if (getCurrentTag().equalsIgnoreCase("name")) { currentArgumentName = content.trim(); } if (getCurrentTag().equalsIgnoreCase("description")) { currentArgumentDescription = content.trim(); } } } /** * Retrieves the upnpDocEntryTable. * * @return The upnpDocEntryTable */ public Hashtable getDocEntryFormServiceTypeTable() { return docEntryFromServiceTypeTable; } }
fraunhoferfokus/fokus-upnp
upnp-core/src/main/java/de/fraunhofer/fokus/upnp/core/UPnPDocParser.java
Java
gpl-3.0
5,855
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Andrew Kofink <ajkofink@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: "Andrew Kofink (@akofink)" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: "Upload the RHEL developer edition manifest" theforeman.foreman.subscription_manifest: username: "admin" password: "changeme" server_url: "https://foreman.example.com" organization: "Default Organization" state: present manifest_path: "/tmp/manifest.zip" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if "same as existing data" in error: # Nothing changed, but everything ok break if "older than existing data" in error: module.fail_json(msg="Manifest is older than existing data.") else: module.fail_json(msg="Upload of the manifest failed: %s" % error) else: module.set_changed() except IOError as e: module.fail_json(msg="Unable to read the manifest file: %s" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg="No manifest found to refresh.") if __name__ == '__main__': main()
ATIX-AG/foreman-ansible-modules
plugins/modules/subscription_manifest.py
Python
gpl-3.0
5,027
import moment from 'moment'; import PublicationsController from './controller/publications.controller.js'; import AuthorsController from './controller/authors.controller.js'; import PublishersController from './controller/publishers.controller.js'; /* * Application routing */ function routing($routeProvider) { $routeProvider .when('/publications', { template: require('./view/publications.html'), controller: PublicationsController, controllerAs: 'vm' }) .when('/authors', { template: require('./view/authors.html'), controller: AuthorsController, controllerAs: 'vm' }) .when('/publishers', { template: require('./view/publishers.html'), controller: PublishersController, controllerAs: 'vm' }) .otherwise({ redirectTo: '/publications' }); } routing.$inject = ['$routeProvider']; /* * Theming configuration for Material AngularJS */ function theming($mdThemingProvider) { $mdThemingProvider .theme('default') .primaryPalette('indigo') .accentPalette('red'); } theming.$inject = ['$mdThemingProvider']; /* * Date localization configuration */ function dateLocalization($mdDateLocaleProvider) { const dateFmt = 'YYYY-MM-DD'; $mdDateLocaleProvider.formatDate = (date) => { return moment(date).format(dateFmt); }; $mdDateLocaleProvider.parseDate = (str) => { const m = moment(str, dateFmt); return m.isValid() ? m.toDate() : new Date(NaN); }; } dateLocalization.$inject = ['$mdDateLocaleProvider']; export { routing, theming, dateLocalization };
enric-sinh/publication-library
web/src/app/app.config.js
JavaScript
gpl-3.0
1,574
#include "disablenonworkingunits.h" #include "wololo/datPatch.h" namespace wololo { void disableNonWorkingUnitsPatch(genie::DatFile *aocDat, std::map<int, std::string> *langReplacement) { /* * Disabling units that are not supposed to show in the scenario editor */ for (size_t civIndex = 0; civIndex < aocDat->Civs.size(); civIndex++) { aocDat->Civs[civIndex].Units[1119].HideInEditor = 1; aocDat->Civs[civIndex].Units[1145].HideInEditor = 1; aocDat->Civs[civIndex].Units[1147].HideInEditor = 1; aocDat->Civs[civIndex].Units[1221].HideInEditor = 1; aocDat->Civs[civIndex].Units[1401].HideInEditor = 1; for (size_t unitIndex = 1224; unitIndex <= 1390; unitIndex++) { aocDat->Civs[civIndex].Units[unitIndex].HideInEditor = 1; } } } DatPatch disableNonWorkingUnits = { &disableNonWorkingUnitsPatch, "Hide units in the scenario editor" }; }
Tails8521/WololoKingdoms
fixes/disablenonworkingunits.cpp
C++
gpl-3.0
872
import styled from "./Theme"; export const Content = styled.div` margin: 2rem 0; padding: 5px; `;
lucas-burdell/lucas-burdell.github.io
src/Content.tsx
TypeScript
gpl-3.0
102
<?php namespace Chamilo\Core\Repository\Selector; /** * A category of options in a ContentObjectTypeSelector * * @author Hans De Bisschop <hans.de.bisschop@ehb.be> */ class TypeSelectorCategory { /** * * @var string */ private $type; /** * * @var string */ private $name; /** * * @var \core\repository\ContentObjectTypeSelectorOption[] */ private $options; /** * * @param string $type * @param string $name * @param \core\repository\ContentObjectTypeSelectorOption[] $options */ public function __construct($type, $name, $options = array()) { $this->type = $type; $this->name = $name; $this->options = $options; } /** * * @return string */ public function get_type() { return $this->type; } /** * * @param string $type */ public function set_type($type) { $this->type = $type; } /** * * @return string */ public function get_name() { return $this->name; } /** * * @param string $name */ public function set_name($name) { $this->name = $name; } /** * * @return \Chamilo\Core\Repository\Selector\TypeSelectorOption[] */ public function get_options() { return $this->options; } /** * * @param \core\repository\ContentObjectTypeSelectorOption[] */ public function set_options($options) { $this->options = $options; } /** * * @param \core\repository\ContentObjectTypeSelectorOption $option */ public function add_option($option) { $this->options[] = $option; } /** * Sort the ContentObjectTypeSelectorOption instances by name */ public function sort() { usort( $this->options, function ($option_a, $option_b) { return strcmp($option_a->get_name(), $option_b->get_name()); }); } /** * * @return int */ public function count() { return count($this->get_options()); } /** * * @return int[] */ public function get_unique_content_object_template_ids() { $types = array(); foreach ($this->get_options() as $option) { if (! in_array($option->get_template_registration_id(), $types)) { $types[] = $option->get_template_registration_id(); } } return $types; } }
vanpouckesven/cosnics
src/Chamilo/Core/Repository/Selector/TypeSelectorCategory.php
PHP
gpl-3.0
2,653
# coding: utf-8 # Copyright (C) 2017 Open Path View, Maison Du Libre # 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/>. # Contributors: Benjamin BERNARD <benjamin.bernard@openpathview.fr> # Email: team@openpathview.fr # Description: Camera Set Partition, represent a partition of ImagesSets. from typing import NamedTuple, List from opv_import.model import ImageSet CameraSetPartition = NamedTuple( 'CameraSetPartition', [ ('ref_set', ImageSet), ('images_sets', List[ImageSet]), ('start_indexes', List[int]), ('fetcher_next_indexes', List[int]), ('break_reason', str), ('number_of_incomplete_sets', int), ('number_of_complete_sets', int), ('max_consecutive_incomplete_sets', int) ] )
OpenPathView/batchPanoMaker
opv_import/model/camera_set_partition.py
Python
gpl-3.0
1,341
<?php /** * @version $Id: search.class.php v1.0 $ * @package PBDigg * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved. * @license PBDigg is free software and use is subject to license terms */ class search { /** * 搜索类型 */ var $_searchtype; /** * 搜索条件语句 */ var $_searchsql = ''; /** * 搜索基本表 */ var $_basetable; /** * 返回限定 */ var $_limit = ''; /** * 搜索hash */ var $_cacheHash = ''; /** * 记录总数 */ var $_resultNum; /** * 分页参数 */ var $_mult = ''; /** * 搜索匹配正则 */ var $_pattern = array('%','_','*'); var $_replace = array('\%','\_','%'); /** * 数据库实例 */ var $DB = null; var $db_prefix = ''; /** * 是否缓存搜索 */ var $_ifcache; /** * 缓存周期 */ var $_cacheTime = 600; function search($type, $cache = false) { $this->__construct($type, $cache); } function __construct($type, $cache = false) { if (in_array($type, array('article', 'comment', 'attachment', 'author'))) { global $page, $pagesize, $DB, $db_prefix; $this->DB = $DB; $this->db_prefix = $db_prefix; $this->_searchtype = $type; $this->_ifcache = $cache ? true : false; $this->_limit = sqlLimit($page, $pagesize); switch ($this->_searchtype) { case 'article': $this->_basetable = 't'; break; case 'comment': $this->_basetable = 'c'; break; case 'attachment': $this->_basetable = 'a'; break; case 'author': $this->_basetable = 'm'; break; } } } function getMult() { return $this->_mult; } function getResultNum() { return intval($this->_resultNum); } function exportResults($condition) { global $searchhash; if (!is_array($condition)) return; $cached = false; if ($this->_ifcache && isset($searchhash) && preg_match('~^[a-z0-9]{32}$~', $searchhash)) { $cached = $this->getCache($searchhash); } if (!$cached) { foreach ($condition as $k => $v) { $this->$k($v); } $this->_cacheHash = md5(md5($this->_searchsql).$this->_searchtype); $this->_ifcache && $cached = $this->getCache($this->_cacheHash); } $this->_searchsql && $this->_searchsql = ' WHERE '.substr($this->_searchsql, 4); return $this->{$this->_searchtype}($cached); } function getCache($searchhash) { global $timestamp; $cacheData = $this->DB->fetch_one("SELECT num, ids, exptime FROM {$this->db_prefix}scaches WHERE hash = '$searchhash' AND exptime > '$timestamp'"); if ($cacheData && $cacheData['ids']) { $this->_resultNum = (int)$cacheData['num']; $newids = ''; $ids = explode(',', $cacheData['ids']); foreach ($ids as $v) { $newids .= (int)$v.','; } $newids && $newids = substr($newids, 0, -1); switch ($this->_searchtype) { case 'article': $this->_searchsql = " AND t.tid IN ($newids)"; break; case 'comment': $this->_searchsql = " AND c.rid IN ($newids)"; break; case 'attachment': $this->_searchsql = " AND a.aid IN ($newids)"; break; case 'author': $this->_searchsql = " AND m.uid IN ($newids)"; break; } $newids != $cacheData['ids'] && $this->DB->db_exec("UPDATE {$this->db_prefix}scaches SET ids = '".addslashes($newids)."' WHERE hash = '$searchhash' AND exptime = '".$cacheData['exptime']."'"); $this->_mult = '&searchhash='.$searchhash; return true; } } function buildCache($ids) { global $timestamp; $this->DB->db_exec("DELETE FROM {$this->db_prefix}scaches WHERE exptime <= '$timestamp'"); $this->DB->db_exec("INSERT INTO {$this->db_prefix}scaches (hash,keywords,num,ids,searchip,searchtime,exptime) VALUES ('".$this->_cacheHash."','','".$this->_resultNum."','$ids','','','".($timestamp + $this->_cacheTime)."')"); $this->_mult = '&searchhash='.$this->_cacheHash; } function article($cached) { $anonymity = getSingleLang('common', 'common_anonymity'); if ($this->_ifcache && !$cached) { $query = $this->DB->db_query("SELECT t.tid FROM {$this->db_prefix}threads t ".$this->_searchsql); $ids = ''; $num = 0; while ($rs = $this->DB->fetch_all($query)) { $ids .= (int)$rs['tid'].','; $num++; } if ($ids) { $this->_resultNum = (int)$num; $ids = substr($ids, 0, -1); $this->buildCache($ids); $this->_searchsql = " WHERE t.tid IN ($ids)"; unset($ids, $num); } } if (!isset($this->_resultNum)) { $rs = $this->DB->fetch_one("SELECT COUNT(*) num FROM {$this->db_prefix}threads t ".$this->_searchsql); $this->_resultNum = (int)$rs['num']; } $query = $this->DB->db_query("SELECT t.tid, t.subject, t.author, t.postdate, t.postip FROM {$this->db_prefix}threads t ".$this->_searchsql.$this->_limit); $article = array(); while ($rs = $this->DB->fetch_all($query)) { $rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i'); !$rs['author'] && $rs['author'] = $anonymity; $article[] = $rs; } return $article; } function comment($cached) { $anonymity = getSingleLang('common', 'common_anonymity'); if ($this->_ifcache && !$cached) { $query = $this->DB->db_query("SELECT c.rid FROM {$this->db_prefix}comments c ".$this->_searchsql); $ids = ''; $num = 0; while ($rs = $this->DB->fetch_all($query)) { $ids .= (int)$rs['rid'].','; $num++; } if ($ids) { $this->_resultNum = (int)$num; $ids = substr($ids, 0, -1); $this->buildCache($ids); $this->_searchsql = " WHERE c.rid IN ($ids)"; unset($ids, $num); } } if (!isset($this->_resultNum)) { $rs = $this->DB->fetch_one("SELECT COUNT(*) num FROM {$this->db_prefix}comments c ".$this->_searchsql); $this->_resultNum = (int)$rs['num']; } $query = $this->DB->db_query("SELECT c.rid, c.content, c.author, c.postdate, c.postip FROM {$this->db_prefix}comments c ".$this->_searchsql.$this->_limit); $comment = array(); while ($rs = $this->DB->fetch_all($query)) { $rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i'); $rs['content'] = PBSubStr($rs['content'], 50); !$rs['author'] && $rs['author'] = $anonymity; $comment[] = $rs; } return $comment; } // function author() // { // $this->_sql = "SELECT * FROM {$this->db_prefix}threads t"; // } function attachment($cached) { $anonymity = getSingleLang('common', 'common_anonymity'); if ($this->_ifcache && !$cached) { $query = $this->DB->db_query("SELECT a.aid FROM {$this->db_prefix}attachments a ".$this->_searchsql); $ids = ''; $num = 0; while ($rs = $this->DB->fetch_all($query)) { $ids .= (int)$rs['aid'].','; $num++; } if ($ids) { $this->_resultNum = (int)$num; $ids = substr($ids, 0, -1); $this->buildCache($ids); $this->_searchsql = " WHERE a.aid IN ($ids)"; unset($ids, $num); } } if (!isset($this->_resultNum)) { $rs = $this->DB->fetch_one("SELECT COUNT(*) num FROM {$this->db_prefix}attachments a ".$this->_searchsql); $this->_resultNum = (int)$rs['num']; } $query = $this->DB->db_query("SELECT a.aid, a.tid, a.uid, a.filename, a.filesize, a.uploaddate, a.downloads FROM {$this->db_prefix}attachments a ".$this->_searchsql.$this->_limit); $attachment = array(); while ($rs = $this->DB->fetch_all($query)) { $rs['uploaddate'] = gdate($rs['uploaddate'], 'Y-m-d H:i'); $rs['filename'] = htmlspecialchars($rs['filename']); $rs['filesize'] = getRealSize($rs['filesize']); $attachment[] = $rs; } return $attachment; } function cid($cid) { !is_array($cid) && $cid = explode(',', $cid); $newcid = ''; foreach ($cid as $v) { $v && is_numeric($v) && $newcid .= $newcid ? ',' : '' . (int)$v; } if ($newcid) { $this->_searchsql .= " AND ".$this->_basetable.".cid IN ($newcid)"; $this->_mult .= '&cid='.$newcid; } } function mid($mid) { global $module; !is_array($mid) && $mid = explode(',', $mid); $newmid = ''; if (!is_object($module)) { require_once PBDIGG_ROOT.'include/module.class.php'; $module = new module(); } foreach ($mid as $v) { $v && is_numeric($v) && in_array($mid, $module->getModuleId()) && $newmid .= $newmid ? ',' : '' . (int)$v; } if ($newmid) { $this->_searchsql .= " AND ".$this->_basetable.".module IN ($newmid)"; $this->_mult .= '&mid='.$newmid; } } function uid($uid) { !is_array($uid) && $uid = explode(',', $uid); $newuid = ''; foreach ($uid as $v) { $v && is_numeric($v) && $newuid .= $newuid ? ',' : '' . (int)$v; } if ($newuid) { $this->_searchsql .= " AND ".$this->_basetable.".uid IN ($newuid)"; $this->_mult .= '&uid='.$newuid; } } function authors($author) { $author = strip_tags(trim($author)); $_author = explode(',', $author); $authorCondition = ''; foreach ($_author as $value) { if (trim($value) && (strlen($value) <= 20)) { $authorCondition .= " OR username LIKE '".str_replace($this->_pattern, $this->_replace, preg_replace('~\*{2,}~i', '*', $value))."'"; } } if ($authorCondition) { $query = $this->DB->db_query("SELECT uid FROM {$this->db_prefix}members WHERE ".substr($authorCondition, 3)); $uids = ''; while ($rs = $this->DB->fetch_all($query)) { $uids .= ",".(int)$rs['uid']; } $this->_searchsql .= $uids ? ' AND '.$this->_basetable.'.uid IN ('.substr($uids, 1).')' : ' AND 0'; $this->_mult .= '&authors='.rawurlencode($author); } } function tags($tags) { $tags = strip_tags(trim($tags)); $_tags = explode(',', $tags); $tagCondition = ''; foreach ($_tags as $value) { if (trim($value) && (strlen($value) <= 30)) { $tagCondition .= " OR tg.tagname LIKE '".str_replace($this->_pattern, $this->_replace, preg_replace('/\*{2,}/i', '*', $value))."'"; } } if ($tagCondition) { $query = $this->DB->db_query("SELECT tc.tid FROM {$this->db_prefix}tagcache tc INNER JOIN {$this->db_prefix}tags tg USING (tagid) WHERE ".substr($tagCondition, 3)); $tids = ''; while ($rs = $this->DB->fetch_all($query)) { $tids .= ",".(int)$rs['tid']; } $this->_searchsql .= $tids ? ' AND '.$this->_basetable.'.tid IN ('.substr($tids, 1).')' : ' AND 0'; $this->_mult .= '&tags='.rawurlencode($tags); } } /** * @param string $datefield 时间字段 */ function searchdate($params) { foreach ($params as $k => $v) { if (preg_replace('~[a-z]~i', '', $k)) return; list ($more, $less) = $v; if ($more && preg_match('~^\d{4}-\d{1,2}-\d{1,2}$~i', $more)) { $this->_searchsql .= " AND {$this->_basetable}.$k >= ".pStrToTime($more.' 0:0:0'); $this->_mult .= '&'.$k.'more='.$more; } if ($less && preg_match('~^\d{4}-\d{1,2}-\d{1,2}$~i', $less)) { $this->_searchsql .= " AND {$this->_basetable}.$k < ".pStrToTime($less.' 0:0:0'); $this->_mult .= '&'.$k.'less='.$less; } } } function searchscope($params) { foreach ($params as $k => $v) { if (preg_replace('~[a-z]~i', '', $k)) return; list ($more, $less) = $v; if (is_numeric($more) && $more != -1) { $more = (int)$more; $this->_searchsql .= " AND {$this->_basetable}.$k >= $more"; $this->_mult .= '&'.$k.'more='.$more; } if (is_numeric($less) && $less != -1) { $less = (int)$less; $this->_searchsql .= " AND {$this->_basetable}.$k < $less"; $this->_mult .= '&'.$k.'less='.$less; } } } function postip($ip) { if ($ip && preg_match('~^[0-9\*\.]+$~i', $ip)) { $this->_searchsql .= " AND ".$this->_basetable.".postip ".((strpos($ip, '*') === FALSE) ? (" = '$ip'") : " LIKE '".str_replace('*', '%', preg_replace('~\*{2,}~i', '*', $ip))."'"); $this->_mult .= '&postip='.rawurlencode($ip); } } function isimg($bool) { if ($bool) { $this->_searchsql .= ' AND '.$this->_basetable.'.isimg = 1'; $this->_mult .= '&isimg=1'; } } function linkhost($linkhost) { if ($linkhost && preg_match('~^[-_a-z0-9\.\~!\$&\'\(\)\*\+,;=:@\|/]+$~i', $linkhost)) { $this->_searchsql .= " AND ".$this->_basetable.".linkhost ".(strpos($linkhost, '*') === FALSE ? " = '$linkhost'" : " LIKE '".str_replace('*', '%', preg_replace('~\*{2,}~i', '*', $linkhost))."'"); $this->_mult .= '&linkhost='.rawurlencode($linkhost);; } } } ?>
mikeshou/pbdigg
include/search.class.php
PHP
gpl-3.0
12,688
using System; namespace ForumSystem.Data.Models.BaseEntities { public interface IDeletableEntity { bool IsDeleted { get; set; } DateTime? DeletedOn { get; set; } } }
iwelina-popova/ForumSystem
Source/Data/ForumSystem.Data.Models/BaseEntities/IDeletableEntity.cs
C#
gpl-3.0
199
<?php /** * Nombre del archivo: RegionSicaController.php * Descripción:Contiene las funciones del controlador * Fecha de creación:18/11/2017 * Creado por: Juan Carlos Centeno Borja */ namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\region_sica; use App\Http\Requests; use App\Http\Controllers\Controller; class RegionSicaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function fnc_obtener_id($param){ $id_region_sica=0; $obj_region_sica= region_sica::all(); foreach ($obj_region_sica as $paises){ if($paises->nombre_pais==$param){ $id_region_sica=$paises->id_region_sica; } } return $id_region_sica; } public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
jcenteno1973/sicafam
app/Http/Controllers/RegionSicaController.php
PHP
gpl-3.0
2,136
/* * Copyright (C) 2013 Huub de Beer * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ var model = function(name, config) { "use strict"; var _model = {name: name}, _appendix = {}; // ## Data invariant and initialization // // This model describes a dynamic phenomenon in terms of changing // quantities over time. // // // This description starts at `T_START` milliseconds // (ms), defaulting to 0 ms and ends at `T_END` ms. If no end is specified // it is assumed that the phenomenon does not end or is still ongoing in // the real world (RW). The phenomenon's change is tracked by "measuring" // the changing quantities at consecutive moments in time. These moments // are `T_STEP` apart, defaulting to 1 ms, and are tracked by order // number. var T_START = config.time.start || 0, T_END = config.time.end || Infinity, T_STEP = config.time.step || 1; function set_end(seconds) { T_END = seconds*1000; } _model.set_end = set_end; // To translate from a moment's order number to its corresponding time in // ms and vice versa, two helper functions are defined, `time_to_moment` // and `moment_to_time`, as well as a shorthand name for these two helper // functions, respectively, `t2m` and `m2t`. _model.time_to_moment = function(time) { return Math.floor(time / T_STEP); }; var t2m = _model.time_to_moment; _model.moment_to_time = function(moment) { return moment * T_STEP; }; var m2t = _model.moment_to_time; // When I use "measured" I mean to denote that the values of the // quantities describing the phenomenon have been captured, computed, // downloaded, measured, or otherwise obtained. This `model` function is // intended to be applicable for describing purely theoretical models of a // phenomenon as well as real-time measurements of a phenomenon. // // "Measuring" a moment is left to the `measure_moment` function. Each // model has to (re)implement this function to specify the relationship // between the phenomenon's quantities of interest at each moment during // the phenomenon. _model.measure_moment = function(moment) { // to be implemented in an object implementing model }; // The model has the following data invariant: // // (∀m: 0 ≤ m ≤ |`moments`|: `moment_computed`(`moments`[m])) // // stating that the phenomenon has been described quantitatively for all // moments. These "measurements" are stored in a list of `moments` and can // be accessed through a moment's order number. var moments = []; _model.get_moment = function(moment) { return moments[moment]; }; _model.number_of_moments = function() { return moments.length; }; // A moment can only be inspected if it already has been "measured". // Following the data invariant, a moment has been measured when its order // number is smaller or equal to the number of measured moments. _model.moment_measured = function(moment) { return (moment <= (moments.length - 1)); }; // Furthermore, the current moment of interest, or `now`, points to an // already "measured" moment during the phenomenon's duration. Hence, the // data invariant is extended as follows: // // `t2m`(`T_START`) ≤ `now` ≤ `t2m`(`T_END`) → `moment_computed`(`now`) var now; // To ensure this data invariant, `now` is set to a moment before the // phenomenon started. now = t2m(T_START) - 1; // ## Inspecting and running a model // Inspection through registerd views var views = []; var update_views = function() { var update_view = function(view) { view.update(_model.name); }; views.forEach(update_view); }; _model.update_views = update_views; var update_all_views = function() { var update_view = function(view) { if (view.update_all) { view.update_all(); } else { view.update(_model.name); } }; views.forEach(update_view); }; _model.update_all_views = update_all_views; _model.register = function(view) { var view_found = views.indexOf(view); if (view_found === -1) { views.push(view); views.forEach(function(v) { if(v.update_all) v.update_all();}); } }; _model.get_views_of_type = function(view_type) { return views.filter(function(v) { return v.type === view_type; }); }; _model.unregister = function(view) { if (arguments.length === 0) { var unregister = function(view) { view.unregister(_model.name); }; views.forEach(unregister); } else { var view_found = views.indexOf(view); if (view_found !== -1) { views.slice(view_found, 1); } } }; // As a model can be inspected repeatedly, as is one // of the reasons to model a phenomenon using a computer, we introduce a // `reset` function to resets `now` to a moment before the phenomenon // started. _model.reset = function() { now = t2m(T_START) - 1; _model.step(); update_views(); }; // Once a model has been started, the current moment will be measured as // well as all moments before since the start. These moments can be // inspected. // _model.has_started = function() { return now >= 0; }; // The `step` function will advance `now` to the next moment if the end of // the phenomenon has not been reached yet. If that moment has not been // "measured" earlier, "measure" it now. _model.step = function(do_not_update_views) { if (m2t(now) + T_STEP <= T_END) { now++; if (!_model.moment_measured(now)) { var moment = _model.measure_moment(now); moment._time_ = m2t(now); moments.push(moment); } } if (!do_not_update_views) { update_views(); } return now; }; // If the phenomenon is a finite process or the "measuring" process cannot // go further `T_END` will have a value that is not `Infinity`. _model.can_finish = function() { return Math.abs(T_END) !== Infinity; }; // To inspect the whole phenomenon at once or inspect the last moment, // `finish`ing the model will ensure that all moments during the // phenomenon have been "measured". _model.finish = function() { var DO_NOT_UPDATE_VIEWS = true; if (_model.can_finish()) { while ((moments.length - 1) < t2m(T_END)) { _model.step(DO_NOT_UPDATE_VIEWS); } } now = moments.length - 1; _model.update_views(); return now; }; // We call the model finished if the current moment, or `now`, is the // phenomenon's last moment. _model.is_finished = function() { return _model.can_finish() && m2t(now) >= T_END; }; function reset_model() { moments = []; _model.action("reset").callback(_model)(); // _model.reset(); } _model.reset_model = reset_model; /** * ## Actions on the model * */ _model.actions = {}; _model.add_action = function( action ) { _model.actions[action.name] = action; _model.actions[action.name].install = function() { return action.callback(_model); }; }; if (config.actions) { var add_action = function(action_name) { _model.add_action(config.actions[action_name]); }; Object.keys(config.actions).forEach(add_action); } _model.action = function( action_name ) { if (_model.actions[action_name]) { return _model.actions[action_name]; } }; _model.remove_action = function( action ) { if (_model.actions[action.name]) { delete _model.actions[action.name]; } }; _model.disable_action = function( action_name ) { if (_model.actions[action_name]) { _model.actions[action_name].enabled = false; } }; _model.enable_action = function( action_name ) { if (_model.actions[action_name]) { _model.actions[action_name].enabled = true; } }; _model.toggle_action = function( action_name ) { if (_model.actions[action_name]) { _model.actions[action_name].enabled = !_model.action[action_name].enabled; } }; // ## Coordinating quantities // // All quantities that describe the phenomenon being modeled change in // coordination with time's change. Add the model's time as a quantity to // the list with quantities. To allow people to model time as part of // their model, for example to describe the phenomenon accelerated, the // internal time is added as quantity `_time_` and, as a result, "_time_" // is not allowed as a quantity name. _model.quantities = config.quantities || {}; _model.quantities._time_ = { hidden: true, minimum: T_START, maximum: T_END, value: m2t(now), stepsize: T_STEP, unit: "ms", label: "internal time", monotone: true }; _model.get_minimum = function(quantity) { if (arguments.length===0) { // called without any arguments: return all minima var minima = {}, add_minimum = function(quantity) { minima[quantity] = parseFloat(_model.quantities[quantity].minimum); }; Object.keys(_model.quantities).forEach(add_minimum); return minima; } else { // return quantity's minimum return parseFloat(_model.quantities[quantity].minimum); } }; _model.get_maximum = function(quantity) { if (arguments.length===0) { // called without any arguments: return all minima var maxima = {}, add_maximum = function(quantity) { maxima[quantity] = parseFloat(_model.quantities[quantity].maximum); }; Object.keys(_model.quantities).forEach(add_maximum); return maxima; } else { // return quantity's minimum return parseFloat(_model.quantities[quantity].maximum); } }; _model.find_moment = function(quantity, value, EPSILON) { if (moments.length === 0) { // no moment are measured yet, so there is nothing to be found return -1; } else { var val = _appendix.quantity_value(quantity); // pre: quantity is monotone // determine if it is increasing or decreasing // determine type of monotone // // As the first moment has been measured and we do know the // minimum of this quantity, type of monotone follows. var start = val(0), INCREASING = (start !== _model.get_maximum(quantity)); // Use a stupid linear search to find the moment that approaches the // value best var m = 0, n = moments.length - 1, lowerbound, upperbound; if (INCREASING) { lowerbound = function(moment) { return val(moment) < value; }; upperbound = function(moment) { return val(moment) > value; }; } else { lowerbound = function(moment) { return val(moment) > value; }; upperbound = function(moment) { return val(moment) < value; }; } // Increasing "function", meaning // // (∀m: 0 ≤ m < |`moments`|: `val`(m) <= `val`(m+1)) // // Therefore, // // (∃m, n: 0 ≤ m < n ≤ |`moments`|: // `val`(m) ≤ value ≤ `val`(n) ⋀ // (∀p: m < p < n: `val`(p) = value)) // // `find_moment` finds those moments m and n and returns the // one closest to value or, when even close, the last moment // decreasing is reverse. while (lowerbound(m)) { m++; if (m>n) { // return -1; } } return m; //m--; /* while (upperbound(n)) { n--; if (n<m) { return -1; } } //n++; return (Math.abs(val(n)-value) < Math.abs(val(m)-value))?n:m; */ } }; _model.get = function(quantity) { if (now < 0) { return undefined; } else { return moments[now][quantity]; } }; _model.set = function(quantity, value) { var q = _model.quantities[quantity]; if (value < parseFloat(q.minimum)) { value = parseFloat(q.minimum); } else if (value > parseFloat(q.maximum)) { value = parseFloat(q.maximum); } // q.minimum ≤ value ≤ q.maximum // has value already been "measured"? // As some quantities can have the same value more often, there are // potentially many moments that fit the bill. There can be an unknown // amount of moments that aren't measured as well. // // However, some quantities will be strictly increasing or decreasing // and no value will appear twice. For example, the internal time will // only increase. Those quantities with property `monotone` // `true`, only one value will be searched for var approx = _appendix.approximates(), moment = -1; if (q.monotone) { moment = _model.find_moment(quantity, value); if (moment === -1) { // not yet "measured" var DO_NOT_UPDATE_VIEWS = true; _model.step(DO_NOT_UPDATE_VIEWS); // THIS DOES WORK ONLY FOR INCREASING QUANTITIES. CHANGE THIS // ALTER WITH FIND FUNCTION !!!! while((moments[now][quantity] < value) && !_model.is_finished()) { _model.step(DO_NOT_UPDATE_VIEWS); } } else { now = moment; } update_views(); return moments[now]; } }; _model.data = function() { return moments.slice(0, now + 1); }; _model.current_moment = function(moment_only) { if (moment_only) { return now; } else { return moments[now]; } }; _model.graphs_shown = { tailpoints: false, line: false, arrows: false }; _model.show_graph = function(kind) { var graphs = _model.get_views_of_type("graph"); function show_this_graph(g) { switch(kind) { case "line": g.show_line(_model.name); break; case "tailpoints": g.show_tailpoints(_model.name); break; case "arrows": g.show_arrows(_model.name); break; } } graphs.forEach(show_this_graph); _model.graphs_shown[kind] = true; }; _model.hide_graph = function(kind) { var graphs = _model.get_views_of_type("graph"); function hide_this_graph(g) { switch(kind) { case "line": g.hide_line(_model.name); break; case "tailpoints": g.hide_tailpoints(_model.name); break; case "arrows": g.hide_arrows(_model.name); break; } } graphs.forEach(hide_this_graph); _model.graphs_shown[kind] = false; }; _model.graph_is_shown = function(kind) { return _model.graphs_shown[kind]; }; // ## _appendix H: helper functions _appendix.approximates = function(epsilon) { var EPSILON = epsilon || 0.001, fn = function(a, b) { return Math.abs(a - b) <= EPSILON; }; fn.EPSILON = EPSILON; return fn; }; _appendix.quantity_value = function(quantity) { return function(moment) { return moments[moment][quantity]; }; }; var step = (config.step_size || T_STEP)*5 ; function step_size(size) { if (arguments.length === 1) { step = size; } return step; } _model.step_size = step_size; function random_color() { var hexes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'], colors = [], i = 0; while (i < 6) { colors.push(hexes[Math.round(Math.random()*(hexes.length - 1))]); i++; } return "#"+ colors.join(""); } var color = random_color(); _model.color = function(c) { if (arguments.length === 1) { if (c === "random") { color = random_color(); } else { color = c; } } return color; }; return _model; }; module.exports = model;
htdebeer/PhD-DE3
src/models/model.js
JavaScript
gpl-3.0
19,172
///////////////////////////////////////////////////////////////////////////// // C# Version Copyright (c) 2003 CenterSpace Software, LLC // // // // This code is free software under the Artistic license. // // // // CenterSpace Software // // 2098 NW Myrtlewood Way // // Corvallis, Oregon, 97330 // // USA // // http://www.centerspace.net // ///////////////////////////////////////////////////////////////////////////// /* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not 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. Any feedback is very welcome. http://www.math.keio.ac.jp/matumoto/emt.html email: matumoto@math.keio.ac.jp */ using System; namespace CenterSpace.Free { /// <summary> /// Class MersenneTwister generates random numbers from a uniform distribution using /// the Mersenne Twister algorithm. /// </summary> /// <remarks>Caution: MT is for MonteCarlo, and is NOT SECURE for CRYPTOGRAPHY /// as it is.</remarks> public class MersenneTwister { #region Constants ------------------------------------------------------- // Period parameters. private const int N = 624; private const int M = 397; private const uint MATRIX_A = 0x9908b0dfU; // constant vector a private const uint UPPER_MASK = 0x80000000U; // most significant w-r bits private const uint LOWER_MASK = 0x7fffffffU; // least significant r bits private const int MAX_RAND_INT = 0x7fffffff; #endregion Constants #region Instance Variables ---------------------------------------------- // mag01[x] = x * MATRIX_A for x=0,1 private uint[] mag01 = {0x0U, MATRIX_A}; // the array for the state vector private uint[] mt = new uint[N]; // mti==N+1 means mt[N] is not initialized private int mti = N+1; #endregion Instance Variables #region Constructors ---------------------------------------------------- /// <summary> /// Creates a random number generator using the time of day in milliseconds as /// the seed. /// </summary> public MersenneTwister() { init_genrand( (uint)DateTime.Now.Millisecond ); } /// <summary> /// Creates a random number generator initialized with the given seed. /// </summary> /// <param name="seed">The seed.</param> public MersenneTwister( int seed ) { init_genrand( (uint)seed ); } /// <summary> /// Creates a random number generator initialized with the given array. /// </summary> /// <param name="init">The array for initializing keys.</param> public MersenneTwister( int[] init ) { uint[] initArray = new uint[init.Length]; for ( int i = 0; i < init.Length; ++i ) initArray[i] = (uint)init[i]; init_by_array( initArray, (uint)initArray.Length ); } #endregion Constructors #region Properties ------------------------------------------------------ /// <summary> /// Gets the maximum random integer value. All random integers generated /// by instances of this class are less than or equal to this value. This /// value is <c>0x7fffffff</c> (<c>2,147,483,647</c>). /// </summary> public static int MaxRandomInt { get { return 0x7fffffff; } } #endregion Properties #region Member Functions ------------------------------------------------ /// <summary> /// Returns a random integer greater than or equal to zero and /// less than or equal to <c>MaxRandomInt</c>. /// </summary> /// <returns>The next random integer.</returns> public int Next() { return genrand_int31(); } /// <summary> /// Returns a positive random integer less than the specified maximum. /// </summary> /// <param name="maxValue">The maximum value. Must be greater than zero.</param> /// <returns>A positive random integer less than or equal to <c>maxValue</c>.</returns> public int Next( int maxValue ) { return Next( 0, maxValue ); } /// <summary> /// Returns a random integer within the specified range. /// </summary> /// <param name="minValue">The lower bound.</param> /// <param name="maxValue">The upper bound.</param> /// <returns>A random integer greater than or equal to <c>minValue</c>, and less than /// or equal to <c>maxValue</c>.</returns> public int Next( int minValue, int maxValue ) { if ( minValue > maxValue ) { int tmp = maxValue; maxValue = minValue; minValue = tmp; } return (int)( Math.Floor((maxValue-minValue+1)*genrand_real1() + minValue) ); } /// <summary> /// Returns a random number between 0.0 and 1.0. /// </summary> /// <returns>A single-precision floating point number greater than or equal to 0.0, /// and less than 1.0.</returns> public float NextFloat() { return (float) genrand_real2(); } /// <summary> /// Returns a random number greater than or equal to zero, and either strictly /// less than one, or less than or equal to one, depending on the value of the /// given boolean parameter. /// </summary> /// <param name="includeOne"> /// If <c>true</c>, the random number returned will be /// less than or equal to one; otherwise, the random number returned will /// be strictly less than one. /// </param> /// <returns> /// If <c>includeOne</c> is <c>true</c>, this method returns a /// single-precision random number greater than or equal to zero, and less /// than or equal to one. If <c>includeOne</c> is <c>false</c>, this method /// returns a single-precision random number greater than or equal to zero and /// strictly less than one. /// </returns> public float NextFloat( bool includeOne ) { if ( includeOne ) { return (float) genrand_real1(); } return (float) genrand_real2(); } /// <summary> /// Returns a random number greater than 0.0 and less than 1.0. /// </summary> /// <returns>A random number greater than 0.0 and less than 1.0.</returns> public float NextFloatPositive() { return (float) genrand_real3(); } /// <summary> /// Returns a random number between 0.0 and 1.0. /// </summary> /// <returns>A double-precision floating point number greater than or equal to 0.0, /// and less than 1.0.</returns> public double NextDouble() { return genrand_real2(); } /// <summary> /// Returns a random number greater than or equal to zero, and either strictly /// less than one, or less than or equal to one, depending on the value of the /// given boolean parameter. /// </summary> /// <param name="includeOne"> /// If <c>true</c>, the random number returned will be /// less than or equal to one; otherwise, the random number returned will /// be strictly less than one. /// </param> /// <returns> /// If <c>includeOne</c> is <c>true</c>, this method returns a /// single-precision random number greater than or equal to zero, and less /// than or equal to one. If <c>includeOne</c> is <c>false</c>, this method /// returns a single-precision random number greater than or equal to zero and /// strictly less than one. /// </returns> public double NextDouble( bool includeOne ) { if ( includeOne ) { return genrand_real1(); } return genrand_real2(); } /// <summary> /// Returns a random number greater than 0.0 and less than 1.0. /// </summary> /// <returns>A random number greater than 0.0 and less than 1.0.</returns> public double NextDoublePositive() { return genrand_real3(); } /// <summary> /// Generates a random number on <c>[0,1)</c> with 53-bit resolution. /// </summary> /// <returns>A random number on <c>[0,1)</c> with 53-bit resolution</returns> public double Next53BitRes() { return genrand_res53(); } /// <summary> /// Reinitializes the random number generator using the time of day in /// milliseconds as the seed. /// </summary> public void Initialize() { init_genrand( (uint)DateTime.Now.Millisecond ); } /// <summary> /// Reinitializes the random number generator with the given seed. /// </summary> /// <param name="seed">The seed.</param> public void Initialize( int seed ) { init_genrand( (uint)seed ); } /// <summary> /// Reinitializes the random number generator with the given array. /// </summary> /// <param name="init">The array for initializing keys.</param> public void Initialize( int[] init ) { uint[] initArray = new uint[init.Length]; for ( int i = 0; i < init.Length; ++i ) initArray[i] = (uint)init[i]; init_by_array( initArray, (uint)initArray.Length ); } #region Methods ported from C ------------------------------------------- // initializes mt[N] with a seed private void init_genrand( uint s) { mt[0]= s & 0xffffffffU; for (mti=1; mti<N; mti++) { mt[mti] = (uint)(1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); // See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. // In the previous versions, MSBs of the seed affect // only MSBs of the array mt[]. // 2002/01/09 modified by Makoto Matsumoto mt[mti] &= 0xffffffffU; // for >32 bit machines } } // initialize by an array with array-length // init_key is the array for initializing keys // key_length is its length private void init_by_array(uint[] init_key, uint key_length) { int i, j, k; init_genrand(19650218U); i=1; j=0; k = (int)(N>key_length ? N : key_length); for (; k>0; k--) { mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U)) + init_key[j] + j); /* non linear */ mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=key_length) j=0; } for (k=N-1; k>0; k--) { mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))- i); /* non linear */ mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000U; // MSB is 1; assuring non-zero initial array } // generates a random number on [0,0xffffffff]-interval uint genrand_int32() { uint y; if (mti >= N) { /* generate N words at one time */ int kk; if (mti == N+1) /* if init_genrand() has not been called, */ init_genrand(5489U); /* a default initial seed is used */ for (kk=0;kk<N-M;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U]; } for (;kk<N-1;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U]; mti = 0; } y = mt[mti++]; // Tempering y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680U; y ^= (y << 15) & 0xefc60000U; y ^= (y >> 18); return y; } // generates a random number on [0,0x7fffffff]-interval private int genrand_int31() { return (int)(genrand_int32()>>1); } // generates a random number on [0,1]-real-interval double genrand_real1() { return genrand_int32()*(1.0/4294967295.0); // divided by 2^32-1 } // generates a random number on [0,1)-real-interval double genrand_real2() { return genrand_int32()*(1.0/4294967296.0); // divided by 2^32 } // generates a random number on (0,1)-real-interval double genrand_real3() { return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); // divided by 2^32 } // generates a random number on [0,1) with 53-bit resolution double genrand_res53() { uint a=genrand_int32()>>5, b=genrand_int32()>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } // These real versions are due to Isaku Wada, 2002/01/09 added #endregion Methods ported from C #endregion Member Functions } }
bashrc/sentience
sentcore/MersenneTwister.cs
C#
gpl-3.0
15,228
package main import ( "net/http" "os" "path" "strings" "github.com/zenazn/goji/web" ) func fileServeHandler(c web.C, w http.ResponseWriter, r *http.Request) { fileName := c.URLParams["name"] filePath := path.Join(Config.filesDir, fileName) if !fileExistsAndNotExpired(fileName) { notFoundHandler(c, w, r) return } if !Config.allowHotlink { referer := r.Header.Get("Referer") if referer != "" && !strings.HasPrefix(referer, Config.siteURL) { w.WriteHeader(403) return } } w.Header().Set("Content-Security-Policy", Config.fileContentSecurityPolicy) http.ServeFile(w, r, filePath) } func staticHandler(c web.C, w http.ResponseWriter, r *http.Request) { path := r.URL.Path if path[len(path)-1:] == "/" { notFoundHandler(c, w, r) return } else { if path == "/favicon.ico" { path = "/static/images/favicon.gif" } filePath := strings.TrimPrefix(path, "/static/") file, err := staticBox.Open(filePath) if err != nil { notFoundHandler(c, w, r) return } w.Header().Set("Etag", timeStartedStr) w.Header().Set("Cache-Control", "max-age=86400") http.ServeContent(w, r, filePath, timeStarted, file) return } } func fileExistsAndNotExpired(filename string) bool { filePath := path.Join(Config.filesDir, filename) _, err := os.Stat(filePath) if err != nil { return false } if isFileExpired(filename) { os.Remove(path.Join(Config.filesDir, filename)) os.Remove(path.Join(Config.metaDir, filename)) return false } return true }
matthazinski/linx-server
fileserve.go
GO
gpl-3.0
1,505
/****************************************************************************** ******************************************************************************* ******************************************************************************* libferris Copyright (C) 2001 Ben Martin libferris 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. libferris 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 libferris. If not, see <http://www.gnu.org/licenses/>. For more details see the COPYING file in the root directory of this distribution. $Id: libferrispostgresqlshared.cpp,v 1.2 2006/12/07 06:49:42 ben Exp $ ******************************************************************************* ******************************************************************************* ******************************************************************************/ #include "config.h" #include "libferrisgoogle_shared.hh" #include <Ferris/Configuration_private.hh> #include <QNetworkReply> #include <QNetworkAccessManager> #include <QBuffer> #include <Ferris/FerrisQt_private.hh> #include <Ferris/FerrisKDE.hh> #include <Ferris/FerrisDOM.hh> #include <Ferris/FerrisBoost.hh> #include <Ferris/Iterator.hh> #include <Ferris/FerrisKDE.hh> #include <qjson/parser.h> #define DEBUG LG_GOOGLE_D namespace Ferris { using namespace XML; using namespace std; static const string DBNAME = FDB_SECURE; string prettyprintxml( const std::string& s ) { try { fh_domdoc dom = Factory::StringToDOM( s ); fh_stringstream ss = tostream( dom ); return ss.str(); } catch( exception& e ) { return s; } } FERRISEXP_EXPORT userpass_t getGoogleUserPass( const std::string& server ) { string user; string pass; string Key = ""; // server; { stringstream ss; ss << "google" << Key << "-username"; user = getConfigString( DBNAME, tostr(ss), "" ); } { stringstream ss; ss << "google" << Key << "-password"; pass = getConfigString( DBNAME, tostr(ss), "" ); } return make_pair( user, pass ); } FERRISEXP_EXPORT void setGoogleUserPass( const std::string& server, const std::string& user, const std::string& pass ) { string Key = ""; // server; { stringstream ss; ss << "google" << Key << "-username"; setConfigString( DBNAME, tostr(ss), user ); } { stringstream ss; ss << "google" << Key << "-password"; setConfigString( DBNAME, tostr(ss), pass ); } } FERRISEXP_EXPORT std::string columnNumberToName( int col ) { stringstream ss; int aval = 'a'; --aval; ss << (char)(aval + col); string v = ss.str(); return v; } /********************************************************************************/ /********************************************************************************/ /********************************************************************************/ // GoogleClientResponseWaiter::GoogleClientResponseWaiter() // { // m_loop = g_main_loop_new( 0, 0 ); // } // void // GoogleClientResponseWaiter::block() // { // LG_GOOGLE_D << "GoogleClientResponseWaiter::block(top)" << endl; // g_main_loop_run( m_loop ); // LG_GOOGLE_D << "GoogleClientResponseWaiter::block(done)" << endl; // } // void // GoogleClientResponseWaiter::unblock() // { // g_main_loop_quit( m_loop ); // } /********************************************************************************/ /********************************************************************************/ /********************************************************************************/ GoogleClient::GoogleClient() : m_qmanager( 0 ) { } QNetworkAccessManager* GoogleClient::getQManager() { return ::Ferris::getQManager(); // return new QNetworkAccessManager(0); // if( !m_qmanager ) // { // m_qmanager = new QNetworkAccessManager(0); // } // return m_qmanager; } void GoogleClient::addAuth( QNetworkRequest& r, const std::string& service ) { if( m_authTokens[ service ].empty() ) Authenticate_ClientLogin( service ); DEBUG << "Auth token service:" << service << " token:" << m_authTokens[service] << endl; r.setRawHeader("Authorization", m_authTokens[service].c_str() ); } void GoogleClient::dumpReplyToConsole(QNetworkReply* reply ) { m_waiter.unblock( reply ); cerr << "GoogleClient::dumpReplyToConsole()" << endl; cerr << "error:" << reply->error() << endl; cerr << "earl:" << tostr(reply->url().toString()) << endl; QByteArray ba = reply->readAll(); cerr << "ba.sz:" << ba.size() << endl; cerr << "ba:" << (string)ba << endl; cerr << "-------------" << endl; } void GoogleClient::dumpReplyToConsole() { QNetworkReply* reply = (QNetworkReply*)sender(); m_waiter.unblock( reply ); cerr << "GoogleClient::dumpReplyToConsole()" << endl; cerr << "error:" << reply->error() << endl; cerr << "earl:" << tostr(reply->url().toString()) << endl; QByteArray ba = reply->readAll(); cerr << "ba.sz:" << ba.size() << endl; cerr << "ba:" << (string)ba << endl; cerr << "-------------" << endl; } std::string responseToAuthToken( const std::string& data ) { string ret; stringstream ss; ss << data; string s; while( getline(ss,s) ) { // LG_GOOGLE_D << "s:" << s << endl; if( starts_with( s, "Auth=" )) { ret = "GoogleLogin " + s; ret = Util::replace_all( ret, "Auth=", "auth=" ); } } return ret; } void GoogleClient::replyFinished(QNetworkReply* reply ) { m_waiter.unblock( reply ); LG_GOOGLE_D << "-------------" << endl; LG_GOOGLE_D << "GoogleClient::replyFinished(3)" << endl; // m_authToken = responseToAuthToken( (string)reply->readAll() ); // stringstream ss; // ss << reply->readAll().data(); // string s; // while( getline(ss,s) ) // { // // LG_GOOGLE_D << "s:" << s << endl; // if( starts_with( s, "Auth=" )) // { // m_authToken = "GoogleLogin " + s; // } // } // listSheets(); } void GoogleClient::handleFinished() { QNetworkReply* r = dynamic_cast<QNetworkReply*>(sender()); m_waiter.unblock(r); LG_GOOGLE_D << "GoogleClient::handleFinished()" << endl; } void GoogleClient::handleFinished( QNetworkReply* r ) { m_waiter.unblock(r); LG_GOOGLE_D << "GoogleClient::handleFinished(QNR)" << endl; } void GoogleClient::localtest() { QNetworkAccessManager* qm = getQManager(); QNetworkRequest request; request.setUrl(QUrl("http://alkid")); request.setRawHeader("User-Agent", "MyOwnBrowser 1.0"); cerr << "getting reply..." << endl; connect( qm, SIGNAL(finished(QNetworkReply*)), SLOT(dumpReplyToConsole(QNetworkReply*))); QNetworkReply *reply = qm->get(request); QUrl postdata("https://www.google.com/accounts/ClientLogin"); postdata.addQueryItem("accountType", "HOSTED_OR_GOOGLE"); // connect( reply, SIGNAL( finished() ), SLOT( dumpReplyToConsole() ) ); m_waiter.block(reply); } void GoogleClient::Authenticate_ClientLogin( const std::string& service ) { userpass_t up = getGoogleUserPass(); std::string username = up.first; std::string password = up.second; QNetworkAccessManager* qm = getQManager(); QNetworkRequest request; QUrl postdata("https://www.google.com/accounts/ClientLogin"); postdata.addQueryItem("accountType", "HOSTED_OR_GOOGLE"); postdata.addQueryItem("Email", username.c_str() ); postdata.addQueryItem("Passwd", password.c_str() ); postdata.addQueryItem("service", service.c_str() ); postdata.addQueryItem("source", "libferris" FERRIS_VERSION); request.setUrl(postdata); connect( qm, SIGNAL(finished(QNetworkReply*)), SLOT(handleFinished(QNetworkReply*))); LG_GOOGLE_D << "postdata.toEncoded():" << tostr(QString(postdata.toEncoded())) << endl; LG_GOOGLE_D << "getting reply...2" << endl; QByteArray empty; QNetworkReply *reply = qm->post( request, empty ); m_waiter.block(reply); string token = responseToAuthToken( (string)reply->readAll() ); LG_GOOGLE_D << "service:" << service << " token:" << token << endl; m_authTokens[service] = token; } QNetworkReply* GoogleClient::get( QNetworkRequest req ) { QNetworkAccessManager* qm = getQManager(); QNetworkReply* reply = qm->get( req ); connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) ); m_waiter.block(reply); return reply; } QNetworkReply* GoogleClient::put( QNetworkRequest req, QByteArray& ba ) { QNetworkAccessManager* qm = getQManager(); QNetworkReply* reply = qm->put( req, ba ); connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) ); m_waiter.block(reply); return reply; } QNetworkReply* GoogleClient::put( QNetworkRequest req, const std::string& data ) { QByteArray ba( data.data(), data.size() ); return put( req, ba ); } QNetworkReply* GoogleClient::post( QNetworkRequest req, const std::string& data ) { QNetworkAccessManager* qm = getQManager(); QNetworkReply* reply = qm->post( req, data.c_str() ); connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) ); m_waiter.block(reply); return reply; } QNetworkRequest GoogleClient::createRequest( QUrl& u, const std::string& service, const std::string& gversion ) { QNetworkRequest req; addAuth( req, service ); if( !gversion.empty() ) req.setRawHeader("GData-Version", gversion.c_str() ); req.setUrl(u); return req; } std::string GoogleClient::getYoutubeDevKey() { return getStrSubCtx( "~/.ferris/youtube-dev-key.txt", "" ); } FERRISEXP_API std::list< DOMElement* > getAllChildrenElementsWithAttribute( DOMNode* node, const std::string& name, const std::string& attr, const std::string& value, bool recurse = true ); FERRISEXP_API DOMElement* getFirstChildElementsWithAttribute( DOMNode* node, const std::string& name, const std::string& attrname, const std::string& value, bool recurse = true ); FERRISEXP_API std::list< DOMElement* > getAllChildrenElementsWithAttribute( DOMNode* node, const std::string& name, const std::string& attrname, const std::string& value, bool recurse ) { typedef std::list< DOMElement* > LIST; LIST l = getAllChildrenElements( node, name, recurse ); LIST ret; for( LIST::iterator li = l.begin(); li != l.end(); ++li ) { DOMElement* e = *li; std::string s = getAttribute( e, attrname ); // cerr << "value:" << value << " s:" << s << endl; if( s == value ) { // cerr << "match!" << endl; ret.push_back( e ); } } // cerr << "ret.sz:" << ret.size() << endl; return ret; } FERRISEXP_API DOMElement* getFirstChildElementsWithAttribute( DOMNode* node, const std::string& name, const std::string& attrname, const std::string& value, bool recurse ) { DOMElement* ret = 0; std::list< DOMElement* > l = getAllChildrenElementsWithAttribute( node, name, attrname, value, recurse ); if( !l.empty() ) ret = l.front(); return ret; } std::string getMatchingAttribute( DOMNode* node, const std::string& name, const std::string& attrname, const std::string& value, const std::string& desiredAttribute ) { DOMElement* e = getFirstChildElementsWithAttribute( node, name, attrname, value ); if( e ) { return getAttribute( e, desiredAttribute ); } return ""; } typedef std::list< DOMElement* > entries_t; GoogleSpreadSheets_t GoogleClient::listSheets() { LG_GOOGLE_D << "running listSheets...." << endl; QUrl u("http://spreadsheets.google.com/feeds/spreadsheets/private/full"); QNetworkRequest request = createRequest( u ); QNetworkReply *reply = get( request ); LG_GOOGLE_D << "after running listSheets...." << endl; QByteArray ba = reply->readAll(); LG_GOOGLE_D << "spreadsheets error:" << reply->error() << endl; LG_GOOGLE_D << "spreadsheets reply:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); GoogleSpreadSheets_t ret; for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { fh_GoogleSpreadSheet t = new GoogleSpreadSheet( this, dom, *ei ); ret.push_back(t); } return ret; } fh_GoogleDocumentFolder GoogleClient::getRootFolder() { DEBUG << "GoogleClient::getRootFolder...." << endl; fh_GoogleDocumentFolder ret = new GoogleDocumentFolder( this, "" ); return ret; } GoogleDocuments_t GoogleClient::listDocuments() { LG_GOOGLE_D << "running listDocuments...." << endl; QUrl u("http://docs.google.com/feeds/documents/private/full"); QNetworkRequest request = createRequest( u, "writely" ); request.setRawHeader("GData-Version", " 2.0"); QNetworkReply *reply = get( request ); LG_GOOGLE_D << "after running listDocuments...." << endl; QByteArray ba = reply->readAll(); LG_GOOGLE_D << "docs error:" << reply->error() << endl; LG_GOOGLE_D << "docs reply:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); m_documentsETag = getAttribute( dom->getDocumentElement(), "gd:etag" ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); if( LG_GOOGLE_D_ACTIVE ) { fh_stringstream ss = tostream( dom ); LG_GOOGLE_D << "Documents:" << ss.str() << endl; LG_GOOGLE_D << "m_documentsETag:" << m_documentsETag << endl; } GoogleDocuments_t ret; for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { fh_GoogleDocument t = new GoogleDocument( this, dom, *ei ); ret.push_back(t); } // // Have to get all the folder names to get the top level ones :( // GET /feeds/documents/private/full/-/folder?showfolders=true // { request.setUrl( QUrl( "http://docs.google.com/feeds/documents/private/full/-/folder?showfolders=true" )); QNetworkReply *reply = get( request ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "docs folders error:" << reply->error() << endl; LG_GOOGLE_D << "docs folders reply:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { fh_GoogleDocument t = new GoogleDocument( this, dom, *ei ); ret.push_back(t); } } // // GET /feeds/documents/private/full/-/folder?showfolders=true // { // QUrl u("http://docs.google.com/feeds/documents/private/full/-/folder?showfolders=true"); // QNetworkRequest request = createRequest( u, "writely" ); // request.setRawHeader("GData-Version", " 2.0"); // QNetworkReply *reply = get( request ); // LG_GOOGLE_D << "after running listDocuments...." << endl; // QByteArray ba = reply->readAll(); // LG_GOOGLE_D << "docs error:" << reply->error() << endl; // fh_domdoc dom = Factory::StringToDOM( (string)ba ); // fh_stringstream ss = tostream( dom ); // LG_GOOGLE_D << "Folders:" << ss.str() << endl; // } // GET http://docs.google.com/feeds/folders/private/full/folder%3Afolder_id { LG_GOOGLE_D << "------------------------------------------------------------------------" << endl; // QUrl u("http://docs.google.com/feeds/folders/private/full/folder%3A1d90eb20-cad4-4bf3-b4d7-0ff8ddf3448d"); QUrl u("http://docs.google.com/feeds/folders/private/full/folder%3Abe4824a5-8b8f-4129-9b33-5c5f3c1cdb57?showfolders=true"); QNetworkRequest request = createRequest( u, "writely" ); request.setRawHeader("GData-Version", " 2.0"); QNetworkReply* reply = get( request ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "x error:" << reply->error() << endl; LG_GOOGLE_D << "x reply:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); fh_stringstream ss = tostream( dom ); LG_GOOGLE_D << "DATA:" << ss.str() << endl; } return ret; } fh_YoutubeUpload GoogleClient::createYoutubeUpload() { return new YoutubeUpload( this ); } /****************************************/ /****************************************/ /****************************************/ // This is for the root directory... GoogleDocumentFolder::GoogleDocumentFolder( fh_GoogleClient gc, const std::string& folderID ) : m_gc( gc ), m_haveRead( false ), m_folderID( folderID ) { } GoogleDocumentFolder::GoogleDocumentFolder( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e ) : m_gc( gc ), m_haveRead( false ) { m_title = getStrSubCtx( e, "title" ); m_editURL = getMatchingAttribute( e, "link", "rel", "edit", "href" ); m_folderID = getStrSubCtx( e, "id" ); m_folderID = m_folderID.substr( m_folderID.length() - strlen("fac1125b-6dc7-4e79-8ef2-7dc1c8b4c9b8")); // m_folderID = Util::replace_all( m_folderID, // "http://docs.google.com/feeds/documents/private/full/folder%3A", // "" ); } // <category label="spreadsheet" scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/docs/2007#spreadsheet"/> void GoogleDocumentFolder::addItem( fh_domdoc dom, DOMElement* e ) { string kind = getMatchingAttribute( e, "category", "scheme", "http://schemas.google.com/g/2005#kind", "label" ); DEBUG << "kind:" << kind << endl; if( kind == "folder" ) { fh_GoogleDocumentFolder f = new GoogleDocumentFolder( m_gc, dom, e ); m_folders.push_back(f); } else { fh_GoogleDocument d = new GoogleDocument( m_gc, dom, e ); m_docs.push_back(d); } } void GoogleDocumentFolder::read( bool force ) { DEBUG << "read() title:" << m_title << " folderID:" << m_folderID << endl; GoogleDocumentFolders_t ret; if( m_haveRead ) return; m_haveRead = true; // // Have to get all the folder names to get the top level ones :( // GET /feeds/documents/private/full/-/folder?showfolders=true // if( m_folderID.empty() ) { QUrl u("http://docs.google.com/feeds/documents/private/full?showfolders=true"); QNetworkRequest request = m_gc->createRequest( u, "writely" ); request.setRawHeader("GData-Version", " 2.0"); QNetworkReply *reply = m_gc->get( request ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "docs folders error:" << reply->error() << endl; LG_GOOGLE_D << "docs folders reply:" << (string)ba << endl; if( reply->error() == 0 ) { fh_domdoc dom = Factory::StringToDOM( (string)ba ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { DOMElement* e = *ei; string p = getMatchingAttribute( e, "link", "rel", "http://schemas.google.com/docs/2007#parent", "href" ); if( p.empty() ) { addItem( dom, *ei ); } } if( LG_GOOGLE_D_ACTIVE ) { fh_stringstream ss = tostream( dom ); LG_GOOGLE_D << "TOP FOLDER....:" << ss.str() << endl; } } } else { stringstream uss; uss << "http://docs.google.com/feeds/folders/private/full/folder%3A" << m_folderID << "?showfolders=true"; QUrl u(uss.str().c_str()); QNetworkRequest request = m_gc->createRequest( u, "writely" ); request.setRawHeader("GData-Version", " 2.0"); QNetworkReply* reply = m_gc->get( request ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "x error:" << reply->error() << endl; LG_GOOGLE_D << "x reply:" << (string)ba << endl; if( reply->error() == 0 ) { fh_domdoc dom = Factory::StringToDOM( (string)ba ); fh_stringstream ss = tostream( dom ); LG_GOOGLE_D << "DATA:" << ss.str() << endl; entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { addItem( dom, *ei ); } } } } GoogleDocumentFolders_t GoogleDocumentFolder::getSubFolders() { read(); return m_folders; } GoogleDocuments_t GoogleDocumentFolder::getDocuments() { read(); return m_docs; } std::string GoogleDocumentFolder::getEditURL() { return m_editURL; } std::string GoogleDocumentFolder::getTitle() { return m_title; } fh_GoogleDocument GoogleDocumentFolder::createDocument( const std::string& data, const std::string& slug, const std::string& format ) { fh_GoogleDocument ret = new GoogleDocument( m_gc, data, slug, format ); return ret; } /****************************************/ /****************************************/ /****************************************/ GoogleDocument::GoogleDocument( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e ) : m_gc( gc ), m_haveRead( false ) { m_title = getStrSubCtx( e, "title" ); m_editURL = getMatchingAttribute( e, "link", "rel", "edit", "href" ); m_docID = getStrSubCtx( e, "gd:resourceId" ); m_docID = Util::replace_all( m_docID, "document:", "" ); } GoogleDocument::GoogleDocument( fh_GoogleClient gc, const std::string& data, const std::string& slug, const std::string& format ) : m_gc(gc), m_haveRead( false ) { QNetworkRequest request = prepareCreateOrReplace( data, slug, format, true ); QNetworkReply* reply = m_gc->post( request, data.c_str() ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "create doc error code:" << reply->error() << endl; LG_GOOGLE_D << "create doc reply:" << (string)ba << endl; } std::string GoogleDocument::getEditURL() { return m_editURL; } std::string GoogleDocument::getTitle() { return m_title; } fh_istream GoogleDocument::exportToFormat( const std::string& format ) { DEBUG << "exportToFormat() m_docID:" << m_docID << endl; QUrl u( "http://docs.google.com/feeds/download/documents/Export" ); u.addQueryItem("docID", m_docID.c_str() ); u.addQueryItem("exportFormat", format.c_str() ); LG_GOOGLE_D << "export args:" << tostr(QString(u.toEncoded())) << endl; QNetworkRequest request = m_gc->createRequest( u, "writely", "" ); QNetworkReply *reply = m_gc->get( request ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "export error:" << reply->error() << endl; LG_GOOGLE_D << "export reply:" << (string)ba << endl; fh_stringstream ret; ret.write( ba.data(), ba.size() ); ret->clear(); ret->seekg(0, ios::beg); ret->seekp(0, ios::beg); ret->clear(); return ret; } string filenameToContentType( const std::string& slug_const, const std::string& format, const std::string& data = "" ) { string slug = tolowerstr()( slug_const ); // 299, update reply:Content-Type application/vnd.oasis.opendocument.spreadsheet is not a valid input type. string ret = "text/plain"; if( format == "xx" || ends_with( slug, "xx" ) ) ret = "application/vnd.ms-excel"; else if( format == "xls" || ends_with( slug, "xls" ) ) ret = "application/vnd.ms-excel"; else if( format == "doc" || ends_with( slug, "doc" ) ) ret = "application/msword"; else if( format == "odt" || ends_with( slug, "odt" ) ) ret = "application/vnd.oasis.opendocument.text"; else if( format == "ods" || ends_with( slug, "ods" ) ) ret = "application/vnd.oasis.opendocument.spreadsheet"; else if( ends_with( slug, "png" ) ) ret = "image/png"; else if( ends_with( slug, "pdf" ) ) ret = "application/pdf"; else { string mt = regex_match_single( data, ".*mimetypeapplication/([^P]+)PK.*" ); if( !mt.empty() ) ret = "application/" + mt; } return ret; } QNetworkRequest GoogleDocument::prepareCreateOrReplace( const std::string& data, const std::string& slug, const std::string& format, bool create ) { string ctype = filenameToContentType( slug, format, data ); stringstream uss; if( create ) uss << "http://docs.google.com/feeds/documents/private/full"; else { if( contains( m_docID, "spreadshee" )) uss << "http://docs.google.com/feeds/media/private/full/" << m_docID; else uss << "http://docs.google.com/feeds/media/private/full/document:" << m_docID; } QUrl u( uss.str().c_str() ); QNetworkRequest request = m_gc->createRequest( u, "writely", "" ); request.setHeader( QNetworkRequest::ContentTypeHeader, ctype.c_str() ); request.setHeader( QNetworkRequest::ContentLengthHeader, tostr(data.length()).c_str() ); request.setRawHeader("Content-Type", ctype.c_str() ); // request.setRawHeader("Content-Length", tostr(data.length()).c_str() ); request.setRawHeader("Slug", slug.c_str() ); if( !create ) request.setRawHeader("If-Match", "*" ); DEBUG << "import url:" << tostr(QString(u.toEncoded())) << endl; DEBUG << "slug:" << slug << endl; DEBUG << "ctype:" << ctype << endl; DEBUG << "format:" << format << endl; return request; } void GoogleDocument::importFromFormat( fh_istream iss, const std::string& format ) { DEBUG << "importFromFormat() m_title:" << m_title << endl; string data = StreamToString(iss); QNetworkRequest request = prepareCreateOrReplace( data, m_title, format, false ); DEBUG << "importFromFormat() Calling put..." << endl; QNetworkReply* reply = m_gc->put( request, data ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "update error code:" << reply->error() << endl; LG_GOOGLE_D << "update reply:" << (string)ba << endl; } /****************************************/ /****************************************/ /****************************************/ GoogleSpreadSheet::GoogleSpreadSheet( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e ) : m_gc( gc ), m_haveRead( false ) { m_title = getStrSubCtx( e, "title" ); m_feedURL = getMatchingAttribute( e, "content", "type", "application/atom+xml;type=feed", "src" ); // non versioned data header // m_feedURL = getMatchingAttribute( e, "link", // "rel", "http://schemas.google.com/spreadsheets/2006#worksheetsfeed", // "href" ); } std::string GoogleSpreadSheet::getFeedURL() { return m_feedURL; } std::string GoogleSpreadSheet::getTitle() { return m_title; } GoogleWorkSheets_t GoogleSpreadSheet::listSheets() { LG_GOOGLE_D << "running list WORK Sheets...." << endl; if( m_haveRead ) return m_sheets; QUrl u( getFeedURL().c_str() ); QNetworkRequest request = m_gc->createRequest( u ); QNetworkReply* reply = m_gc->get( request ); LG_GOOGLE_D << "after running list WORK Sheets...." << endl; QByteArray ba = reply->readAll(); LG_GOOGLE_D << "worksheets error:" << reply->error() << endl; LG_GOOGLE_D << "worksheets reply:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { fh_GoogleWorkSheet t = new GoogleWorkSheet( m_gc, dom, *ei ); m_sheets.push_back(t); } return m_sheets; } // void // GoogleSpreadSheet::addDocsAPIAuth_reply(QNetworkReply* reply ) // { // m_gc->m_waiter.unblock(reply); // } // void // GoogleSpreadSheet::addDocsAPIAuth( QNetworkRequest& r ) // { // if( m_docsAPIAuth.empty() ) // { // QNetworkAccessManager* qm = m_gc->getQManager(); // QNetworkRequest request; // userpass_t up = getGoogleUserPass(); // string username = up.first; // string password = up.second; // QUrl postdata("https://www.google.com/accounts/ClientLogin"); // postdata.addQueryItem("accountType", "HOSTED_OR_GOOGLE"); // postdata.addQueryItem("Email", username.c_str() ); // postdata.addQueryItem("Passwd", password.c_str() ); // postdata.addQueryItem("service", "writely"); // postdata.addQueryItem("source", "libferris" FERRIS_VERSION); // request.setUrl(postdata); // connect( qm, SIGNAL(finished(QNetworkReply*)), SLOT(addDocsAPIAuth_reply(QNetworkReply*))); // LG_GOOGLE_D << "GoogleSpreadSheet::addDocsAPIAuth():" << tostr(QString(postdata.toEncoded())) << endl; // LG_GOOGLE_D << "getting reply...2" << endl; // QByteArray empty; // QNetworkReply *reply = qm->post( request, empty ); // LG_GOOGLE_D << "calling block()" << endl; // m_gc->m_waiter.block(reply); // LG_GOOGLE_D << "after block()" << endl; // m_docsAPIAuth = responseToAuthToken( (string)reply->readAll() ); // LG_GOOGLE_D << "m_docsAPIAuth:" << m_docsAPIAuth << endl; // } // r.setRawHeader("Authorization", m_docsAPIAuth.c_str() ); // } string GoogleSpreadSheet::getDocIDFromTitle( const std::string& title ) { // cerr << "FIXME GoogleSpreadSheet::getDocIDFromTitle() " << endl; // return "tz96EupEQKYKTbu3m0GpqTw"; // QUrl u( "http://docs.google.com/feeds/documents/private/full/-/spreadsheet" ); // QNetworkRequest request = m_gc->createRequest( u ); // request.setRawHeader("GData-Version", " 2.0"); QUrl u("http://docs.google.com/feeds/documents/private/full"); QNetworkRequest request; // m_gc->addAuth( request, "wise" ); m_gc->addAuth( request, "writely" ); request.setRawHeader("GData-Version", " 2.0"); request.setUrl(u); LG_GOOGLE_D << "about to issue google docs request..." << endl; QNetworkReply *reply = m_gc->get( request ); LG_GOOGLE_D << "done with google docs request..." << endl; QByteArray ba = reply->readAll(); LG_GOOGLE_D << "getDocIDFromTitle error:" << reply->error() << endl; LG_GOOGLE_D << "getDocIDFromTitle reply:" << (string)ba << endl; string ret; fh_domdoc dom = Factory::StringToDOM( (string)ba ); string etag = getAttribute( dom->getDocumentElement(), "gd:etag" ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { DOMElement* e = *ei; string t = getStrSubCtx( e, "title" ); if( t == title ) { ret = getStrSubCtx( e, "id" ); break; } } LG_GOOGLE_D << "docid ret:" << ret << endl; return ret; } fh_GoogleDocument GoogleSpreadSheet::getDocument() { // getDocIDFromTitle // ( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e ); stringstream uss; uss << "http://docs.google.com/feeds/documents/private/full?" << "title-exact=true&title=" << getTitle(); QUrl u( uss.str().c_str() ); DEBUG << "GoogleSpreadSheet::getDocument() earl:" << uss.str() << endl; QNetworkRequest request = m_gc->createRequest( u, "writely" ); request.setRawHeader("GData-Version", " 2.0"); QNetworkReply *reply = m_gc->get( request ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "docs error:" << reply->error() << endl; LG_GOOGLE_D << "docs reply:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); if( LG_GOOGLE_D_ACTIVE ) { fh_stringstream ss = tostream( dom ); LG_GOOGLE_D << "Documents:" << ss.str() << endl; } for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { fh_GoogleDocument t = new GoogleDocument( m_gc, dom, *ei ); return t; } return 0; } void GoogleSpreadSheet::importFromFormat( fh_istream iss, const std::string& format ) { LG_GOOGLE_D << "GoogleSpreadSheet::importFromFormat() format:" << format << endl; string docid = getDocIDFromTitle( m_title ); LG_GOOGLE_D << "getDocIDFromTitle() title:" << m_title << " docid:" << docid << endl; fh_GoogleDocument doc = getDocument(); doc->importFromFormat( iss, format ); } fh_istream GoogleSpreadSheet::exportToFormat( const std::string& format ) { LG_GOOGLE_D << "GoogleSpreadSheet::exportToFormat() format:" << format << endl; string docid = getDocIDFromTitle( m_title ); LG_GOOGLE_D << "getDocIDFromTitle() title:" << m_title << " docid:" << docid << endl; QUrl u( "http://spreadsheets.google.com/feeds/download/spreadsheets/Export" ); u.addQueryItem("key", docid.c_str() ); u.addQueryItem("exportFormat", format.c_str() ); LG_GOOGLE_D << "exportToFormat, args:" << tostr(QString(u.toEncoded())) << endl; QNetworkRequest request = m_gc->createRequest( u ); QNetworkReply *reply = m_gc->get( request ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "exportToFormat error:" << reply->error() << endl; if( !reply->error() ) LG_GOOGLE_D << "exportToFormat reply.len:" << ba.size() << endl; else LG_GOOGLE_D << "exportToFormat reply:" << (string)ba << endl; { QVariant qv = reply->header( QNetworkRequest::ContentTypeHeader ); DEBUG << "Got ctype:" << tostr(qv.toString()) << endl; // application/vnd.oasis.opendocument.spreadsheet; charset=UTF-8 } fh_stringstream ret; ret.write( ba.data(), ba.size() ); return ret; } fh_GoogleWorkSheet GoogleSpreadSheet::createWorkSheet( const std::string& name ) { LG_GOOGLE_D << "createWorkSheet() top" << endl; stringstream ss; ss << "<entry xmlns=\"http://www.w3.org/2005/Atom\"" << endl << " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">" << endl << " <title>" << name << "</title>" << endl << " <gs:rowCount>100</gs:rowCount>" << endl << " <gs:colCount>100</gs:colCount>" << endl << "</entry>" << endl; QUrl u( getFeedURL().c_str() ); QNetworkRequest request = m_gc->createRequest( u ); request.setHeader( QNetworkRequest::ContentTypeHeader, "application/atom+xml" ); QNetworkReply *reply = m_gc->post( request, ss.str() ); QByteArray ba = reply->readAll(); LG_GOOGLE_D << "createWorkSheet() reply:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); DOMElement* e = dom->getDocumentElement(); fh_GoogleWorkSheet t = new GoogleWorkSheet( m_gc, dom, e ); m_sheets.push_back(t); return t; } /****************************************/ /****************************************/ /****************************************/ GoogleWorkSheet::GoogleWorkSheet( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e ) : m_gc( gc ), m_cellsFetched( false ), m_delayCellSync( false ) { m_etag = getAttribute( e, "gd:etag" ); m_title = getStrSubCtx( e, "title" ); m_cellFeedURL = getMatchingAttribute( e, "link", "rel", "http://schemas.google.com/spreadsheets/2006#cellsfeed", "href" ); m_editURL = getMatchingAttribute( e, "link", "rel", "edit", "href" ); if( LG_GOOGLE_D_ACTIVE ) { fh_stringstream ss = tostream( *e ); LG_GOOGLE_D << "WorkSheet:" << ss.str() << endl; } } std::string GoogleWorkSheet::getCellFeedURL() { return m_cellFeedURL; } std::string GoogleWorkSheet::getTitle() { return m_title; } void GoogleWorkSheet::fetchCells() { QUrl u( getCellFeedURL().c_str() ); QNetworkRequest request = m_gc->createRequest( u ); // If-None-Match: W/"D08FQn8-eil7ImA9WxZbFEw." if( !m_cellFeedETag.empty() ) request.setRawHeader("If-None-Match", m_cellFeedETag.c_str() ); QNetworkReply* reply = m_gc->get( request ); QByteArray ba = reply->readAll(); // cerr << "CELL DATA:" << (string)ba << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); m_cellFeedETag = getAttribute( dom->getDocumentElement(), "gd:etag" ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "entry", false ); int cellURLLength = getCellFeedURL().length(); int header_rownum = 1; int max_headerrow_colnum = 0; for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { DOMElement* e = *ei; fh_GoogleWorkSheetCell cell = new GoogleWorkSheetCell( m_gc, dom, *ei, this, cellURLLength ); LG_GOOGLE_D << "have cell at row:" << cell->row() << " col:" << cell->col() << endl; m_cells_t::iterator ci = m_cells.find( make_pair( cell->row(), cell->col() )); if( ci != m_cells.end() ) { fh_GoogleWorkSheetCell cell = ci->second; cell->update( dom, e, cellURLLength ); } else { m_cells[ make_pair( cell->row(), cell->col() ) ] = cell; } if( cell->row() == header_rownum ) { max_headerrow_colnum = max( max_headerrow_colnum, cell->col() ); } } m_colnames.clear(); LG_GOOGLE_D << "max_headerrow_colnum:" << max_headerrow_colnum << endl; for( int col=1; col <= max_headerrow_colnum; ++col ) { m_cells_t::iterator ci = m_cells.find( make_pair( header_rownum, col )); if( ci != m_cells.end() ) { string v = ci->second->value(); m_colnames[ v ] = col; } string v = columnNumberToName( col ); m_colnames[ v ] = col; LG_GOOGLE_D << " setting col:" << col << " to name:" << v << endl; } for( int col=1; col < 26; ++col ) { string v = columnNumberToName( col ); m_colnames[ v ] = col; } m_cellsFetched = true; } std::list< std::string > GoogleWorkSheet::getColumnNames() { ensureCellsFetched(); std::list< std::string > ret; copy( map_domain_iterator( m_colnames.begin() ), map_domain_iterator( m_colnames.end() ), back_inserter( ret ) ); return ret; } void GoogleWorkSheet::ensureCellsFetched() { if( !m_cellsFetched ) fetchCells(); } fh_GoogleWorkSheetCell GoogleWorkSheet::getCell( int row, int col ) { ensureCellsFetched(); m_cells_t::iterator ci = m_cells.find( make_pair( row, col )); if( ci == m_cells.end() ) { LG_GOOGLE_D << "Creating new cell at row:" << row << " col:" << col << endl; fh_GoogleWorkSheetCell cell = new GoogleWorkSheetCell( m_gc, this, row, col, "" ); m_cells[ make_pair( cell->row(), cell->col() ) ] = cell; return cell; } return ci->second; } fh_GoogleWorkSheetCell GoogleWorkSheet::getCell( int row, const std::string& colName ) { ensureCellsFetched(); int c = m_colnames[ colName ]; LG_GOOGLE_D << "m_colnames.sz:" << m_colnames.size() << " colName:" << colName << " has number:" << c << endl; for( m_colnames_t::iterator ci = m_colnames.begin(); ci != m_colnames.end(); ++ci ) { LG_GOOGLE_D << "ci.first:" << ci->first << " sec:" << ci->second << endl; } return getCell( row, c ); } int GoogleWorkSheet::getLargestRowNumber() { ensureCellsFetched(); int ret = 0; for( m_cells_t::iterator ci = m_cells.begin(); ci != m_cells.end(); ++ci ) { fh_GoogleWorkSheetCell c = ci->second; ret = max( ret, c->row() ); } return ret; } bool GoogleWorkSheet::getDelayCellSync() { return m_delayCellSync; } void GoogleWorkSheet::setDelayCellSync( bool v ) { m_delayCellSync = v; } void GoogleWorkSheet::sync() { if( !getDelayCellSync() ) return; string baseURL = getCellFeedURL(); string fullEditURL = baseURL + "/batch"; stringstream updatess; updatess << "<feed xmlns=\"http://www.w3.org/2005/Atom\"" << endl << " xmlns:batch=\"http://schemas.google.com/gdata/batch\" " << endl << " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\" " << endl << " >" << endl << endl << "<id>" << getCellFeedURL() << "</id> " << endl << endl; for( m_cells_t::iterator ci = m_cells.begin(); ci != m_cells.end(); ++ci ) { fh_GoogleWorkSheetCell c = ci->second; // if( c->isCreated() ) // { // c->sync(); // } // else { c->writeUpdateBlock( updatess ); } } updatess << "</feed>" << endl; QUrl u(fullEditURL.c_str()); QNetworkRequest request = m_gc->createRequest( u ); request.setHeader( QNetworkRequest::ContentTypeHeader, "application/atom+xml" ); if( !m_etag.empty() ) request.setRawHeader("If-Match", "*" ); QNetworkReply* reply = m_gc->post( request, updatess.str() ); cerr << "-------------" << endl; cerr << "m_etag:" << m_etag << endl; cerr << "m_cellFeedETag:" << m_cellFeedETag << endl; cerr << "DST URL:" << fullEditURL << endl; cerr << "SENT2" << endl; cerr << updatess.str() << endl; cerr << "error:" << reply->error() << endl; QByteArray ba = reply->readAll(); cerr << "ba.sz:" << ba.size() << endl; cerr << "ba:" << prettyprintxml( (string)ba ) << endl; cerr << "-------------" << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); entries_t entries = XML::getAllChildrenElements( dom->getDocumentElement(), "atom:entry", false ); int cellURLLength = getCellFeedURL().length(); GoogleSpreadSheets_t ret; for( entries_t::iterator ei = entries.begin(); ei!=entries.end(); ++ei ) { DOMElement* e = *ei; cerr << "have entry..." << endl; DOMElement* x = XML::getChildElement( e, "gs:cell" ); if( x ) { cerr << "have entry/x..." << endl; int row = toint( getAttribute( x, "row" ) ); int col = toint( getAttribute( x, "col" ) ); cerr << "row:" << row << " col:" << col << endl; if( fh_GoogleWorkSheetCell cell = m_cells[ make_pair( row, col ) ] ) cell->update( dom, e, cellURLLength ); } } // // now, update any formula cells // this shouldn't need to be explicit with ETags and feeds // fetchCells(); // for( m_cells_t::iterator ci = m_cells.begin(); ci != m_cells.end(); ++ci ) // { // fh_GoogleWorkSheetCell c = ci->second; // if( c->isFormula() ) // { // } // } } /****************************************/ /****************************************/ /****************************************/ GoogleWorkSheetCell::GoogleWorkSheetCell( fh_GoogleClient gc, fh_domdoc dom, DOMElement* e, fh_GoogleWorkSheet ws, int cellURLLength ) : m_gc( gc ), m_ws( ws ), m_dirty( false ), m_created( false ), m_etag("") { update( dom, e, cellURLLength ); // string editURL = getMatchingAttribute( e, "link", // "rel", "edit", // "href" ); // DOMElement* x = XML::getChildElement( e, "gs:cell" ); // m_value = getStrSubCtx( e, "gs:cell" ); // m_row = toint( getAttribute( x, "row" ) ); // m_col = toint( getAttribute( x, "col" ) ); // m_cellURL = editURL.substr( cellURLLength ); { fh_stringstream ss = tostream( *e ); LG_GOOGLE_D << "CELL:" << ss.str() << endl; } } void GoogleWorkSheetCell::update( fh_domdoc dom, DOMElement* e, int cellURLLength ) { string editURL = getMatchingAttribute( e, "link", "rel", "edit", "href" ); if( editURL.empty() ) editURL = getMatchingAttribute( e, "atom:link", "rel", "edit", "href" ); m_etag = getAttribute( e, "gd:etag" ); DOMElement* x = XML::getChildElement( e, "gs:cell" ); m_value = getStrSubCtx( e, "gs:cell" ); m_row = toint( getAttribute( x, "row" ) ); m_col = toint( getAttribute( x, "col" ) ); m_cellURL = editURL.substr( cellURLLength ); m_isFormula = starts_with( getAttribute( x, "inputValue" ), "=" ); LG_GOOGLE_D << "editURL:" << editURL << endl; LG_GOOGLE_D << "etag:" << m_etag << endl; LG_GOOGLE_D << "m_value:" << m_value << endl; LG_GOOGLE_D << "m_isFormula:" << m_isFormula << endl; } GoogleWorkSheetCell::GoogleWorkSheetCell( fh_GoogleClient gc, fh_GoogleWorkSheet ws, int r, int c, const std::string& v ) : m_gc( gc ), m_ws( ws ), m_created( true ), m_etag("") { m_row = r; m_col = c; m_value = v; { stringstream ss; ss << "/R" << r << "C" << c; m_cellURL = ss.str(); } } bool GoogleWorkSheetCell::isCreated() { return m_created; } bool GoogleWorkSheetCell::isFormula() { return m_isFormula; } int GoogleWorkSheetCell::row() { return m_row; } int GoogleWorkSheetCell::col() { return m_col; } std::string GoogleWorkSheetCell::value() { LG_GOOGLE_D << "reading cell at row:" << m_row << " col:" << m_col << " result:" << m_value << endl; return m_value; } void GoogleWorkSheetCell::writeUpdateBlock( stringstream& ss ) { if( !m_dirty ) return; string fullEditURL = editURL(); if( m_created ) fullEditURL += "/latest"; cerr << "m_etag:" << m_etag << endl; ss << "" << endl << "<entry " // << " xmlns:gd=\"http://schemas.google.com/g/2005\" " // << " gd:etag=\"" << Util::replace_all( m_etag, "\"", "&quot;" ) << "\" " << " >" << endl << " <batch:id>A" << toVoid(this) << "</batch:id> " << endl << " <batch:operation type=\"update\"/> " << endl << " <id>" << fullEditURL << "</id> " << endl << " <link rel=\"edit\" type=\"application/atom+xml\" " << endl << " href=\"" << fullEditURL << "\"/>" << endl << " <gs:cell row=\"" << row() << "\" col=\"" << col() << "\" inputValue=\"" << m_value << "\"/>" << endl << "</entry> " << endl << endl; } void GoogleWorkSheetCell::sync() { string fullEditURL = editURL(); if( m_created ) fullEditURL += "/latest"; cerr << "SENDING VALUE:" << m_value << endl; stringstream updatess; updatess << "" << endl << "<entry xmlns=\"http://www.w3.org/2005/Atom\"" << endl << " xmlns:gs=\"http://schemas.google.com/spreadsheets/2006\">" << endl << " <id>" << "http://spreadsheets.google.com/feeds/cells/key/worksheetId/private/full/cellId" << "</id>" << endl << " <link rel=\"edit\" type=\"application/atom+xml\"" << endl << " href=\"" << fullEditURL << "\"/>" << endl << " <gs:cell row=\"" << row() << "\" col=\"" << col() << "\" inputValue=\"" << m_value << "\" />" << endl << "</entry>" << endl <<"" << endl; QUrl u(fullEditURL.c_str()); QNetworkRequest request = m_gc->createRequest( u ); request.setHeader( QNetworkRequest::ContentTypeHeader, "application/atom+xml" ); QNetworkReply* reply = m_gc->put( request, updatess.str() ); cerr << "-------------" << endl; cerr << "SENT to:" << fullEditURL << endl; cerr << updatess.str() << endl; cerr << "error:" << reply->error() << endl; QByteArray ba = reply->readAll(); cerr << "ba.sz:" << ba.size() << endl; cerr << "ba:" << prettyprintxml( (string)ba ) << endl; cerr << "-------------" << endl; fh_domdoc dom = Factory::StringToDOM( (string)ba ); DOMElement* e = dom->getDocumentElement(); string editURL = getMatchingAttribute( e, "link", "rel", "edit", "href" ); cerr << "have updated editURL:" << editURL << endl; int cellURLLength = m_ws->getCellFeedURL().length(); m_value = getStrSubCtx( e, "gs:cell" ); m_cellURL = editURL.substr( cellURLLength ); } void GoogleWorkSheetCell::value( const std::string& s ) { if( m_ws->getDelayCellSync() ) { m_dirty = true; m_value = s; return; } m_value = s; sync(); } std::string GoogleWorkSheetCell::editURL() { return m_ws->getCellFeedURL() + m_cellURL; } /****************************************/ /****************************************/ /****************************************/ YoutubeUpload::YoutubeUpload( fh_GoogleClient gc ) : m_gc( gc ) { } YoutubeUpload::~YoutubeUpload() { // cerr << "~YoutubeUpload()" << endl; // BackTrace(); } void YoutubeUpload::streamingUploadComplete() { cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO) << " blocking for reply" << endl; DEBUG << "YoutubeUpload::streamingUploadComplete() blocking for reply" << endl; QNetworkReply* reply = m_reply; cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO) << " wc1" << endl; m_streamToQIO->writingComplete(); cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO) << " wc2" << endl; DEBUG << "YoutubeUpload::streamingUploadComplete() reading data..." << endl; QByteArray ba = m_streamToQIO->readResponse(); // QByteArray ba = reply->readAll(); cerr << "YoutubeUpload::streamingUploadComplete() m_streamToQIO:" << GetImpl(m_streamToQIO) << " reply:" << reply->error() << endl; DEBUG << "streamingUploadComplete() reply.err:" << reply->error() << endl; DEBUG << "streamingUploadComplete() got reply:" << tostr(ba) << endl; fh_domdoc dom = Factory::StringToDOM( tostr(ba) ); DOMElement* e = dom->getDocumentElement(); m_url = getMatchingAttribute( e, "link", "rel", "self", "href" ); m_id = XML::getChildText( firstChild( e, "yt:videoid" )); // <?xml version="1.0" encoding="UTF-8"?> // <entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:media="http://search.yahoo.com/mrss/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:yt="http://gdata.youtube.com/schemas/2007" gd:etag="W/&quot;C0YMQXoycCp7ImA9WxNTFEU.&quot;"> // <id>tag:youtube.com,2008:video:jKY6tYD5s0U</id> // <published>2009-08-16T20:53:00.498-07:00</published> // <updated>2009-08-16T20:53:00.498-07:00</updated> // <app:edited>2009-08-16T20:53:00.498-07:00</app:edited> // <app:control> // <app:draft>yes</app:draft> // <yt:state name="processing"/> // </app:control> // <category scheme="http://schemas.google.com/g/2005#kind" term="http://gdata.youtube.com/schemas/2007#video"/> // <category scheme="http://gdata.youtube.com/schemas/2007/categories.cat" term="People" label="People &amp; Blogs"/> // <category scheme="http://gdata.youtube.com/schemas/2007/keywords.cat" term="nothing"/> // <title>nothing</title> // <link rel="alternate" type="text/html" href="http://www.youtube.com/watch?v=jKY6tYD5s0U"/> // <link rel="http://gdata.youtube.com/schemas/2007#video.responses" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/responses"/> // <link rel="http://gdata.youtube.com/schemas/2007#video.ratings" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/ratings"/> // <link rel="http://gdata.youtube.com/schemas/2007#video.complaints" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/complaints"/> // <link rel="http://gdata.youtube.com/schemas/2007#video.related" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/related"/> // <link rel="http://gdata.youtube.com/schemas/2007#video.captionTracks" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/captions" yt:hasEntries="false"/> // <link rel="http://gdata.youtube.com/schemas/2007#insight.views" type="text/html" href="http://insight.youtube.com/video-analytics/csvreports?query=jKY6tYD5s0U&amp;type=v&amp;starttime=1249862400000&amp;endtime=1250467200000&amp;region=world&amp;token=yyT3Wb4oxV4D5VKuz1sLnroReKR8MTI1MDQ4Mjk4MA%3D%3D&amp;hl=en_US"/> // <link rel="self" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/users/monkeyiqtesting/uploads/jKY6tYD5s0U"/> // <link rel="edit" type="application/atom+xml" href="http://gdata.youtube.com/feeds/api/users/monkeyiqtesting/uploads/jKY6tYD5s0U"/> // <author> // <name>monkeyiqtesting</name> // <uri>http://gdata.youtube.com/feeds/api/users/monkeyiqtesting</uri> // </author> // <gd:comments> // <gd:feedLink href="http://gdata.youtube.com/feeds/api/videos/jKY6tYD5s0U/comments" countHint="0"/> // </gd:comments> // <media:group> // <media:category label="People &amp; Blogs" scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category> // <media:content url="http://www.youtube.com/v/jKY6tYD5s0U&amp;f=user_uploads&amp;d=DeKCSMvhFol1x0mvu9wlZWD9LlbsOl3qUImVMV6ramM&amp;app=youtube_gdata" type="application/x-shockwave-flash" medium="video" isDefault="true" expression="full" yt:format="5"/> // <media:credit role="uploader" scheme="urn:youtube">monkeyiqtesting</media:credit> // <media:description type="plain">nothing</media:description> // <media:keywords>nothing</media:keywords> // <media:player url="http://www.youtube.com/watch?v=jKY6tYD5s0U"/> // <media:title type="plain">nothing</media:title> // <yt:uploaded>2009-08-16T20:53:00.498-07:00</yt:uploaded> // <yt:videoid>jKY6tYD5s0U</yt:videoid> // </media:group> // </entry> } fh_iostream YoutubeUpload::createStreamingUpload( const std::string& ContentType ) { m_url = ""; m_id = ""; // NO X-GData-Client: <client_id> // OK X-GData-Key: key=<developer_key> // OK Slug: <video_filename> // OK Authorization: AuthSub token="<authentication_token>" // OK GData-Version: 2 // OK Content-Length: <content_length> string devkey = (string)"key=" + m_gc->getYoutubeDevKey(); QUrl u( "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads"); // u.addQueryItem("Slug", m_uploadFilename.c_str()); // u.addQueryItem("X-GData-Key", devkey.c_str()); QNetworkRequest req = m_gc->createRequest( u, "youtube", "2" ); req.setRawHeader("Slug", m_uploadFilename.c_str()); req.setRawHeader("X-GData-Key", devkey.c_str()); DEBUG << "X-GData-Key START|" << devkey << "|END" << endl; req.setHeader(QNetworkRequest::ContentLengthHeader, tostr(m_uploadSize).c_str() ); m_streamToQIO = Factory::createStreamToQIODevice(); { string desc = m_desc; string title = m_title; string keywords = m_keywords; if( keywords.empty() ) keywords = "none"; stringstream ss; ss << "Content-Type: application/atom+xml; charset=UTF-8\n"; ss << "\n"; ss << "<?xml version=\"1.0\"?>"; ss << "<entry xmlns=\"http://www.w3.org/2005/Atom\"\n"; ss << " xmlns:media=\"http://search.yahoo.com/mrss/\"\n"; ss << " xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">\n"; ss << " <media:group>\n"; // if( m_uploadDefaultsToPrivate ) // ss << " <yt:private/>\n"; ss << " <media:title type=\"plain\">" << title << "</media:title>\n"; ss << " <media:description type=\"plain\">\n"; ss << " " << desc << "\n"; ss << " </media:description>\n"; ss << " <media:category\n"; ss << " scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">People\n"; ss << " </media:category>\n"; ss << " <media:keywords>" << keywords << "</media:keywords>\n"; ss << " </media:group>\n"; ss << "</entry>\n"; string API_XML_request; API_XML_request = ss.str(); m_streamToQIO->addExtraDataChunk( API_XML_request ); } stringstream blobss; blobss << "Content-Type: " << ContentType << "\n" << "Content-Transfer-Encoding: binary;"; m_streamToQIO->setContentType( "multipart/related" ); QNetworkReply* reply = m_streamToQIO->post( ::Ferris::getQNonCachingManager(), req, blobss.str() ); m_reply = reply; fh_iostream ret = m_streamToQIO->getStream(); return ret; } /****************************************/ /****************************************/ /****************************************/ namespace Factory { fh_GoogleClient createGoogleClient() { Main::processAllPendingEvents(); KDE::ensureKDEApplication(); return new GoogleClient(); } }; /******************************************************/ /******************************************************/ /******************************************************/ GDriveFile::GDriveFile( fh_GDriveClient gd, QVariantMap dm ) : m_gd( gd ) , m_id(tostr(dm["id"])) , m_etag(tostr(dm["etag"])) , m_rdn(tostr(dm["originalFilename"])) , m_mime(tostr(dm["mimeType"])) , m_title(tostr(dm["title"])) , m_desc(tostr(dm["description"])) , m_earl(tostr(dm["downloadUrl"])) , m_earlview(tostr(dm["webViewLink"])) , m_ext(tostr(dm["fileExtension"])) , m_md5(tostr(dm["md5checksum"])) , m_sz(toint(tostr(dm["fileSize"]))) { m_ctime = parseTime(tostr(dm["createdDate"])); m_mtime = parseTime(tostr(dm["modifiedDate"])); m_mmtime = parseTime(tostr(dm["modifiedByMeDate"])); } time_t GDriveFile::parseTime( const std::string& v_const ) { string v = v_const; try { // 2013-07-26T03:51:28.238Z v = replaceg( v, "\\.[0-9]*Z", "Z" ); return Time::toTime(Time::ParseTimeString( v )); } catch( ... ) { return 0; } } QNetworkRequest GDriveFile::createRequest( const std::string& earl ) { QNetworkRequest req( QUrl(earl.c_str()) ); req.setRawHeader("Authorization", string(string("Bearer ") + m_gd->m_accessToken).c_str() ); return req; } fh_istream GDriveFile::getIStream() { m_gd->ensureAccessTokenFresh(); QNetworkAccessManager* qm = getQManager(); QNetworkRequest req = createRequest(m_earl); DEBUG << "getIStream()...url:" << tostr(QString(req.url().toEncoded())) << endl; QNetworkReply *reply = qm->get( req ); fh_istream ret = Factory::createIStreamFromQIODevice( reply ); return ret; } void GDriveFile::OnStreamClosed( fh_istream& ss, std::streamsize tellp, ferris_ios::openmode m ) { DEBUG << "GDriveFile::OnStreamClosed(top)" << endl; m_streamToQIO->writingComplete(); QByteArray ba = m_streamToQIO->readResponse(); DEBUG << "RESULT:" << tostr(ba) << endl; } fh_iostream GDriveFile::getIOStream() { DEBUG << "GDriveFile::getIOStream(top)" << endl; // PUT https://www.googleapis.com/upload/drive/v2/files/fileId stringstream earlss; earlss << "https://www.googleapis.com/upload/drive/v2/files/" << m_id << "?" << "uploadType=media&" << "fileId=" << m_id; QNetworkRequest req = createRequest(tostr(earlss)); req.setRawHeader( "Accept", "*/*" ); req.setRawHeader( "Connection", "" ); req.setRawHeader( "Accept-Encoding", "" ); req.setRawHeader( "Accept-Language", "" ); req.setRawHeader( "User-Agent", "" ); DEBUG << "PUT()ing main request..." << endl; m_streamToQIO = Factory::createStreamToQIODevice(); QNetworkReply* reply = m_streamToQIO->put( ::Ferris::getQNonCachingManager(), req ); m_streamToQIO_reply = reply; DEBUG << "preparing iostream for user..." << endl; fh_iostream ret = m_streamToQIO->getStream(); ferris_ios::openmode m = 0; ret->getCloseSig().connect( sigc::bind( sigc::mem_fun(*this, &_Self::OnStreamClosed ), m )); DEBUG << "GDriveFile::getIOStream(end)" << endl; return ret; } bool GDriveFile::isDir() const { return m_mime == "application/vnd.google-apps.folder"; } string GDriveFile::DRIVE_BASE() { return "https://www.googleapis.com/drive/v2/"; } QNetworkRequest GDriveFile::addAuth( QNetworkRequest req ) { return m_gd->addAuth( req ); } QNetworkReply* GDriveFile::wait(QNetworkReply* reply ) { return getDrive()->wait( reply ); } void GDriveFile::updateMetadata( const std::string& key, const std::string& value ) { stringmap_t update; update[ key ] = value; updateMetadata( update ); } fh_GDriveFile GDriveFile::createFile( const std::string& title ) { QNetworkRequest req = createRequest(DRIVE_BASE() + "files"); req.setRawHeader("Content-Type", "application/json" ); stringmap_t update; update["fileId"] = ""; update["title"] = title; update["description"] = "new"; update["data"] = ""; update["mimeType"] = KDE::guessMimeType( title ); string body = stringmapToJSON( update ); DEBUG << "createFile() url:" << tostr( req.url().toEncoded() ) << endl; DEBUG << "createFile() body:" << body << endl; QNetworkReply* reply = getDrive()->callPost( req, stringmap_t(), body ); wait( reply ); QByteArray ba = reply->readAll(); DEBUG << "REST error code:" << reply->error() << endl; DEBUG << "HTTP response :" << httpResponse(reply) << endl; QVariantMap dm = JSONToQVMap( tostr(ba) ); fh_GDriveFile f = new GDriveFile( getDrive(), dm ); return f; } void GDriveFile::updateMetadata( stringmap_t& update ) { getDrive()->ensureAccessTokenFresh(); // PATCH https://www.googleapis.com/drive/v2/files/fileId QUrl u( string(DRIVE_BASE() + "files/" + m_id).c_str() ); QNetworkRequest req; req.setUrl( u ); DEBUG << "u1.str::" << tostr(req.url().toString()) << endl; req.setRawHeader("Content-Type", "application/json" ); req = addAuth( req ); DEBUG << "u2.str::" << tostr(req.url().toString()) << endl; std::string json = stringmapToJSON( update ); DEBUG << " json:" << json << endl; QBuffer* buf = new QBuffer(new QByteArray(json.c_str())); QNetworkReply* reply = getQManager()->sendCustomRequest( req, "PATCH", buf ); wait( reply ); QByteArray ba = reply->readAll(); DEBUG << "REST error code:" << reply->error() << endl; DEBUG << "HTTP response :" << httpResponse(reply) << endl; DEBUG << "result:" << tostr(ba) << endl; stringmap_t sm = JSONToStringMap( tostr(ba) ); fh_stringstream ess; for( stringmap_t::iterator iter = update.begin(); iter != update.end(); ++iter ) { DEBUG << "iter->first:" << iter->first << endl; DEBUG << "iter->second:" << iter->second << endl; DEBUG << " got:" << sm[iter->first] << endl; if( sm[iter->first] != iter->second ) { ess << "attribute " << iter->first << " not correct." << endl; ess << "expected:" << iter->second << endl; ess << " got:" << sm[iter->first] << endl; } } string e = tostr(ess); DEBUG << "e:" << e << endl; if( !e.empty() ) { Throw_WebAPIException( e, 0 ); } } GDrivePermissions_t GDriveFile::readPermissions() { GDrivePermissions_t ret; QNetworkRequest req = createRequest(DRIVE_BASE() + "files/" + m_id + "/permissions"); req.setRawHeader("Content-Type", "application/json" ); stringmap_t args; args["fileId"] = m_id; QNetworkReply* reply = getDrive()->callMeth( req, args ); QByteArray ba = reply->readAll(); DEBUG << "readPermissions() REST error code:" << reply->error() << endl; DEBUG << "readPermissions() HTTP response :" << httpResponse(reply) << endl; DEBUG << "readPermissions() RESULT:" << tostr(ba) << endl; QVariantMap qm = JSONToQVMap( tostr(ba) ); QVariantList l = qm["items"].toList(); foreach (QVariant ding, l) { QVariantMap dm = ding.toMap(); int perm = GDrivePermission::NONE; if( dm["role"] == "reader" ) perm = GDrivePermission::READ; if( dm["role"] == "writer" || dm["role"] == "owner" ) perm = GDrivePermission::WRITE; fh_GDrivePermission p = new GDrivePermission( perm, tostr(dm["name"])); ret.push_back(p); } return ret; } void GDriveFile::sharesAdd( std::string email ) { stringlist_t emails; emails.push_back( email ); return sharesAdd( emails ); } void GDriveFile::sharesAdd( stringlist_t& emails ) { // POST https://www.googleapis.com/drive/v2/files/fileId/permissions for( stringlist_t::iterator si = emails.begin(); si != emails.end(); ++si ) { string email = *si; QNetworkRequest req = createRequest(DRIVE_BASE() + "files/" + m_id + "/permissions"); req.setRawHeader("Content-Type", "application/json" ); stringmap_t args; args["fileId"] = m_id; args["emailMessage"] = "Life moves pretty fast. If you don't stop and look around once in a while, you could miss it."; stringstream bodyss; bodyss << "{" << endl << " \"kind\": \"drive#permission\", " << endl << " \"value\": \"" << email << "\" , " << endl << " \"role\": \"writer\"," << endl << " \"type\": \"user\"" << endl << " } " << endl; DEBUG << "body:" << tostr(bodyss) << endl; QNetworkReply* reply = getDrive()->callPost( req, args, tostr(bodyss) ); QByteArray ba = reply->readAll(); DEBUG << "sharesAdd() REST error code:" << reply->error() << endl; DEBUG << "sharesAdd() HTTP response :" << httpResponse(reply) << endl; DEBUG << "sharesAdd() RESULT:" << tostr(ba) << endl; stringmap_t sm = JSONToStringMap( tostr(ba) ); if( !sm["etag"].empty() && !sm["id"].empty() ) continue; // Failed stringstream ess; ess << "Failed to create permission for user:" << email << endl << " reply:" << tostr(ba) << endl; Throw_WebAPIException( tostr(ess), 0 ); } } /********************/ GDriveClient::GDriveClient() : m_clientID( "881964254376.apps.googleusercontent.com" ) , m_secret( "UH9zxZ8k_Fj3actLPRVPVG8Q" ) { readAuthTokens(); } void GDriveClient::readAuthTokens() { m_accessToken = getConfigString( FDB_SECURE, "gdrive-access-token", "" ); m_refreshToken = getConfigString( FDB_SECURE, "gdrive-refresh-token", "" ); m_accessToken_expiretime = toType<time_t>( getConfigString( FDB_SECURE, "gdrive-access-token-expires-timet", "0")); } std::string GDriveClient::AUTH_BASE() { return "https://accounts.google.com/o/oauth2/"; } fh_GDriveClient GDriveClient::getGDriveClient() { Main::processAllPendingEvents(); KDE::ensureKDEApplication(); static fh_GDriveClient ret = new GDriveClient(); return ret; } bool GDriveClient::haveAPIKey() const { return !m_clientID.empty() && !m_secret.empty(); } bool GDriveClient::isAuthenticated() const { return !m_accessToken.empty() && !m_refreshToken.empty(); } void GDriveClient::handleFinished() { QNetworkReply* r = dynamic_cast<QNetworkReply*>(sender()); m_waiter.unblock(r); DEBUG << "handleFinished() r:" << r << endl; } QNetworkReply* GDriveClient::wait(QNetworkReply* reply ) { connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) ); m_waiter.block(reply); return reply; } QNetworkReply* GDriveClient::post( QNetworkRequest req ) { QUrl u = req.url(); DEBUG << "u.str::" << tostr(u.toString()) << endl; string body = tostr(u.encodedQuery()); DEBUG << "body:" << body << endl; u.setEncodedQuery(QByteArray()); // u.setUrl( "http://localhost/testing" ); req.setHeader( QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded" ); req.setHeader(QNetworkRequest::ContentLengthHeader, tostr(body.size()).c_str() ); QNetworkReply* reply = getQManager()->post( req, body.c_str() ); connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) ); m_waiter.block(reply); DEBUG << "REST error code:" << reply->error() << endl; return reply; } std::string GDriveClient::requestToken( stringmap_t args ) { QUrl u( string(AUTH_BASE() + "auth").c_str() ); u.addQueryItem("response_type", "code" ); u.addQueryItem("client_id", m_clientID.c_str() ); u.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob" ); u.addQueryItem("scope", "https://www.googleapis.com/auth/drive.file " "https://www.googleapis.com/auth/drive " "https://www.googleapis.com/auth/drive.scripts " "https://www.googleapis.com/auth/drive.appdata " ); u.addQueryItem("state", "anyone... anyone?" ); std::string authURL = tostr( u.toEncoded() ); return authURL; } void GDriveClient::accessToken( const std::string& code, stringmap_t args ) { QUrl u( string(AUTH_BASE() + "token").c_str() ); QNetworkRequest req; req.setUrl( u ); args["code"] = code; args["client_id"] = m_clientID; args["client_secret"] = m_secret; args["redirect_uri"] = "urn:ietf:wg:oauth:2.0:oob"; args["grant_type"] = "authorization_code"; DEBUG << "u1.str::" << tostr(req.url().toString()) << endl; req = setArgs( req, args ); DEBUG << "u2.str::" << tostr(req.url().toString()) << endl; QNetworkReply* reply = post( req ); QByteArray ba = reply->readAll(); cerr << "result:" << tostr(ba) << endl; stringmap_t sm = JSONToStringMap( tostr(ba) ); time_t expiretime = Time::getTime() + toint(sm["expires_in"]); setConfigString( FDB_SECURE, "gdrive-access-token", sm["access_token"] ); setConfigString( FDB_SECURE, "gdrive-refresh-token", sm["refresh_token"] ); setConfigString( FDB_SECURE, "gdrive-access-token-expires-timet", tostr(expiretime) ); readAuthTokens(); } void GDriveClient::ensureAccessTokenFresh( int force ) { if( !isAuthenticated() ) return; if( !force ) { if( Time::getTime() + 30 < m_accessToken_expiretime ) return; } DEBUG << "ensureAccessTokenFresh() really doing it!" << endl; QUrl u( string(AUTH_BASE() + "token").c_str() ); QNetworkRequest req; req.setUrl( u ); stringmap_t args; args["refresh_token"] = m_refreshToken; args["client_id"] = m_clientID; args["client_secret"] = m_secret; args["grant_type"] = "refresh_token"; req = setArgs( req, args ); QNetworkReply* reply = post( req ); cerr << "ensureAccessTokenFresh() have reply..." << endl; QByteArray ba = reply->readAll(); cerr << "ensureAccessTokenFresh(b) m_accessToken:" << m_accessToken << endl; cerr << "ensureAccessTokenFresh() result:" << tostr(ba) << endl; stringmap_t sm = JSONToStringMap( tostr(ba) ); time_t expiretime = Time::getTime() + toint(sm["expires_in"]); setConfigString( FDB_SECURE, "gdrive-access-token", sm["access_token"] ); setConfigString( FDB_SECURE, "gdrive-access-token-expires-timet", tostr(expiretime) ); readAuthTokens(); cerr << "ensureAccessTokenFresh(e) m_accessToken:" << m_accessToken << endl; } QNetworkRequest GDriveClient::addAuth( QNetworkRequest req ) { req.setRawHeader("Authorization", string(string("Bearer ") + m_accessToken).c_str() ); return req; } QNetworkReply* GDriveClient::callMeth( QNetworkRequest req, stringmap_t args ) { ensureAccessTokenFresh(); req = setArgs( req, args ); req = addAuth( req ); QUrl u = req.url(); DEBUG << "callMeth U:" << tostr(QString(u.toEncoded())) << endl; // u.setUrl( "http://localhost/testing" ); // req.setUrl(u); QNetworkReply* reply = getQManager()->get( req ); connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) ); m_waiter.block(reply); DEBUG << "REST error code:" << reply->error() << endl; return reply; } QNetworkReply* GDriveClient::callPost( QNetworkRequest req, stringmap_t args, const std::string& body ) { ensureAccessTokenFresh(); req = setArgs( req, args ); req = addAuth( req ); QUrl u = req.url(); DEBUG << "callPost U:" << tostr(QString(u.toEncoded())) << endl; DEBUG << " body:" << body << endl; QBuffer* buf = new QBuffer(new QByteArray(body.c_str())); QNetworkReply* reply = getQManager()->post( req, buf ); connect( reply, SIGNAL( finished() ), SLOT( handleFinished() ) ); m_waiter.block(reply); DEBUG << "REST error code:" << reply->error() << endl; return reply; } string GDriveClient::DRIVE_BASE() { return "https://www.googleapis.com/drive/v2/"; } QNetworkRequest GDriveClient::createRequest( const std::string& earlTail ) { QUrl u( string(DRIVE_BASE() + earlTail).c_str() ); QNetworkRequest req; req.setUrl( u ); return req; } files_t GDriveClient::filesList( const std::string& q_const, const std::string& pageToken ) { string q = q_const; if( q.empty() ) { q = "hidden = false and trashed = false"; } files_t ret; // QNetworkRequest req = createRequest("files/root/children"); QNetworkRequest req = createRequest("files"); stringmap_t args; args["maxResults"] = tostr(1000); if( !pageToken.empty() ) args["pageToken"] = pageToken; if( !q.empty() ) args["q"] = q; QNetworkReply* reply = callMeth( req, args ); QByteArray ba = reply->readAll(); DEBUG << "filesList() result:" << tostr(ba) << endl; stringmap_t sm = JSONToStringMap( tostr(ba) ); DEBUG << "etag:" << sm["etag"] << endl; QVariantMap qm = JSONToQVMap( tostr(ba) ); QVariantList l = qm["items"].toList(); foreach (QVariant ding, l) { QVariantMap dm = ding.toMap(); string rdn = tostr(dm["originalFilename"]); long sz = toint(tostr(dm["fileSize"])); QVariantMap labels = dm["labels"].toMap(); if( labels["hidden"].toInt() || labels["trashed"].toInt() ) continue; bool skipThisOne = false; QVariantList parents = dm["parents"].toList(); foreach (QVariant pv, parents) { QVariantMap pm = pv.toMap(); if( !pm["isRoot"].toInt() ) { skipThisOne = 1; break; } } if( dm["userPermission"].toMap()["role"] != "owner" ) skipThisOne = true; if( skipThisOne ) continue; DEBUG << "sz:" << sz << " fn:" << rdn << endl; fh_GDriveFile f = new GDriveFile( this, dm ); ret.push_back(f); } return ret; } /****************************************/ /****************************************/ /****************************************/ };
monkeyiq/ferris
plugins/context/libferrisgoogle_shared.cpp
C++
gpl-3.0
87,216
// // This file is part of Return To The Roots. // // Return To The Roots is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Return To The Roots is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Return To The Roots. If not, see <http://www.gnu.org/licenses/>. #include "rttrDefines.h" // IWYU pragma: keep #include "LanGameInfo.h" #include "s25util/Serializer.h" bool LanGameInfo::Serialize(Serializer& serializer) { if(name.size() > 64) name.resize(64); if(map.size() > 64) map.resize(64); if(version.size() > 16) version.resize(16); serializer.PushString(name); serializer.PushBool(hasPwd); serializer.PushString(map); serializer.PushUnsignedChar(curNumPlayers); serializer.PushUnsignedChar(maxNumPlayers); serializer.PushUnsignedShort(port); serializer.PushBool(isIPv6); serializer.PushString(version); serializer.PushString(revision); return true; } bool LanGameInfo::Deserialize(Serializer& serializer) { name = serializer.PopString(); hasPwd = serializer.PopBool(); map = serializer.PopString(); curNumPlayers = serializer.PopUnsignedChar(); maxNumPlayers = serializer.PopUnsignedChar(); port = serializer.PopUnsignedShort(); isIPv6 = serializer.PopBool(); version = serializer.PopString(); revision = serializer.PopString(); return true; }
stefson/s25client
libs/s25main/gameTypes/LanGameInfo.cpp
C++
gpl-3.0
1,822
<?php /* publicacion_miniatura.php Una publicacion en miniatura */ /* Created on : 23/04/2015, 14:40:40 Author : Juan Manuel Scarciofolo License : GPLv3 */ ?> <div class="publicacion_miniatura"> <h2><?php print $producto->getDescripcion(); ?></h2> <p> <?php $img = $producto->getImagenes(); for ($index = 0; $index < 3; $index++) { if (!empty($img[$index]['imagen'])) { break; } } print getImagen($img[$index]['imagen'], 'img_preview img_preview_left'); print extractoTexto($producto->getResumen()); ?> </p> </div>
scarfive/mercadosocialmdq
publicacion_miniatura.php
PHP
gpl-3.0
727
require 'package' class Aspell_fr < Package description 'French Aspell Dictionary' homepage 'https://ftpmirror.gnu.org/aspell/dict/0index.html' version '0.50-3' source_url 'https://ftpmirror.gnu.org/aspell/dict/fr/aspell-fr-0.50-3.tar.bz2' source_sha256 'f9421047519d2af9a7a466e4336f6e6ea55206b356cd33c8bd18cb626bf2ce91' binary_url ({ aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.50-3-chromeos-armv7l.tar.xz', armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.50-3-chromeos-armv7l.tar.xz', i686: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.50-3-chromeos-i686.tar.xz', x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/aspell_fr-0.50-3-chromeos-x86_64.tar.xz', }) binary_sha256 ({ aarch64: 'c109f726e0a3a7e708a6c8fb4cb1cd7f84d0486fa352c141ce5f70817651efc7', armv7l: 'c109f726e0a3a7e708a6c8fb4cb1cd7f84d0486fa352c141ce5f70817651efc7', i686: '3a466ebca6ea8267b2ba5e5bcda9b1e15869f11d144b2c282dc5ff40a37d7364', x86_64: '8ffcc409bf5c6e4a142b68d027498942788535f8025927de23efa477e1a7d2c1', }) depends_on 'aspell' def self.build system './configure' system 'make' end def self.install system "make", "DESTDIR=#{CREW_DEST_DIR}", "install" end end
chromebrew/chromebrew-test
packages/aspell_fr.rb
Ruby
gpl-3.0
1,281
require_relative '../core_ext/array' require_relative '../core_ext/hash' require_relative 'host' require_relative 'command' require_relative 'command_map' require_relative 'configuration' require_relative 'coordinator' require_relative 'logger' require_relative 'log_message' require_relative 'formatters/abstract' require_relative 'formatters/black_hole' require_relative 'formatters/pretty' require_relative 'formatters/dot' require_relative 'runners/abstract' require_relative 'runners/sequential' require_relative 'runners/parallel' require_relative 'runners/group' require_relative 'runners/null' require_relative 'backends/abstract' require_relative 'backends/printer' require_relative 'backends/netssh' require_relative 'backends/local' require_relative 'backends/skipper'
mattbrictson/sshkit
lib/sshkit/all.rb
Ruby
gpl-3.0
786
#!/usr/bin/env python # -*- coding: utf-8 -*- """ add word counts to Cornetto lexical units database file The word count file should have three columns, delimited by white space, containing (1) the count, (2) the lemma, (3) the main POS tag. The tagset is assumed to be the Spoken Dutch Corpus tagset, and the character encoding must be ISO-8859-1. The counts appear as the value of the feature "count" on <form> elements. The updated lexical units xml database is written to standard output. Since we have only the lemma and the POS, and no word sense, the frequency information is added to each matching lexical unit regardless of its sense (i.e. the value of the "c_seq_nr" attribute). """ # TODO: # - deal with multiword counts __author__ = 'Erwin Marsi <e.marsi@gmail.com>' __version__ = '0.6' from sys import stderr, stdout from xml.etree.cElementTree import iterparse, SubElement, tostring, ElementTree from cornetto.argparse import ArgumentParser, RawDescriptionHelpFormatter def read_counts(file): if not hasattr(file, "read"): file = open(file) counts = {} totals = dict(noun=0, verb=0, adj=0, other=0) for l in file: try: count, form, tag = l.strip().split() except ValueError: stderr.write("Warning; ill-formed line: %s\n" % repr(l)) continue # translate CGN tagset to word category if tag in ("N", "VNW", "TW", "SPEC"): cat = "noun" elif tag in ("WW"): cat = "verb" elif tag in ("ADJ", "BW"): cat = "adj" else: # LET LID TSW VG VZ cat = "other" # Cornetto word forms are stored in unicode form = form.decode("iso-8859-1") count = int(count) if form not in counts: counts[form] = dict(noun=0, verb=0, adj=0, other=0) counts[form][cat] += count totals[cat] += count return counts, totals def add_count_attrib(counts, totals, cdb_lu_file): parser = iterparse(cdb_lu_file) for event, elem in parser: if elem.tag == "form": # following the ElementTree conventions, # word form will be ascii or unicode form = elem.get("form-spelling") # lower case because Cornette is not consistent cat = elem.get("form-cat").lower() # fix category flaws in current release of Cornetto if cat == "adjective": cat = "adj" elif cat == "adverb": cat = "other" try: count = counts[form][cat] except KeyError: # form not found count = 0 elem.set("count", str(count)) # Finally, add totals, per category and overall, to the doc root # Note that all words _not_ in Cornetto are not included in these totals totals["all"] = sum(totals.values()) for cat, count in totals.items(): parser.root.set("count-total-%s" % cat, str(count)) return ElementTree(parser.root) parser = ArgumentParser(description=__doc__, version="%(prog)s version " + __version__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument("cdb_lu", type=file, help="xml file containing the lexical units") parser.add_argument("word_counts", type=file, help="tabular file containing the word counts") args = parser.parse_args() counts, totals = read_counts(args.word_counts) etree = add_count_attrib(counts, totals, args.cdb_lu) etree.write(stdout, encoding="utf-8") #def add_statistics_elem(counts, cdb_lu_file): #""" #adds a separate <statistics> element, #which accomodates for other counts for other sources #""" #parser = iterparse(cdb_lu_file) #for event, elem in parser: #if elem.tag == "cdb_lu": #try: #count = counts[form][cat] #except KeyError: #count = 0 #freq_el = SubElement(elem, "statistics") #SubElement(freq_el, "count", scr="uvt").text = str(count) #elif elem.tag == "form": ## following the ElementTree conventions, ## word form will be ascii or unicode #form = elem.get("form-spelling") #cat = elem.get("form-cat") #return ElementTree(parser.root)
emsrc/pycornetto
bin/cornetto-add-counts.py
Python
gpl-3.0
4,585
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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. */ package com.stt.data.jpa.service; import com.stt.data.jpa.domain.City; import com.stt.data.jpa.domain.Hotel; import com.stt.data.jpa.domain.HotelSummary; import com.stt.data.jpa.domain.RatingCount; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import java.util.List; interface HotelRepository extends Repository<Hotel, Long> { Hotel findByCityAndName(City city, String name); @Query("select h.city as city, h.name as name, avg(r.rating) as averageRating " + "from Hotel h left outer join h.reviews r where h.city = ?1 group by h") Page<HotelSummary> findByCity(City city, Pageable pageable); @Query("select r.rating as rating, count(r) as count " + "from Review r where r.hotel = ?1 group by r.rating order by r.rating DESC") List<RatingCount> findRatingCounts(Hotel hotel); }
shitongtong/libraryManage
spring-boot-demo/data-jpa/src/main/java/com/stt/data/jpa/service/HotelRepository.java
Java
gpl-3.0
1,574
/************************************************************************ * Copyright (C) 2019 Spatial Information Systems Research Limited * * 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 <Action/ActionToggleCameraActorInteraction.h> #include <FaceModelViewer.h> #include <FaceModel.h> using FaceTools::Action::ActionToggleCameraActorInteraction; using FaceTools::Interactor::ActorMoveNotifier; using FaceTools::Action::FaceAction; using FaceTools::Action::Event; using FaceTools::FaceModelViewer; using FaceTools::ModelViewer; using FaceTools::FM; using FaceTools::FVS; using FaceTools::Vis::FV; using MS = FaceTools::Action::ModelSelector; ActionToggleCameraActorInteraction::ActionToggleCameraActorInteraction( const QString& dn, const QIcon& ico, const QKeySequence& ks) : FaceAction( dn, ico, ks), _dblClickDrag(false) { const Interactor::SelectNotifier *sn = MS::selector(); connect( sn, &Interactor::SelectNotifier::onDoubleClickedSelected, this, &ActionToggleCameraActorInteraction::_doDoubleClicked); connect( sn, &Interactor::SelectNotifier::onLeftButtonUp, this, &ActionToggleCameraActorInteraction::_doLeftButtonUp); _moveNotifier = std::shared_ptr<ActorMoveNotifier>( new ActorMoveNotifier); connect( &*_moveNotifier, &ActorMoveNotifier::onActorStart, this, &ActionToggleCameraActorInteraction::_doOnActorStart); connect( &*_moveNotifier, &ActorMoveNotifier::onActorStop, this, &ActionToggleCameraActorInteraction::_doOnActorStop); setCheckable( true, false); } // end ctor QString ActionToggleCameraActorInteraction::toolTip() const { return "When on, click and drag the selected model to change its position or orientation."; } // end toolTip QString ActionToggleCameraActorInteraction::whatsThis() const { QStringList htext; htext << "With this option toggled off, mouse clicking and dragging causes the camera to move around."; htext << "When this option is toggled on, clicking and dragging on a model will reposition or reorient it in space."; htext << "Click and drag with the left mouse button to rotate the model in place."; htext << "Click and drag with the right mouse button (or hold down the SHIFT key while left clicking and dragging)"; htext << "to shift the model laterally. Click and drag with the middle mouse button (or hold down the CTRL key while"; htext << "left or right clicking and dragging) to move the model towards or away from you."; htext << "Note that clicking and dragging off the model's surface will still move the camera around, but that this also"; htext << "toggles this option off (any camera action from the menu/toolbar will also toggle this option off)."; return tr( htext.join(" ").toStdString().c_str()); } // end whatsThis bool ActionToggleCameraActorInteraction::checkState( Event) { return MS::interactionMode() == IMode::ACTOR_INTERACTION; } // end checkState bool ActionToggleCameraActorInteraction::checkEnable( Event) { const FM* fm = MS::selectedModel(); return fm || isChecked(); } // end checkEnabled void ActionToggleCameraActorInteraction::doAction( Event) { if ( isChecked()) { MS::showStatus( "Model interaction ACTIVE"); MS::setInteractionMode( IMode::ACTOR_INTERACTION, true); } // end if else { MS::showStatus( "Camera interaction ACTIVE", 5000); MS::setInteractionMode( IMode::CAMERA_INTERACTION); } // end else } // end doAction void ActionToggleCameraActorInteraction::_doOnActorStart() { storeUndo( this, Event::AFFINE_CHANGE); } // end _doOnActorStart void ActionToggleCameraActorInteraction::_doOnActorStop() { emit onEvent( Event::AFFINE_CHANGE); } // end _doOnActorStop // Called only when user double clicks on an already selected model. void ActionToggleCameraActorInteraction::_doDoubleClicked() { _dblClickDrag = true; setChecked( true); execute( Event::USER); } // end _doDoubleClicked void ActionToggleCameraActorInteraction::_doLeftButtonUp() { if ( _dblClickDrag) { _dblClickDrag = false; setChecked( false); execute( Event::USER); } // end if } // end _doLeftButtonUp
richeytastic/FaceTools
src/Action/ActionToggleCameraActorInteraction.cpp
C++
gpl-3.0
4,893
#!/usr/bin/env python3 from heapq import heapify, heappop, heappush with open('NUOC.INP') as f: m, n = map(int, f.readline().split()) height = [[int(i) for i in line.split()] for line in f] queue = ([(h, 0, i) for i, h in enumerate(height[0])] + [(h, m - 1, i) for i, h in enumerate(height[-1])] + [(height[i][0], i, 0) for i in range(m)] + [(height[i][-1], i, n - 1) for i in range(m)]) heapify(queue) visited = ([[True] * n] + [[True] + [False] * (n - 2) + [True] for _ in range(m - 2)] + [[True] * n]) result = 0 while queue: h, i, j = heappop(queue) for x, y in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1): if 0 <= x < m and 0 <= y < n and not visited[x][y]: result += max(0, h - height[x][y]) heappush(queue, (max(height[x][y], h), x, y)) visited[x][y] = True with open('NUOC.OUT', 'w') as f: print(result, file=f)
McSinyx/hsg
others/other/nuoc.py
Python
gpl-3.0
941
#include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <string.h> #define BUFFER_SIZE 1024 int main() { int socketfd; int port = 2047; struct sockaddr_in server_in; struct sockaddr_in client_in; int client_in_length = sizeof(client_in); char buffer[BUFFER_SIZE]; //Create a socket socketfd = socket(AF_INET, SOCK_DGRAM, 0); if (socketfd < 0) { perror("Creating a socket failed!"); return -1; } // Set the server address, by defaulting server_in to 0 // then setting it to the port, before binding memset((char *) &server_in, 0, sizeof(server_in)); server_in.sin_family = AF_INET; //IPV4 server_in.sin_port = htons(port); server_in.sin_addr.s_addr = htons(INADDR_ANY); //Any interface //Bind, Note the second parameter needs to be a sockaddr if (bind(socketfd, (struct sockaddr *) &server_in, sizeof(server_in)) == -1) { perror("Binding Failed, ec set to errno!"); return -2; } //Keep listening, for stuff while (true) { memset(buffer, 0, sizeof(buffer)); if (recvfrom(socketfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *) &client_in, (socklen_t *)&client_in_length) == -1) { perror("Recieving from client failed"); return -3; } if (sendto(socketfd, "OK\n", 3, 0, (struct sockaddr *) &client_in, client_in_length) == -1) perror("Sending to client failed"); //Make sure its not empty lines printf("Message: %s", buffer); } printf("Hello to the world of tomrow"); return 0; }
dashee/dashee
playground/src/udpserver.cpp
C++
gpl-3.0
1,733
<?php /* Copyright (C) 2014 Daniel Preussker <f0o@devilcode.org> * 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 <https://www.gnu.org/licenses/>. */ /** * Custom Frontpage * @author f0o <f0o@devilcode.org> * @copyright 2014 f0o, LibreNMS * @license GPL */ use Illuminate\Support\Facades\Auth; use LibreNMS\Alert\AlertUtil; use LibreNMS\Config; $install_dir = Config::get('install_dir'); if (Config::get('map.engine', 'leaflet') == 'leaflet') { $temp_output = ' <script src="js/leaflet.js"></script> <script src="js/leaflet.markercluster.js"></script> <script src="js/leaflet.awesome-markers.min.js"></script> <div id="leaflet-map"></div> <script> '; $init_lat = Config::get('leaflet.default_lat', 51.48); $init_lng = Config::get('leaflet.default_lng', 0); $init_zoom = Config::get('leaflet.default_zoom', 5); $group_radius = Config::get('leaflet.group_radius', 80); $tile_url = Config::get('leaflet.tile_url', '{s}.tile.openstreetmap.org'); $show_status = [0, 1]; $map_init = '[' . $init_lat . ', ' . $init_lng . '], ' . sprintf('%01.1f', $init_zoom); $temp_output .= 'var map = L.map(\'leaflet-map\', { zoomSnap: 0.1 } ).setView(' . $map_init . '); L.tileLayer(\'//' . $tile_url . '/{z}/{x}/{y}.png\', { attribution: \'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors\' }).addTo(map); var markers = L.markerClusterGroup({ maxClusterRadius: ' . $group_radius . ', iconCreateFunction: function (cluster) { var markers = cluster.getAllChildMarkers(); var n = 0; color = "green" newClass = "Cluster marker-cluster marker-cluster-small leaflet-zoom-animated leaflet-clickable"; for (var i = 0; i < markers.length; i++) { if (markers[i].options.icon.options.markerColor == "blue" && color != "red") { color = "blue"; } if (markers[i].options.icon.options.markerColor == "red") { color = "red"; } } return L.divIcon({ html: cluster.getChildCount(), className: color+newClass, iconSize: L.point(40, 40) }); }, }); var redMarker = L.AwesomeMarkers.icon({ icon: \'server\', markerColor: \'red\', prefix: \'fa\', iconColor: \'white\' }); var blueMarker = L.AwesomeMarkers.icon({ icon: \'server\', markerColor: \'blue\', prefix: \'fa\', iconColor: \'white\' }); var greenMarker = L.AwesomeMarkers.icon({ icon: \'server\', markerColor: \'green\', prefix: \'fa\', iconColor: \'white\' }); '; // Checking user permissions if (Auth::user()->hasGlobalRead()) { // Admin or global read-only - show all devices $sql = "SELECT DISTINCT(`device_id`),`location`,`sysName`,`hostname`,`os`,`status`,`lat`,`lng` FROM `devices` LEFT JOIN `locations` ON `devices`.`location_id`=`locations`.`id` WHERE `disabled`=0 AND `ignore`=0 AND ((`lat` != '' AND `lng` != '') OR (`location` REGEXP '\[[0-9\.\, ]+\]')) AND `status` IN " . dbGenPlaceholders(count($show_status)) . ' ORDER BY `status` ASC, `hostname`'; $param = $show_status; } else { // Normal user - grab devices that user has permissions to $device_ids = Permissions::devicesForUser()->toArray() ?: [0]; $sql = "SELECT DISTINCT(`devices`.`device_id`) as `device_id`,`location`,`sysName`,`hostname`,`os`,`status`,`lat`,`lng` FROM `devices` LEFT JOIN `locations` ON `devices`.location_id=`locations`.`id` WHERE `disabled`=0 AND `ignore`=0 AND ((`lat` != '' AND `lng` != '') OR (`location` REGEXP '\[[0-9\.\, ]+\]')) AND `devices`.`device_id` IN " . dbGenPlaceholders(count($device_ids)) . ' AND `status` IN ' . dbGenPlaceholders(count($show_status)) . ' ORDER BY `status` ASC, `hostname`'; $param = array_merge($device_ids, $show_status); } foreach (dbFetchRows($sql, $param) as $map_devices) { $icon = 'greenMarker'; $z_offset = 0; $tmp_loc = parse_location($map_devices['location']); if (is_numeric($tmp_loc['lat']) && is_numeric($tmp_loc['lng'])) { $map_devices['lat'] = $tmp_loc['lat']; $map_devices['lng'] = $tmp_loc['lng']; } if ($map_devices['status'] == 0) { if (AlertUtil::isMaintenance($map_devices['device_id'])) { if ($show_status == 0) { // Don't show icon if only down devices should be shown continue; } else { $icon = 'blueMarker'; $z_offset = 5000; } } else { $icon = 'redMarker'; $z_offset = 10000; // move marker to foreground } } $temp_output .= "var title = '<a href=\"" . \LibreNMS\Util\Url::deviceUrl((int) $map_devices['device_id']) . '"><img src="' . getIcon($map_devices) . '" width="32" height="32" alt=""> ' . format_hostname($map_devices) . "</a>'; var tooltip = '" . format_hostname($map_devices) . "'; var marker = L.marker(new L.LatLng(" . $map_devices['lat'] . ', ' . $map_devices['lng'] . "), {title: tooltip, icon: $icon, zIndexOffset: $z_offset}); marker.bindPopup(title); markers.addLayer(marker);\n"; } if (Config::get('network_map_show_on_worldmap')) { if (Auth::user()->hasGlobalRead()) { $sql = " SELECT ll.id AS left_id, ll.lat AS left_lat, ll.lng AS left_lng, rl.id AS right_id, rl.lat AS right_lat, rl.lng AS right_lng, sum(lp.ifHighSpeed) AS link_capacity, sum(lp.ifOutOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_out_usage_pct, sum(lp.ifInOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_in_usage_pct FROM devices AS ld, devices AS rd, links AS l, locations AS ll, locations AS rl, ports as lp WHERE l.local_device_id = ld.device_id AND l.remote_device_id = rd.device_id AND ld.location_id != rd.location_id AND ld.location_id = ll.id AND rd.location_id = rl.id AND lp.device_id = ld.device_id AND lp.port_id = l.local_port_id AND lp.ifType = 'ethernetCsmacd' AND ld.disabled = 0 AND ld.ignore = 0 AND rd.disabled = 0 AND rd.ignore = 0 AND lp.ifOutOctets_rate != 0 AND lp.ifInOctets_rate != 0 AND lp.ifOperStatus = 'up' AND ll.lat IS NOT NULL AND ll.lng IS NOT NULL AND rl.lat IS NOT NULL AND rl.lng IS NOT NULL AND ld.status IN " . dbGenPlaceholders(count($show_status)) . ' AND rd.status IN ' . dbGenPlaceholders(count($show_status)) . ' GROUP BY left_id, right_id, ll.lat, ll.lng, rl.lat, rl.lng '; $param = array_merge($show_status, $show_status); } else { $device_ids = Permissions::devicesForUser()->toArray() ?: [0]; $sql = " SELECT ll.id AS left_id, ll.lat AS left_lat, ll.lng AS left_lng, rl.id AS right_id, rl.lat AS right_lat, rl.lng AS right_lng, sum(lp.ifHighSpeed) AS link_capacity, sum(lp.ifOutOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_out_usage_pct, sum(lp.ifInOctets_rate) * 8 / sum(lp.ifSpeed) * 100 as link_in_usage_pct FROM devices AS ld, devices AS rd, links AS l, locations AS ll, locations AS rl, ports as lp WHERE l.local_device_id = ld.device_id AND l.remote_device_id = rd.device_id AND ld.location_id != rd.location_id AND ld.location_id = ll.id AND rd.location_id = rl.id AND lp.device_id = ld.device_id AND lp.port_id = l.local_port_id AND lp.ifType = 'ethernetCsmacd' AND ld.disabled = 0 AND ld.ignore = 0 AND rd.disabled = 0 AND rd.ignore = 0 AND lp.ifOutOctets_rate != 0 AND lp.ifInOctets_rate != 0 AND lp.ifOperStatus = 'up' AND ll.lat IS NOT NULL AND ll.lng IS NOT NULL AND rl.lat IS NOT NULL AND rl.lng IS NOT NULL AND ld.status IN " . dbGenPlaceholders(count($show_status)) . ' AND rd.status IN ' . dbGenPlaceholders(count($show_status)) . ' AND ld.device_id IN ' . dbGenPlaceholders(count($device_ids)) . ' AND rd.device_id IN ' . dbGenPlaceholders(count($device_ids)) . ' GROUP BY left_id, right_id, ll.lat, ll.lng, rl.lat, rl.lng '; $param = array_merge($show_status, $show_status, $device_ids, $device_ids); } foreach (dbFetchRows($sql, $param) as $link) { $icon = 'greenMarker'; $z_offset = 0; $speed = $link['link_capacity'] / 1000; if ($speed > 500000) { $width = 20; } else { $width = round(0.77 * pow($speed, 0.25)); } $link_used = max($link['link_out_usage_pct'], $link['link_in_usage_pct']); $link_used = round(2 * $link_used, -1) / 2; if ($link_used > 100) { $link_used = 100; } if (is_nan($link_used)) { $link_used = 0; } $link_color = Config::get("network_map_legend.$link_used"); $temp_output .= 'var marker = new L.Polyline([new L.LatLng(' . $link['left_lat'] . ', ' . $link['left_lng'] . '), new L.LatLng(' . $link['right_lat'] . ', ' . $link['right_lng'] . ")], { color: '" . $link_color . "', weight: " . $width . ', opacity: 0.8, smoothFactor: 1 }); markers.addLayer(marker); '; } } $temp_output .= 'map.addLayer(markers); map.scrollWheelZoom.disable(); $(document).ready(function(){ $("#leaflet-map").on("click", function(event) { map.scrollWheelZoom.enable(); }); $("#leaflet-map").mouseleave(function(event) { map.scrollWheelZoom.disable(); }); }); </script>'; } else { $temp_output = 'Mapael engine not supported here'; } unset($common_output); $common_output[] = $temp_output;
rasssta/librenms
includes/html/common/worldmap.inc.php
PHP
gpl-3.0
11,457
package com.bruce.android.knowledge.custom_view.scanAnimation; /** * @author zhenghao.qi * @version 1.0 * @time 2015年11月09日14:45:32 */ public class ScanAnimaitonStrategy implements IAnimationStrategy { /** * 起始X坐标 */ private int startX; /** * 起始Y坐标 */ private int startY; /** * 起始点到终点的Y轴位移。 */ private int shift; /** * X Y坐标。 */ private double currentX, currentY; /** * 动画开始时间。 */ private long startTime; /** * 循环时间 */ private long cyclePeriod; /** * 动画正在进行时值为true,反之为false。 */ private boolean doing; /** * 进行动画展示的view */ private AnimationSurfaceView animationSurfaceView; public ScanAnimaitonStrategy(AnimationSurfaceView animationSurfaceView, int shift, long cyclePeriod) { this.animationSurfaceView = animationSurfaceView; this.shift = shift; this.cyclePeriod = cyclePeriod; initParams(); } public void start() { startTime = System.currentTimeMillis(); doing = true; } /** * 设置起始位置坐标 */ private void initParams() { int[] position = new int[2]; animationSurfaceView.getLocationInWindow(position); this.startX = position[0]; this.startY = position[1]; } /** * 根据当前时间计算小球的X/Y坐标。 */ public void compute() { long intervalTime = (System.currentTimeMillis() - startTime) % cyclePeriod; double angle = Math.toRadians(360 * 1.0d * intervalTime / cyclePeriod); int y = (int) (shift / 2 * Math.cos(angle)); y = Math.abs(y - shift/2); currentY = startY + y; doing = true; } @Override public boolean doing() { return doing; } public double getX() { return currentX; } public double getY() { return currentY; } public void cancel() { doing = false; } }
qizhenghao/Hello_Android
app/src/main/java/com/bruce/android/knowledge/custom_view/scanAnimation/ScanAnimaitonStrategy.java
Java
gpl-3.0
2,115
Wordpress 4.5.3 = 8fdd30960a4499c4e96caf8c5f43d6a2 Wordpress 4.1.13 = 9db7f2e6f8e36b05f7ced5f221e6254b Wordpress 3.8.16 = 9ebe6182b84d541634ded7e953aec282 Wordpress 3.4.2 = d59b6610752b975950f30735688efc36 Wordpress 5.1.1 = 2cde4ea09e0a8414786efdcfda5b9ae4 Wordpress 5.3.1 = 3f2b1e00c430271c6b9e901cc0857800
gohdan/DFC
known_files/hashes/wp-includes/js/tinymce/wp-tinymce.php
PHP
gpl-3.0
308
// needs Markdown.Converter.js at the moment (function () { var util = {}, position = {}, ui = {}, doc = window.document, re = window.RegExp, nav = window.navigator, SETTINGS = { lineLength: 72 }, // Used to work around some browser bugs where we can't use feature testing. uaSniffed = { isIE: /msie/.test(nav.userAgent.toLowerCase()), isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()), isOpera: /opera/.test(nav.userAgent.toLowerCase()) }; // ------------------------------------------------------------------- // YOUR CHANGES GO HERE // // I've tried to localize the things you are likely to change to // this area. // ------------------------------------------------------------------- // The text that appears on the upper part of the dialog box when // entering links. var linkDialogText = "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>"; var imageDialogText = "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br></p>"; // The default text that appears in the dialog input box when entering // links. var imageDefaultText = "http://"; var linkDefaultText = "http://"; var defaultHelpHoverTitle = "Markdown Editing Help"; // ------------------------------------------------------------------- // END OF YOUR CHANGES // ------------------------------------------------------------------- // help, if given, should have a property "handler", the click handler for the help button, // and can have an optional property "title" for the button's tooltip (defaults to "Markdown Editing Help"). // If help isn't given, not help button is created. // // The constructed editor object has the methods: // - getConverter() returns the markdown converter object that was passed to the constructor // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op. // - refreshPreview() forces the preview to be updated. This method is only available after run() was called. Markdown.Editor = function (markdownConverter, idPostfix, help) { idPostfix = idPostfix || ""; var hooks = this.hooks = new Markdown.HookCollection(); hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used. */ this.getConverter = function () { return markdownConverter; } var that = this, panels; this.run = function () { if (panels) return; // already initialized panels = new PanelCollection(idPostfix); var commandManager = new CommandManager(hooks); var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); }); var undoManager, uiManager; if (!/\?noundo/.test(doc.location.href)) { undoManager = new UndoManager(function () { previewManager.refresh(); if (uiManager) // not available on the first call uiManager.setUndoRedoButtonStates(); }, panels); this.textOperation = function (f) { undoManager.setCommandMode(); f(); that.refreshPreview(); } } uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, help); uiManager.setUndoRedoButtonStates(); var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); }; forceRefresh(); }; } // before: contains all the text in the input box BEFORE the selection. // after: contains all the text in the input box AFTER the selection. function Chunks() { } // startRegex: a regular expression to find the start tag // endRegex: a regular expresssion to find the end tag Chunks.prototype.findTags = function (startRegex, endRegex) { var chunkObj = this; var regex; if (startRegex) { regex = util.extendRegExp(startRegex, "", "$"); this.before = this.before.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); regex = util.extendRegExp(startRegex, "^", ""); this.selection = this.selection.replace(regex, function (match) { chunkObj.startTag = chunkObj.startTag + match; return ""; }); } if (endRegex) { regex = util.extendRegExp(endRegex, "", "$"); this.selection = this.selection.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); regex = util.extendRegExp(endRegex, "^", ""); this.after = this.after.replace(regex, function (match) { chunkObj.endTag = match + chunkObj.endTag; return ""; }); } }; // If remove is false, the whitespace is transferred // to the before/after regions. // // If remove is true, the whitespace disappears. Chunks.prototype.trimWhitespace = function (remove) { var beforeReplacer, afterReplacer, that = this; if (remove) { beforeReplacer = afterReplacer = ""; } else { beforeReplacer = function (s) { that.before += s; return ""; } afterReplacer = function (s) { that.after = s + that.after; return ""; } } this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer); }; Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) { if (nLinesBefore === undefined) { nLinesBefore = 1; } if (nLinesAfter === undefined) { nLinesAfter = 1; } nLinesBefore++; nLinesAfter++; var regexText; var replacementText; // chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985 if (navigator.userAgent.match(/Chrome/)) { "X".match(/()./); } this.selection = this.selection.replace(/(^\n*)/, ""); this.startTag = this.startTag + re.$1; this.selection = this.selection.replace(/(\n*$)/, ""); this.endTag = this.endTag + re.$1; this.startTag = this.startTag.replace(/(^\n*)/, ""); this.before = this.before + re.$1; this.endTag = this.endTag.replace(/(\n*$)/, ""); this.after = this.after + re.$1; if (this.before) { regexText = replacementText = ""; while (nLinesBefore--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.before = this.before.replace(new re(regexText + "$", ""), replacementText); } if (this.after) { regexText = replacementText = ""; while (nLinesAfter--) { regexText += "\\n?"; replacementText += "\n"; } if (findExtraNewlines) { regexText = "\\n*"; } this.after = this.after.replace(new re(regexText, ""), replacementText); } }; // end of Chunks // A collection of the important regions on the page. // Cached so we don't have to keep traversing the DOM. // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around // this issue: // Internet explorer has problems with CSS sprite buttons that use HTML // lists. When you click on the background image "button", IE will // select the non-existent link text and discard the selection in the // textarea. The solution to this is to cache the textarea selection // on the button's mousedown event and set a flag. In the part of the // code where we need to grab the selection, we check for the flag // and, if it's set, use the cached area instead of querying the // textarea. // // This ONLY affects Internet Explorer (tested on versions 6, 7 // and 8) and ONLY on button clicks. Keyboard shortcuts work // normally since the focus never leaves the textarea. function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); this.preview = doc.getElementById("wmd-preview" + postfix); this.input = doc.getElementById("wmd-input" + postfix); }; // Returns true if the DOM element is visible, false if it's hidden. // Checks if display is anything other than none. util.isVisible = function (elem) { if (window.getComputedStyle) { // Most browsers return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none"; } else if (elem.currentStyle) { // IE return elem.currentStyle["display"] !== "none"; } }; // Adds a listener callback to a DOM element which is fired on a specified // event. util.addEvent = function (elem, event, listener) { if (elem.attachEvent) { // IE only. The "on" is mandatory. elem.attachEvent("on" + event, listener); } else { // Other browsers. elem.addEventListener(event, listener, false); } }; // Removes a listener callback from a DOM element which is fired on a specified // event. util.removeEvent = function (elem, event, listener) { if (elem.detachEvent) { // IE only. The "on" is mandatory. elem.detachEvent("on" + event, listener); } else { // Other browsers. elem.removeEventListener(event, listener, false); } }; // Converts \r\n and \r to \n. util.fixEolChars = function (text) { text = text.replace(/\r\n/g, "\n"); text = text.replace(/\r/g, "\n"); return text; }; // Extends a regular expression. Returns a new RegExp // using pre + regex + post as the expression. // Used in a few functions where we have a base // expression and we want to pre- or append some // conditions to it (e.g. adding "$" to the end). // The flags are unchanged. // // regex is a RegExp, pre and post are strings. util.extendRegExp = function (regex, pre, post) { if (pre === null || pre === undefined) { pre = ""; } if (post === null || post === undefined) { post = ""; } var pattern = regex.toString(); var flags; // Replace the flags with empty space and store them. pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) { flags = flagsPart; return ""; }); // Remove the slash delimiters on the regular expression. pattern = pattern.replace(/(^\/|\/$)/g, ""); pattern = pre + pattern + post; return new re(pattern, flags); } // UNFINISHED // The assignment in the while loop makes jslint cranky. // I'll change it to a better loop later. position.getTop = function (elem, isInner) { var result = elem.offsetTop; if (!isInner) { while (elem = elem.offsetParent) { result += elem.offsetTop; } } return result; }; position.getHeight = function (elem) { return elem.offsetHeight || elem.scrollHeight; }; position.getWidth = function (elem) { return elem.offsetWidth || elem.scrollWidth; }; position.getPageSize = function () { var scrollWidth, scrollHeight; var innerWidth, innerHeight; // It's not very clear which blocks work with which browsers. if (self.innerHeight && self.scrollMaxY) { scrollWidth = doc.body.scrollWidth; scrollHeight = self.innerHeight + self.scrollMaxY; } else if (doc.body.scrollHeight > doc.body.offsetHeight) { scrollWidth = doc.body.scrollWidth; scrollHeight = doc.body.scrollHeight; } else { scrollWidth = doc.body.offsetWidth; scrollHeight = doc.body.offsetHeight; } if (self.innerHeight) { // Non-IE browser innerWidth = self.innerWidth; innerHeight = self.innerHeight; } else if (doc.documentElement && doc.documentElement.clientHeight) { // Some versions of IE (IE 6 w/ a DOCTYPE declaration) innerWidth = doc.documentElement.clientWidth; innerHeight = doc.documentElement.clientHeight; } else if (doc.body) { // Other versions of IE innerWidth = doc.body.clientWidth; innerHeight = doc.body.clientHeight; } var maxWidth = Math.max(scrollWidth, innerWidth); var maxHeight = Math.max(scrollHeight, innerHeight); return [maxWidth, maxHeight, innerWidth, innerHeight]; }; // Handles pushing and popping TextareaStates for undo/redo commands. // I should rename the stack variables to list. function UndoManager(callback, panels) { var undoObj = this; var undoStack = []; // A stack of undo states var stackPtr = 0; // The index of the current state var mode = "none"; var lastState; // The last state var timer; // The setTimeout handle for cancelling the timer var inputStateObj; // Set the mode for later logic steps. var setMode = function (newMode, noSave) { if (mode != newMode) { mode = newMode; if (!noSave) { saveState(); } } if (!uaSniffed.isIE || mode != "moving") { timer = setTimeout(refreshState, 1); } else { inputStateObj = null; } }; var refreshState = function (isInitialState) { inputStateObj = new TextareaState(panels, isInitialState); timer = undefined; }; this.setCommandMode = function () { mode = "command"; saveState(); timer = setTimeout(refreshState, 0); }; this.canUndo = function () { return stackPtr > 1; }; this.canRedo = function () { if (undoStack[stackPtr + 1]) { return true; } return false; }; // Removes the last state and restores it. this.undo = function () { if (undoObj.canUndo()) { if (lastState) { // What about setting state -1 to null or checking for undefined? lastState.restore(); lastState = null; } else { undoStack[stackPtr] = new TextareaState(panels); undoStack[--stackPtr].restore(); if (callback) { callback(); } } } mode = "none"; panels.input.focus(); refreshState(); }; // Redo an action. this.redo = function () { if (undoObj.canRedo()) { undoStack[++stackPtr].restore(); if (callback) { callback(); } } mode = "none"; panels.input.focus(); refreshState(); }; // Push the input area state to the stack. var saveState = function () { var currState = inputStateObj || new TextareaState(panels); if (!currState) { return false; } if (mode == "moving") { if (!lastState) { lastState = currState; } return; } if (lastState) { if (undoStack[stackPtr - 1].text != lastState.text) { undoStack[stackPtr++] = lastState; } lastState = null; } undoStack[stackPtr++] = currState; undoStack[stackPtr + 1] = null; if (callback) { callback(); } }; var handleCtrlYZ = function (event) { var handled = false; if (event.ctrlKey || event.metaKey) { // IE and Opera do not support charCode. var keyCode = event.charCode || event.keyCode; var keyCodeChar = String.fromCharCode(keyCode); switch (keyCodeChar) { case "y": undoObj.redo(); handled = true; break; case "z": if (!event.shiftKey) { undoObj.undo(); } else { undoObj.redo(); } handled = true; break; } } if (handled) { if (event.preventDefault) { event.preventDefault(); } if (window.event) { window.event.returnValue = false; } return; } }; // Set the mode depending on what is going on in the input area. var handleModeChange = function (event) { if (!event.ctrlKey && !event.metaKey) { var keyCode = event.keyCode; if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) { // 33 - 40: page up/dn and arrow keys // 63232 - 63235: page up/dn and arrow keys on safari setMode("moving"); } else if (keyCode == 8 || keyCode == 46 || keyCode == 127) { // 8: backspace // 46: delete // 127: delete setMode("deleting"); } else if (keyCode == 13) { // 13: Enter setMode("newlines"); } else if (keyCode == 27) { // 27: escape setMode("escape"); } else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) { // 16-20 are shift, etc. // 91: left window key // I think this might be a little messed up since there are // a lot of nonprinting keys above 20. setMode("typing"); } } }; var setEventHandlers = function () { util.addEvent(panels.input, "keypress", function (event) { // keyCode 89: y // keyCode 90: z if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) { event.preventDefault(); } }); var handlePaste = function () { if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) { if (timer == undefined) { mode = "paste"; saveState(); refreshState(); } } }; util.addEvent(panels.input, "keydown", handleCtrlYZ); util.addEvent(panels.input, "keydown", handleModeChange); util.addEvent(panels.input, "mousedown", function () { setMode("moving"); }); panels.input.onpaste = handlePaste; panels.input.ondrop = handlePaste; }; var init = function () { setEventHandlers(); refreshState(true); saveState(); }; init(); } // end of UndoManager // The input textarea state/contents. // This is used to implement undo/redo by the undo manager. function TextareaState(panels, isInitialState) { // Aliases var stateObj = this; var inputArea = panels.input; this.init = function () { if (!util.isVisible(inputArea)) { return; } if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box return; } this.setInputAreaSelectionStartEnd(); this.scrollTop = inputArea.scrollTop; if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) { this.text = inputArea.value; } } // Sets the selected text in the input box after we've performed an // operation. this.setInputAreaSelection = function () { if (!util.isVisible(inputArea)) { return; } if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) { inputArea.focus(); inputArea.selectionStart = stateObj.start; inputArea.selectionEnd = stateObj.end; inputArea.scrollTop = stateObj.scrollTop; } else if (doc.selection) { if (doc.activeElement && doc.activeElement !== inputArea) { return; } inputArea.focus(); var range = inputArea.createTextRange(); range.moveStart("character", -inputArea.value.length); range.moveEnd("character", -inputArea.value.length); range.moveEnd("character", stateObj.end); range.moveStart("character", stateObj.start); range.select(); } }; this.setInputAreaSelectionStartEnd = function () { if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) { stateObj.start = inputArea.selectionStart; stateObj.end = inputArea.selectionEnd; } else if (doc.selection) { stateObj.text = util.fixEolChars(inputArea.value); // IE loses the selection in the textarea when buttons are // clicked. On IE we cache the selection. Here, if something is cached, // we take it. var range = panels.ieCachedRange || doc.selection.createRange(); var fixedRange = util.fixEolChars(range.text); var marker = "\x07"; var markedRange = marker + fixedRange + marker; range.text = markedRange; var inputText = util.fixEolChars(inputArea.value); range.moveStart("character", -markedRange.length); range.text = fixedRange; stateObj.start = inputText.indexOf(marker); stateObj.end = inputText.lastIndexOf(marker) - marker.length; var len = stateObj.text.length - util.fixEolChars(inputArea.value).length; if (len) { range.moveStart("character", -fixedRange.length); while (len--) { fixedRange += "\n"; stateObj.end += 1; } range.text = fixedRange; } if (panels.ieCachedRange) stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange panels.ieCachedRange = null; this.setInputAreaSelection(); } }; // Restore this state into the input area. this.restore = function () { if (stateObj.text != undefined && stateObj.text != inputArea.value) { inputArea.value = stateObj.text; } this.setInputAreaSelection(); inputArea.scrollTop = stateObj.scrollTop; }; // Gets a collection of HTML chunks from the inptut textarea. this.getChunks = function () { var chunk = new Chunks(); chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start)); chunk.startTag = ""; chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end)); chunk.endTag = ""; chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end)); chunk.scrollTop = stateObj.scrollTop; return chunk; }; // Sets the TextareaState properties given a chunk of markdown. this.setChunks = function (chunk) { chunk.before = chunk.before + chunk.startTag; chunk.after = chunk.endTag + chunk.after; this.start = chunk.before.length; this.end = chunk.before.length + chunk.selection.length; this.text = chunk.before + chunk.selection + chunk.after; this.scrollTop = chunk.scrollTop; }; this.init(); }; function PreviewManager(converter, panels, previewRefreshCallback) { var managerObj = this; var timeout; var elapsedTime; var oldInputText; var maxDelay = 3000; var startType = "delayed"; // The other legal value is "manual" // Adds event listeners to elements var setupEvents = function (inputElem, listener) { util.addEvent(inputElem, "input", listener); inputElem.onpaste = listener; inputElem.ondrop = listener; util.addEvent(inputElem, "keypress", listener); util.addEvent(inputElem, "keydown", listener); }; var getDocScrollTop = function () { var result = 0; if (window.innerHeight) { result = window.pageYOffset; } else if (doc.documentElement && doc.documentElement.scrollTop) { result = doc.documentElement.scrollTop; } else if (doc.body) { result = doc.body.scrollTop; } return result; }; var makePreviewHtml = function () { // If there is no registered preview panel // there is nothing to do. if (!panels.preview) return; var text = panels.input.value; if (text && text == oldInputText) { return; // Input text hasn't changed. } else { oldInputText = text; } var prevTime = new Date().getTime(); text = converter.makeHtml(text); // Calculate the processing time of the HTML creation. // It's used as the delay time in the event listener. var currTime = new Date().getTime(); elapsedTime = currTime - prevTime; pushPreviewHtml(text); }; // setTimeout is already used. Used as an event listener. var applyTimeout = function () { if (timeout) { clearTimeout(timeout); timeout = undefined; } if (startType !== "manual") { var delay = 0; if (startType === "delayed") { delay = elapsedTime; } if (delay > maxDelay) { delay = maxDelay; } timeout = setTimeout(makePreviewHtml, delay); } }; var getScaleFactor = function (panel) { if (panel.scrollHeight <= panel.clientHeight) { return 1; } return panel.scrollTop / (panel.scrollHeight - panel.clientHeight); }; var setPanelScrollTops = function () { if (panels.preview) { panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview); } }; this.refresh = function (requiresRefresh) { if (requiresRefresh) { oldInputText = ""; makePreviewHtml(); } else { applyTimeout(); } }; this.processingTime = function () { return elapsedTime; }; var isFirstTimeFilled = true; // IE doesn't let you use innerHTML if the element is contained somewhere in a table // (which is the case for inline editing) -- in that case, detach the element, set the // value, and reattach. Yes, that *is* ridiculous. var ieSafePreviewSet = function (text) { var preview = panels.preview; var parent = preview.parentNode; var sibling = preview.nextSibling; parent.removeChild(preview); preview.innerHTML = text; if (!sibling) parent.appendChild(preview); else parent.insertBefore(preview, sibling); } var nonSuckyBrowserPreviewSet = function (text) { panels.preview.innerHTML = text; } var previewSetter; var previewSet = function (text) { if (previewSetter) return previewSetter(text); try { nonSuckyBrowserPreviewSet(text); previewSetter = nonSuckyBrowserPreviewSet; } catch (e) { previewSetter = ieSafePreviewSet; previewSetter(text); } }; var pushPreviewHtml = function (text) { var emptyTop = position.getTop(panels.input) - getDocScrollTop(); if (panels.preview) { previewSet(text); previewRefreshCallback(); } setPanelScrollTops(); if (isFirstTimeFilled) { isFirstTimeFilled = false; return; } var fullTop = position.getTop(panels.input) - getDocScrollTop(); if (uaSniffed.isIE) { setTimeout(function () { window.scrollBy(0, fullTop - emptyTop); }, 0); } else { window.scrollBy(0, fullTop - emptyTop); } }; var init = function () { setupEvents(panels.input, applyTimeout); makePreviewHtml(); if (panels.preview) { panels.preview.scrollTop = 0; } }; init(); }; // Creates the background behind the hyperlink text entry box. // And download dialog // Most of this has been moved to CSS but the div creation and // browser-specific hacks remain here. ui.createBackground = function () { var background = doc.createElement("div"), style = background.style; background.className = "wmd-prompt-background"; style.position = "absolute"; style.top = "0"; style.zIndex = "1000"; if (uaSniffed.isIE) { style.filter = "alpha(opacity=50)"; } else { style.opacity = "0.5"; } var pageSize = position.getPageSize(); style.height = pageSize[1] + "px"; if (uaSniffed.isIE) { style.left = doc.documentElement.scrollLeft; style.width = doc.documentElement.clientWidth; } else { style.left = "0"; style.width = "100%"; } doc.body.appendChild(background); return background; }; // This simulates a modal dialog box and asks for the URL when you // click the hyperlink or image buttons. // // text: The html for the input box. // defaultInputText: The default value that appears in the input box. // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel. // It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel // was chosen). ui.prompt = function (text, defaultInputText, callback) { // These variables need to be declared at this level since they are used // in multiple functions. var dialog; // The dialog box. var input; // The text box where you enter the hyperlink. if (defaultInputText === undefined) { defaultInputText = ""; } // Used as a keydown event handler. Esc dismisses the prompt. // Key code 27 is ESC. var checkEscape = function (key) { var code = (key.charCode || key.keyCode); if (code === 27) { close(true); } }; // Dismisses the hyperlink input box. // isCancel is true if we don't care about the input text. // isCancel is false if we are going to keep the text. var close = function (isCancel) { util.removeEvent(doc.body, "keydown", checkEscape); var text = input.value; if (isCancel) { text = null; } else { // Fixes common pasting errors. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://'); if (!/^(?:https?|ftp):\/\//.test(text)) text = 'http://' + text; } dialog.parentNode.removeChild(dialog); callback(text); return false; }; // Create the text input box form/window. var createDialog = function () { // The main dialog box. dialog = doc.createElement("div"); dialog.className = "wmd-prompt-dialog"; dialog.style.padding = "10px;"; dialog.style.position = "fixed"; dialog.style.width = "400px"; dialog.style.zIndex = "1001"; // The dialog text. var question = doc.createElement("div"); question.innerHTML = text; question.style.padding = "5px"; dialog.appendChild(question); // The web form container for the text box and buttons. var form = doc.createElement("form"), style = form.style; form.onsubmit = function () { return close(false); }; style.padding = "0"; style.margin = "0"; style.cssFloat = "left"; style.width = "100%"; style.textAlign = "center"; style.position = "relative"; dialog.appendChild(form); // The input text box input = doc.createElement("input"); input.type = "text"; input.value = defaultInputText; style = input.style; style.display = "block"; style.width = "80%"; style.marginLeft = style.marginRight = "auto"; form.appendChild(input); // The ok button var okButton = doc.createElement("input"); okButton.type = "button"; okButton.onclick = function () { return close(false); }; okButton.value = "OK"; style = okButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; // The cancel button var cancelButton = doc.createElement("input"); cancelButton.type = "button"; cancelButton.onclick = function () { return close(true); }; cancelButton.value = "Cancel"; style = cancelButton.style; style.margin = "10px"; style.display = "inline"; style.width = "7em"; form.appendChild(okButton); form.appendChild(cancelButton); util.addEvent(doc.body, "keydown", checkEscape); dialog.style.top = "50%"; dialog.style.left = "50%"; dialog.style.display = "block"; if (uaSniffed.isIE_5or6) { dialog.style.position = "absolute"; dialog.style.top = doc.documentElement.scrollTop + 200 + "px"; dialog.style.left = "50%"; } doc.body.appendChild(dialog); // This has to be done AFTER adding the dialog to the form if you // want it to be centered. dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px"; dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px"; }; // Why is this in a zero-length timeout? // Is it working around a browser bug? setTimeout(function () { createDialog(); var defTextLen = defaultInputText.length; if (input.selectionStart !== undefined) { input.selectionStart = 0; input.selectionEnd = defTextLen; } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(false); range.moveStart("character", -defTextLen); range.moveEnd("character", defTextLen); range.select(); } input.focus(); }, 0); }; function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions) { var inputBox = panels.input, buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements. makeSpritedButtonRow(); var keyEvent = "keydown"; if (uaSniffed.isOpera) { keyEvent = "keypress"; } util.addEvent(inputBox, keyEvent, function (key) { // Check to see if we have a button key and, if so execute the callback. if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) { var keyCode = key.charCode || key.keyCode; var keyCodeStr = String.fromCharCode(keyCode).toLowerCase(); switch (keyCodeStr) { case "b": doClick(buttons.bold); break; case "i": doClick(buttons.italic); break; case "l": doClick(buttons.link); break; case "q": doClick(buttons.quote); break; case "k": doClick(buttons.code); break; case "g": doClick(buttons.image); break; case "o": doClick(buttons.olist); break; case "u": doClick(buttons.ulist); break; case "h": doClick(buttons.heading); break; case "r": doClick(buttons.hr); break; case "y": doClick(buttons.redo); break; case "z": if (key.shiftKey) { doClick(buttons.redo); } else { doClick(buttons.undo); } break; default: return; } if (key.preventDefault) { key.preventDefault(); } if (window.event) { window.event.returnValue = false; } } }); // Auto-indent on shift-enter util.addEvent(inputBox, "keyup", function (key) { if (key.shiftKey && !key.ctrlKey && !key.metaKey) { var keyCode = key.charCode || key.keyCode; // Character 13 is Enter if (keyCode === 13) { var fakeButton = {}; fakeButton.textOp = bindCommand("doAutoindent"); doClick(fakeButton); } } }); // special handler because IE clears the context of the textbox on ESC if (uaSniffed.isIE) { util.addEvent(inputBox, "keydown", function (key) { var code = key.keyCode; if (code === 27) { return false; } }); } // Perform the button's action. function doClick(button) { inputBox.focus(); if (button.textOp) { if (undoManager) { undoManager.setCommandMode(); } var state = new TextareaState(panels); if (!state) { return; } var chunks = state.getChunks(); // Some commands launch a "modal" prompt dialog. Javascript // can't really make a modal dialog box and the WMD code // will continue to execute while the dialog is displayed. // This prevents the dialog pattern I'm used to and means // I can't do something like this: // // var link = CreateLinkDialog(); // makeMarkdownLink(link); // // Instead of this straightforward method of handling a // dialog I have to pass any code which would execute // after the dialog is dismissed (e.g. link creation) // in a function parameter. // // Yes this is awkward and I think it sucks, but there's // no real workaround. Only the image and link code // create dialogs and require the function pointers. var fixupInputArea = function () { inputBox.focus(); if (chunks) { state.setChunks(chunks); } state.restore(); previewManager.refresh(); }; var noCleanup = button.textOp(chunks, fixupInputArea); if (!noCleanup) { fixupInputArea(); } } if (button.execute) { button.execute(undoManager); } }; function setupButton(button, isEnabled) { var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var image = button.getElementsByTagName("span")[0]; if (isEnabled) { image.style.backgroundPosition = button.XShift + " " + normalYShift; button.onmouseover = function () { image.style.backgroundPosition = this.XShift + " " + highlightYShift; }; button.onmouseout = function () { image.style.backgroundPosition = this.XShift + " " + normalYShift; }; // IE tries to select the background image "button" text (it's // implemented in a list item) so we have to cache the selection // on mousedown. if (uaSniffed.isIE) { button.onmousedown = function () { if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection return; } panels.ieCachedRange = document.selection.createRange(); panels.ieCachedScrollTop = panels.input.scrollTop; }; } if (!button.isHelp) { button.onclick = function () { if (this.onmouseout) { this.onmouseout(); } doClick(this); return false; } } } else { image.style.backgroundPosition = button.XShift + " " + disabledYShift; button.onmouseover = button.onmouseout = button.onclick = function () { }; } } function bindCommand(method) { if (typeof method === "string") method = commandManager[method]; return function () { method.apply(commandManager, arguments); } } function makeSpritedButtonRow() { var buttonBar = panels.buttonBar; var normalYShift = "0px"; var disabledYShift = "-20px"; var highlightYShift = "-40px"; var buttonRow = document.createElement("ul"); buttonRow.id = "wmd-button-row" + postfix; buttonRow.className = 'wmd-button-row'; buttonRow = buttonBar.appendChild(buttonRow); var xPosition = 0; var makeButton = function (id, title, XShift, textOp) { var button = document.createElement("li"); button.className = "wmd-button"; button.style.left = xPosition + "px"; xPosition += 25; var buttonImage = document.createElement("span"); button.id = id + postfix; button.appendChild(buttonImage); button.title = title; button.XShift = XShift; if (textOp) button.textOp = textOp; setupButton(button, true); buttonRow.appendChild(button); return button; }; var makeSpacer = function (num) { var spacer = document.createElement("li"); spacer.className = "wmd-spacer wmd-spacer" + num; spacer.id = "wmd-spacer" + num + postfix; buttonRow.appendChild(spacer); xPosition += 25; } buttons.bold = makeButton("wmd-bold-button", "Strong <strong> Ctrl+B", "0px", bindCommand("doBold")); buttons.italic = makeButton("wmd-italic-button", "Emphasis <em> Ctrl+I", "-20px", bindCommand("doItalic")); makeSpacer(1); buttons.link = makeButton("wmd-link-button", "Hyperlink <a> Ctrl+L", "-40px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, false); })); buttons.quote = makeButton("wmd-quote-button", "Blockquote <blockquote> Ctrl+Q", "-60px", bindCommand("doBlockquote")); buttons.code = makeButton("wmd-code-button", "Code Sample <pre><code> Ctrl+K", "-80px", bindCommand("doCode")); buttons.image = makeButton("wmd-image-button", "Image <img> Ctrl+G", "-100px", bindCommand(function (chunk, postProcessing) { return this.doLinkOrImage(chunk, postProcessing, true); })); makeSpacer(2); buttons.olist = makeButton("wmd-olist-button", "Numbered List <ol> Ctrl+O", "-120px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, true); })); buttons.ulist = makeButton("wmd-ulist-button", "Bulleted List <ul> Ctrl+U", "-140px", bindCommand(function (chunk, postProcessing) { this.doList(chunk, postProcessing, false); })); buttons.heading = makeButton("wmd-heading-button", "Heading <h1>/<h2> Ctrl+H", "-160px", bindCommand("doHeading")); buttons.hr = makeButton("wmd-hr-button", "Horizontal Rule <hr> Ctrl+R", "-180px", bindCommand("doHorizontalRule")); makeSpacer(3); buttons.undo = makeButton("wmd-undo-button", "Undo - Ctrl+Z", "-200px", null); buttons.undo.execute = function (manager) { if (manager) manager.undo(); }; var redoTitle = /win/.test(nav.platform.toLowerCase()) ? "Redo - Ctrl+Y" : "Redo - Ctrl+Shift+Z"; // mac and other non-Windows platforms buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null); buttons.redo.execute = function (manager) { if (manager) manager.redo(); }; if (helpOptions) { var helpButton = document.createElement("li"); var helpButtonImage = document.createElement("span"); helpButton.appendChild(helpButtonImage); helpButton.className = "wmd-button wmd-help-button"; helpButton.id = "wmd-help-button" + postfix; helpButton.XShift = "-240px"; helpButton.isHelp = true; helpButton.style.right = "0px"; helpButton.title = helpOptions.title || defaultHelpHoverTitle; helpButton.onclick = helpOptions.handler; setupButton(helpButton, true); buttonRow.appendChild(helpButton); buttons.help = helpButton; } setUndoRedoButtonStates(); } function setUndoRedoButtonStates() { if (undoManager) { setupButton(buttons.undo, undoManager.canUndo()); setupButton(buttons.redo, undoManager.canRedo()); } }; this.setUndoRedoButtonStates = setUndoRedoButtonStates; } function CommandManager(pluginHooks) { this.hooks = pluginHooks; } var commandProto = CommandManager.prototype; // The markdown symbols - 4 spaces = code, > = blockquote, etc. commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)"; // Remove markdown symbols from the chunk selection. commandProto.unwrap = function (chunk) { var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g"); chunk.selection = chunk.selection.replace(txt, "$1 $2"); }; commandProto.wrap = function (chunk, len) { this.unwrap(chunk); var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"), that = this; chunk.selection = chunk.selection.replace(regex, function (line, marked) { if (new re("^" + that.prefixes, "").test(line)) { return line; } return marked + "\n"; }); chunk.selection = chunk.selection.replace(/\s+$/, ""); }; commandProto.doBold = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 2, "strong text"); }; commandProto.doItalic = function (chunk, postProcessing) { return this.doBorI(chunk, postProcessing, 1, "emphasized text"); }; // chunk: The selected region that will be enclosed with */** // nStars: 1 for italics, 2 for bold // insertText: If you just click the button without highlighting text, this gets inserted commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) { // Get rid of whitespace and fixup newlines. chunk.trimWhitespace(); chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n"); // Look for stars before and after. Is the chunk already marked up? // note that these regex matches cannot fail var starsBefore = /(\**$)/.exec(chunk.before)[0]; var starsAfter = /(^\**)/.exec(chunk.after)[0]; var prevStars = Math.min(starsBefore.length, starsAfter.length); // Remove stars if we have to since the button acts as a toggle. if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) { chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), ""); chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), ""); } else if (!chunk.selection && starsAfter) { // It's not really clear why this code is necessary. It just moves // some arbitrary stuff around. chunk.after = chunk.after.replace(/^([*_]*)/, ""); chunk.before = chunk.before.replace(/(\s?)$/, ""); var whitespace = re.$1; chunk.before = chunk.before + starsAfter + whitespace; } else { // In most cases, if you don't have any selected text and click the button // you'll get a selected, marked up region with the default text inserted. if (!chunk.selection && !starsAfter) { chunk.selection = insertText; } // Add the true markup. var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ? chunk.before = chunk.before + markup; chunk.after = markup + chunk.after; } return; }; commandProto.stripLinkDefs = function (text, defsToAdd) { text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm, function (totalMatch, id, link, newlines, title) { defsToAdd[id] = totalMatch.replace(/\s*$/, ""); if (newlines) { // Strip the title and return that separately. defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, ""); return newlines + title; } return ""; }); return text; }; commandProto.addLinkDef = function (chunk, linkDef) { var refNumber = 0; // The current reference number var defsToAdd = {}; // // Start with a clean slate by removing all previous link definitions. chunk.before = this.stripLinkDefs(chunk.before, defsToAdd); chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd); chunk.after = this.stripLinkDefs(chunk.after, defsToAdd); var defs = ""; var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g; var addDefNumber = function (def) { refNumber++; def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:"); defs += "\n" + def; }; // note that // a) the recursive call to getLink cannot go infinite, because by definition // of regex, inner is always a proper substring of wholeMatch, and // b) more than one level of nesting is neither supported by the regex // nor making a lot of sense (the only use case for nesting is a linked image) var getLink = function (wholeMatch, before, inner, afterInner, id, end) { inner = inner.replace(regex, getLink); if (defsToAdd[id]) { addDefNumber(defsToAdd[id]); return before + inner + afterInner + refNumber + end; } return wholeMatch; }; chunk.before = chunk.before.replace(regex, getLink); if (linkDef) { addDefNumber(linkDef); } else { chunk.selection = chunk.selection.replace(regex, getLink); } var refOut = refNumber; chunk.after = chunk.after.replace(regex, getLink); if (chunk.after) { chunk.after = chunk.after.replace(/\n*$/, ""); } if (!chunk.after) { chunk.selection = chunk.selection.replace(/\n*$/, ""); } chunk.after += "\n\n" + defs; return refOut; }; // takes the line as entered into the add link/as image dialog and makes // sure the URL and the optinal title are "nice". function properlyEncoded(linkdef) { return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) { link = link.replace(/\?.*$/, function (querypart) { return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical }); link = decodeURIComponent(link); // unencode first, to prevent double encoding link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29'); link = link.replace(/\?.*$/, function (querypart) { return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded }); if (title) { title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, ""); title = $.trim(title).replace(/"/g, "quot;").replace(/\(/g, "&#40;").replace(/\)/g, "&#41;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } return title ? link + ' "' + title + '"' : link; }); } commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) { chunk.trimWhitespace(); chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/); var background; if (chunk.endTag.length > 1 && chunk.startTag.length > 0) { chunk.startTag = chunk.startTag.replace(/!?\[/, ""); chunk.endTag = ""; this.addLinkDef(chunk, null); } else { // We're moving start and end tag back into the selection, since (as we're in the else block) we're not // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the // link text. linkEnteredCallback takes care of escaping any brackets. chunk.selection = chunk.startTag + chunk.selection + chunk.endTag; chunk.startTag = chunk.endTag = ""; if (/\n\n/.test(chunk.selection)) { this.addLinkDef(chunk, null); return; } var that = this; // The function to be executed when you enter a link and press OK or Cancel. // Marks up the link and adds the ref. var linkEnteredCallback = function (link) { background.parentNode.removeChild(background); if (link !== null) { // ( $1 // [^\\] anything that's not a backslash // (?:\\\\)* an even number (this includes zero) of backslashes // ) // (?= followed by // [[\]] an opening or closing bracket // ) // // In other words, a non-escaped bracket. These have to be escaped now to make sure they // don't count as the end of the link or similar. // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets), // the bracket in one match may be the "not a backslash" character in the next match, so it // should not be consumed by the first match. // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the // start of the string, so this also works if the selection begins with a bracket. We cannot solve // this by anchoring with ^, because in the case that the selection starts with two brackets, this // would mean a zero-width match at the start. Since zero-width matches advance the string position, // the first bracket could then not act as the "not a backslash" for the second. chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1); var linkDef = " [999]: " + properlyEncoded(link); var num = that.addLinkDef(chunk, linkDef); chunk.startTag = isImage ? "![" : "["; chunk.endTag = "][" + num + "]"; if (!chunk.selection) { if (isImage) { chunk.selection = "enter image description here"; } else { chunk.selection = "enter link description here"; } } } postProcessing(); }; background = ui.createBackground(); if (isImage) { if (!this.hooks.insertImageDialog(linkEnteredCallback)) ui.prompt(imageDialogText, imageDefaultText, linkEnteredCallback); } else { ui.prompt(linkDialogText, linkDefaultText, linkEnteredCallback); } return true; } }; // When making a list, hitting shift-enter will put your cursor on the next line // at the current indent level. commandProto.doAutoindent = function (chunk, postProcessing) { var commandMgr = this, fakeSelection = false; chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n"); chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n"); // There's no selection, end the cursor wasn't at the end of the line: // The user wants to split the current list item / code line / blockquote line // (for the latter it doesn't really matter) in two. Temporarily select the // (rest of the) line to achieve this. if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) { chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) { chunk.selection = wholeMatch; return ""; }); fakeSelection = true; } if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doList) { commandMgr.doList(chunk); } } if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) { if (commandMgr.doBlockquote) { commandMgr.doBlockquote(chunk); } } if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { if (commandMgr.doCode) { commandMgr.doCode(chunk); } } if (fakeSelection) { chunk.after = chunk.selection + chunk.after; chunk.selection = ""; } }; commandProto.doBlockquote = function (chunk, postProcessing) { chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/, function (totalMatch, newlinesBefore, text, newlinesAfter) { chunk.before += newlinesBefore; chunk.after = newlinesAfter + chunk.after; return text; }); chunk.before = chunk.before.replace(/(>[ \t]*)$/, function (totalMatch, blankLine) { chunk.selection = blankLine + chunk.selection; return ""; }); chunk.selection = chunk.selection.replace(/^(\s|>)+$/, ""); chunk.selection = chunk.selection || "Blockquote"; // The original code uses a regular expression to find out how much of the // text *directly before* the selection already was a blockquote: /* if (chunk.before) { chunk.before = chunk.before.replace(/\n?$/, "\n"); } chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/, function (totalMatch) { chunk.startTag = totalMatch; return ""; }); */ // This comes down to: // Go backwards as many lines a possible, such that each line // a) starts with ">", or // b) is almost empty, except for whitespace, or // c) is preceeded by an unbroken chain of non-empty lines // leading up to a line that starts with ">" and at least one more character // and in addition // d) at least one line fulfills a) // // Since this is essentially a backwards-moving regex, it's susceptible to // catstrophic backtracking and can cause the browser to hang; // see e.g. http://meta.stackoverflow.com/questions/9807. // // Hence we replaced this by a simple state machine that just goes through the // lines and checks for a), b), and c). var match = "", leftOver = "", line; if (chunk.before) { var lines = chunk.before.replace(/\n$/, "").split("\n"); var inChain = false; for (var i = 0; i < lines.length; i++) { var good = false; line = lines[i]; inChain = inChain && line.length > 0; // c) any non-empty line continues the chain if (/^>/.test(line)) { // a) good = true; if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain inChain = true; } else if (/^[ \t]*$/.test(line)) { // b) good = true; } else { good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain } if (good) { match += line + "\n"; } else { leftOver += match + line; match = "\n"; } } if (!/(^|\n)>/.test(match)) { // d) leftOver += match; match = ""; } } chunk.startTag = match; chunk.before = leftOver; // end of change if (chunk.after) { chunk.after = chunk.after.replace(/^\n?/, "\n"); } chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/, function (totalMatch) { chunk.endTag = totalMatch; return ""; } ); var replaceBlanksInTags = function (useBracket) { var replacement = useBracket ? "> " : ""; if (chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } if (chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/, function (totalMatch, markdown) { return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n"; }); } }; if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) { this.wrap(chunk, SETTINGS.lineLength - 2); chunk.selection = chunk.selection.replace(/^/gm, "> "); replaceBlanksInTags(true); chunk.skipLines(); } else { chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, ""); this.unwrap(chunk); replaceBlanksInTags(false); if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) { chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n"); } if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) { chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n"); } } chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection); if (!/\n/.test(chunk.selection)) { chunk.selection = chunk.selection.replace(/^(> *)/, function (wholeMatch, blanks) { chunk.startTag += blanks; return ""; }); } }; commandProto.doCode = function (chunk, postProcessing) { var hasTextBefore = /\S[ ]*$/.test(chunk.before); var hasTextAfter = /^[ ]*\S/.test(chunk.after); // Use 'four space' markdown if the selection is on its own // line or is multiline. if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) { chunk.before = chunk.before.replace(/[ ]{4}$/, function (totalMatch) { chunk.selection = totalMatch + chunk.selection; return ""; }); var nLinesBack = 1; var nLinesForward = 1; if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) { nLinesBack = 0; } if (/^\n(\t|[ ]{4,})/.test(chunk.after)) { nLinesForward = 0; } chunk.skipLines(nLinesBack, nLinesForward); if (!chunk.selection) { chunk.startTag = " "; chunk.selection = "enter code here"; } else { if (/^[ ]{0,3}\S/m.test(chunk.selection)) { if (/\n/.test(chunk.selection)) chunk.selection = chunk.selection.replace(/^/gm, " "); else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior chunk.before += " "; } else { chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, ""); } } } else { // Use backticks (`) to delimit the code block. chunk.trimWhitespace(); chunk.findTags(/`/, /`/); if (!chunk.startTag && !chunk.endTag) { chunk.startTag = chunk.endTag = "`"; if (!chunk.selection) { chunk.selection = "enter code here"; } } else if (chunk.endTag && !chunk.startTag) { chunk.before += chunk.endTag; chunk.endTag = ""; } else { chunk.startTag = chunk.endTag = ""; } } }; commandProto.doList = function (chunk, postProcessing, isNumberedList) { // These are identical except at the very beginning and end. // Should probably use the regex extension function to make this clearer. var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/; var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/; // The default bullet is a dash but others are possible. // This has nothing to do with the particular HTML bullet, // it's just a markdown bullet. var bullet = "-"; // The number in a numbered list. var num = 1; // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list. var getItemPrefix = function () { var prefix; if (isNumberedList) { prefix = " " + num + ". "; num++; } else { prefix = " " + bullet + " "; } return prefix; }; // Fixes the prefixes of the other list items. var getPrefixedItem = function (itemText) { // The numbering flag is unset when called by autoindent. if (isNumberedList === undefined) { isNumberedList = /^\s*\d/.test(itemText); } // Renumber/bullet the list element. itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm, function (_) { return getItemPrefix(); }); return itemText; }; chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null); if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) { chunk.before += chunk.startTag; chunk.startTag = ""; } if (chunk.startTag) { var hasDigits = /\d+[.]/.test(chunk.startTag); chunk.startTag = ""; chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n"); this.unwrap(chunk); chunk.skipLines(); if (hasDigits) { // Have to renumber the bullet points if this is a numbered list. chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem); } if (isNumberedList == hasDigits) { return; } } var nLinesUp = 1; chunk.before = chunk.before.replace(previousItemsRegex, function (itemText) { if (/^\s*([*+-])/.test(itemText)) { bullet = re.$1; } nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); if (!chunk.selection) { chunk.selection = "List item"; } var prefix = getItemPrefix(); var nLinesDown = 1; chunk.after = chunk.after.replace(nextItemsRegex, function (itemText) { nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0; return getPrefixedItem(itemText); }); chunk.trimWhitespace(true); chunk.skipLines(nLinesUp, nLinesDown, true); chunk.startTag = prefix; var spaces = prefix.replace(/./g, " "); this.wrap(chunk, SETTINGS.lineLength - spaces.length); chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces); }; commandProto.doHeading = function (chunk, postProcessing) { // Remove leading/trailing whitespace and reduce internal spaces to single spaces. chunk.selection = chunk.selection.replace(/\s+/g, " "); chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, ""); // If we clicked the button with no selected text, we just // make a level 2 hash header around some default text. if (!chunk.selection) { chunk.startTag = "## "; chunk.selection = "Heading"; chunk.endTag = " ##"; return; } var headerLevel = 0; // The existing header level of the selected text. // Remove any existing hash heading markdown and save the header level. chunk.findTags(/#+[ ]*/, /[ ]*#+/); if (/#+/.test(chunk.startTag)) { headerLevel = re.lastMatch.length; } chunk.startTag = chunk.endTag = ""; // Try to get the current header level by looking for - and = in the line // below the selection. chunk.findTags(null, /\s?(-+|=+)/); if (/=+/.test(chunk.endTag)) { headerLevel = 1; } if (/-+/.test(chunk.endTag)) { headerLevel = 2; } // Skip to the next line so we can create the header markdown. chunk.startTag = chunk.endTag = ""; chunk.skipLines(1, 1); // We make a level 2 header if there is no current header. // If there is a header level, we substract one from the header level. // If it's already a level 1 header, it's removed. var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1; if (headerLevelToCreate > 0) { // The button only creates level 1 and 2 underline headers. // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner? var headerChar = headerLevelToCreate >= 2 ? "-" : "="; var len = chunk.selection.length; if (len > SETTINGS.lineLength) { len = SETTINGS.lineLength; } chunk.endTag = "\n"; while (len--) { chunk.endTag += headerChar; } } }; commandProto.doHorizontalRule = function (chunk, postProcessing) { chunk.startTag = "----------\n"; chunk.selection = ""; chunk.skipLines(2, 1, true); } })();
MitchellMcKenna/LifePress
public/scripts/pagedown/Markdown.Editor.js
JavaScript
gpl-3.0
80,757
package de.jdellert.iwsa.sequence; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * Symbol table for mapping IPA segments to integers for efficient internal * representation. The first two integers are always used for special symbols: 0 * ~ #: the word boundary symbol 1 ~ -: the gap symbol * */ public class PhoneticSymbolTable implements Serializable { private static final long serialVersionUID = -8825447220839372572L; private String[] idToSymbol; private Map<String, Integer> symbolToID; public PhoneticSymbolTable(Collection<String> symbols) { this.idToSymbol = new String[symbols.size() + 2]; this.symbolToID = new TreeMap<String, Integer>(); idToSymbol[0] = "#"; idToSymbol[1] = "-"; symbolToID.put("#", 0); symbolToID.put("-", 1); int nextID = 2; for (String symbol : symbols) { idToSymbol[nextID] = symbol; symbolToID.put(symbol, nextID); nextID++; } } public Integer toInt(String symbol) { return symbolToID.get(symbol); } public String toSymbol(int id) { return idToSymbol[id]; } public int[] encode(String[] segments) { int[] segmentIDs = new int[segments.length]; for (int idx = 0; idx < segments.length; idx++) { segmentIDs[idx] = symbolToID.get(segments[idx]); } return segmentIDs; } public String[] decode(int[] segmentIDs) { String[] segments = new String[segmentIDs.length]; for (int idx = 0; idx < segmentIDs.length; idx++) { segments[idx] = idToSymbol[segmentIDs[idx]]; } return segments; } public Set<String> getDefinedSymbols() { return new TreeSet<String>(symbolToID.keySet()); } public int getSize() { return idToSymbol.length; } public String toSymbolPair(int symbolPairID) { return "(" + toSymbol(symbolPairID / idToSymbol.length) + "," + toSymbol(symbolPairID % idToSymbol.length) + ")"; } public String toString() { StringBuilder line1 = new StringBuilder(); StringBuilder line2 = new StringBuilder(); for (int i = 0; i < idToSymbol.length; i++) { line1.append(i + "\t"); line2.append(idToSymbol[i] + "\t"); } return line1 + "\n" + line2; } }
jdellert/iwsa
src/de/jdellert/iwsa/sequence/PhoneticSymbolTable.java
Java
gpl-3.0
2,258
/* * GNU LESSER GENERAL PUBLIC LICENSE * Version 3, 29 June 2007 * * Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> * Everyone is permitted to copy and distribute verbatim copies * of this license document, but changing it is not allowed. * * You can view LICENCE file for details. * * @author The Dragonet Team */ package org.dragonet.proxy.network.translator; import java.util.Iterator; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.spacehq.mc.protocol.data.message.Message; public final class MessageTranslator { public static String translate(Message message) { String ret = message.getFullText(); /* * It is a JSON message? */ try { /* * Do not ask me why, but json strings has colors. * Changing this allows colors in plain texts! yay! */ JSONObject jObject = null; if (message.getFullText().startsWith("{") && message.getFullText().endsWith("}")) { jObject = new JSONObject(message.getFullText()); } else { jObject = new JSONObject(message.toJsonString()); } /* * Let's iterate! */ ret = handleKeyObject(jObject); } catch (JSONException e) { /* * If any exceptions happens, then: * * The JSON message is buggy or * * It isn't a JSON message * * So, if any exceptions happens, we send the original message */ } return ret; } public static String handleKeyObject(JSONObject jObject) throws JSONException { String chatMessage = ""; Iterator<String> iter = jObject.keys(); while (iter.hasNext()) { String key = iter.next(); try { if (key.equals("color")) { String color = jObject.getString(key); if (color.equals("light_purple")) { chatMessage = chatMessage + "§d"; } if (color.equals("blue")) { chatMessage = chatMessage + "§9"; } if (color.equals("aqua")) { chatMessage = chatMessage + "§b"; } if (color.equals("gold")) { chatMessage = chatMessage + "§6"; } if (color.equals("green")) { chatMessage = chatMessage + "§a"; } if (color.equals("white")) { chatMessage = chatMessage + "§f"; } if (color.equals("yellow")) { chatMessage = chatMessage + "§e"; } if (color.equals("gray")) { chatMessage = chatMessage + "§7"; } if (color.equals("red")) { chatMessage = chatMessage + "§c"; } if (color.equals("black")) { chatMessage = chatMessage + "§0"; } if (color.equals("dark_green")) { chatMessage = chatMessage + "§2"; } if (color.equals("dark_gray")) { chatMessage = chatMessage + "§8"; } if (color.equals("dark_red")) { chatMessage = chatMessage + "§4"; } if (color.equals("dark_blue")) { chatMessage = chatMessage + "§1"; } if (color.equals("dark_aqua")) { chatMessage = chatMessage + "§3"; } if (color.equals("dark_purple")) { chatMessage = chatMessage + "§5"; } } if (key.equals("bold")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§l"; } } if (key.equals("italic")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§o"; } } if (key.equals("underlined")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§n"; } } if (key.equals("strikethrough")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§m"; } } if (key.equals("obfuscated")) { String bold = jObject.getString(key); if (bold.equals("true")) { chatMessage = chatMessage + "§k"; } } if (key.equals("text")) { /* * We only need the text message from the JSON. */ String jsonMessage = jObject.getString(key); chatMessage = chatMessage + jsonMessage; continue; } if (jObject.get(key) instanceof JSONArray) { chatMessage += handleKeyArray(jObject.getJSONArray(key)); } if (jObject.get(key) instanceof JSONObject) { chatMessage += handleKeyObject(jObject.getJSONObject(key)); } } catch (JSONException e) { } } return chatMessage; } public static String handleKeyArray(JSONArray jObject) throws JSONException { String chatMessage = ""; JSONObject jsonObject = jObject.toJSONObject(jObject); Iterator<String> iter = jsonObject.keys(); while (iter.hasNext()) { String key = iter.next(); try { /* * We only need the text message from the JSON. */ if (key.equals("text")) { String jsonMessage = jsonObject.getString(key); chatMessage = chatMessage + jsonMessage; continue; } if (jsonObject.get(key) instanceof JSONArray) { handleKeyArray(jsonObject.getJSONArray(key)); } if (jsonObject.get(key) instanceof JSONObject) { handleKeyObject(jsonObject.getJSONObject(key)); } } catch (JSONException e) { } } return chatMessage; } }
WeaveMN/DragonProxy
src/main/java/org/dragonet/proxy/network/translator/MessageTranslator.java
Java
gpl-3.0
7,266
/* * LBFGS.java * * Copyright (C) 2016 Pavel Prokhorov (pavelvpster@gmail.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.interactiverobotics.ml.optimization; import static org.interactiverobotics.ml.optimization.OptimizationResult.Status.*; import org.apache.log4j.Logger; import org.interactiverobotics.math.Vector; import java.util.Objects; /** * Limited-memory BFGS. * * https://en.wikipedia.org/wiki/Limited-memory_BFGS * * Liu, D. C.; Nocedal, J. (1989). "On the Limited Memory Method for Large Scale Optimization". * Mathematical Programming B. 45 (3): 503–528. doi:10.1007/BF01589116. * */ public final class LBFGS extends AbstractOptimizer implements Optimizer { private static final Logger LOG = Logger.getLogger(LBFGS.class); public LBFGS(final OptimizableFunction function) { this.function = Objects.requireNonNull(function); } private final OptimizableFunction function; /** * Maximum number of iterations. */ private int maxIterations = 100; /** * The number of corrections to approximate the inverse Hessian matrix. */ private int m = 6; /** * Epsilon for convergence test. * Controls the accuracy of with which the solution is to be found. */ private double epsilon = 1.0E-5; /** * Distance (in iterations) to calculate the rate of decrease of the function. * Used in delta convergence test. */ private int past = 3; /** * Minimum rate of decrease of the function. * Used in delta convergence test. */ private double delta = 1.0E-5; /** * Maximum number of line search iterations. */ private int maxLineSearchIterations = 100; /** * Continue optimization if line search returns {@code MAX_ITERATION_REACHED}. */ private boolean continueOnMaxLineSearchIterations = false; public int getMaxIterations() { return maxIterations; } public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; } public int getM() { return m; } public void setM(int m) { this.m = m; } public double getEpsilon() { return epsilon; } public void setEpsilon(double epsilon) { this.epsilon = epsilon; } public int getPast() { return past; } public void setPast(int past) { this.past = past; } public double getDelta() { return delta; } public void setDelta(double delta) { this.delta = delta; } public int getMaxLineSearchIterations() { return maxLineSearchIterations; } public void setMaxLineSearchIterations(int maxLineSearchIterations) { this.maxLineSearchIterations = maxLineSearchIterations; } public boolean isContinueOnMaxLineSearchIterations() { return continueOnMaxLineSearchIterations; } public void setContinueOnMaxLineSearchIterations(boolean continueOnMaxLineSearchIterations) { this.continueOnMaxLineSearchIterations = continueOnMaxLineSearchIterations; } @Override public OptimizationResult optimize() { LOG.debug("Limited-memory BFGS optimize..."); final BacktrackingLineSearch lineSearch = new BacktrackingLineSearch(function); lineSearch.setMaxIterations(maxLineSearchIterations); final State[] states = new State[m]; for (int i = 0; i < m; i ++) { states[i] = new State(); } int currentStateIndex = 0; final double[] pastValues; if (past > 0) { pastValues = new double[past]; pastValues[0] = function.getValue(); } else { pastValues = null; } Vector parameters = function.getParameters(); Vector gradient = function.getValueGradient(); final double initialGradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0); LOG.debug("Initial gradient norm = " + initialGradientNorm); if (initialGradientNorm <= epsilon) { LOG.debug("Already minimized"); return new OptimizationResult(ALREADY_MINIMIZED, parameters, function.getValue(), 0); } Vector direction = gradient.copy().neg(); double step = Vector.dotProduct(direction, direction); Vector prevParameters, prevGradient; OptimizationResult.Status status = MAX_ITERATION_REACHED; int iteration; for (iteration = 1; iteration <= maxIterations; iteration ++) { LOG.debug("Iteration " + iteration); // save previous Parameters and Gradient prevParameters = parameters.copy(); prevGradient = gradient.copy(); // search for optimal Step LOG.debug("Direction: " + direction + " Step = " + step); lineSearch.setDirection(direction); lineSearch.setInitialStep(step); final OptimizationResult lineSearchResult = lineSearch.optimize(); if (!lineSearchResult.hasConverged()) { LOG.error("Line search not converged: " + lineSearchResult.getStatus()); final boolean continueOptimization = (lineSearchResult.getStatus() == MAX_ITERATION_REACHED) && continueOnMaxLineSearchIterations; if (!continueOptimization) { // step back function.setParameters(prevParameters); status = lineSearchResult.getStatus(); break; } } parameters = function.getParameters(); gradient = function.getValueGradient(); final double value = function.getValue(); final boolean stop = fireOptimizerStep(parameters, value, direction, iteration); if (stop) { LOG.debug("Stop"); status = STOP; break; } // test for convergence final double gradientNorm = gradient.getLength() / Math.max(parameters.getLength(), 1.0); LOG.debug("Gradient norm = " + gradientNorm); if (gradientNorm <= epsilon) { LOG.debug("Success"); status = SUCCESS; break; } // delta convergence test if (past > 0) { if (iteration > past) { // relative improvement from the past final double rate = (pastValues[iteration % past] - value) / value; if (rate < delta) { status = STOP; break; } } pastValues[iteration % past] = value; } // update S and Y final State currentState = states[currentStateIndex]; currentState.s = parameters.copy().sub(prevParameters); currentState.y = gradient.copy().sub(prevGradient); final double ys = Vector.dotProduct(currentState.y, currentState.s); final double yy = Vector.dotProduct(currentState.y, currentState.y); currentState.ys = ys; currentStateIndex = (currentStateIndex + 1) % m; // update Direction direction = gradient.copy(); int availableStates = Math.min(iteration, m); LOG.debug("Available states = " + availableStates); int j = currentStateIndex; for (int i = 0; i < availableStates; i ++) { j = (j + m - 1) % m; final State t = states[j]; t.alpha = Vector.dotProduct(t.s, direction) / t.ys; direction.sub(t.y.copy().scale(t.alpha)); } direction.scale(ys / yy); for (int i = 0; i < availableStates; i ++) { final State t = states[j]; final double beta = Vector.dotProduct(t.y, direction) / t.ys; direction.add(t.s.copy().scale(t.alpha - beta)); j = (j + 1) % m; } direction.neg(); step = 1.0; } final Vector finalParameters = function.getParameters(); final double finalValue = function.getValue(); LOG.debug("Status = " + status + " Final Value = " + finalValue + " Parameters: " + finalParameters + " Iteration = " + iteration); return new OptimizationResult(status, finalParameters, finalValue, iteration); } private static class State { public double alpha; public Vector s; public Vector y; public double ys; } }
pavelvpster/Math
src/main/java/org/interactiverobotics/ml/optimization/LBFGS.java
Java
gpl-3.0
9,413
package cn.bjsxt.oop.staticInitBlock; public class Parent001 /*extends Object*/ { static int aa; static { System.out.println(" 静态初始化Parent001"); aa=200; } }
yangweijun213/Java
J2SE300/28_51OO/src/cn/bjsxt/oop/staticInitBlock/Parent001.java
Java
gpl-3.0
184
using Fallout4Checklist.Entities; namespace Fallout4Checklist.ViewModels { public class WeaponStatsViewModel { public WeaponStatsViewModel(Weapon weapon) { Weapon = weapon; } public Weapon Weapon { get; set; } } }
street1030/Fallout4Checklist
Fallout4Checklist/ViewModels/AreaDetail/WeaponStatsViewModel.cs
C#
gpl-3.0
275
/********************************************************* ********************************************************* ** DO NOT EDIT ** ** ** ** THIS FILE AS BEEN GENERATED AUTOMATICALLY ** ** BY UPA PORTABLE GENERATOR ** ** (c) vpc ** ** ** ********************************************************* ********************************************************/ namespace Net.TheVpc.Upa.Impl.Uql { /** * @author Taha BEN SALAH <taha.bensalah@gmail.com> * @creationdate 11/19/12 7:22 PM */ public interface ExpressionDeclarationList { System.Collections.Generic.IList<Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration> GetExportedDeclarations(); void ExportDeclaration(string name, Net.TheVpc.Upa.Impl.Uql.DecObjectType type, object referrerName, object referrerParentId); System.Collections.Generic.IList<Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration> GetDeclarations(string alias); Net.TheVpc.Upa.Impl.Uql.ExpressionDeclaration GetDeclaration(string name); } }
thevpc/upa
upa-impl-core/src/main/csharp/Sources/Auto/Uql/ExpressionDeclarationList.cs
C#
gpl-3.0
1,258
/* * Copyright (C) 2018 Johan Dykstrom * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package se.dykstrom.jcc.common.ast; import java.util.Objects; /** * Abstract base class for different types of jump statements, such as GOTO or GOSUB. * * @author Johan Dykstrom */ public abstract class AbstractJumpStatement extends AbstractNode implements Statement { private final String jumpLabel; protected AbstractJumpStatement(int line, int column, String jumpLabel) { super(line, column); this.jumpLabel = jumpLabel; } /** * Returns the label to jump to. */ public String getJumpLabel() { return jumpLabel; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AbstractJumpStatement that = (AbstractJumpStatement) o; return Objects.equals(jumpLabel, that.jumpLabel); } @Override public int hashCode() { return Objects.hash(jumpLabel); } }
dykstrom/jcc
src/main/java/se/dykstrom/jcc/common/ast/AbstractJumpStatement.java
Java
gpl-3.0
1,652
class Block { constructor(x, y, width, colour) { this.x = x; this.y = y; this.width = width; this.colour = colour; this.occupied = false; } draw() { fill(this.colour); rect(this.x, this.y, this.width, this.width); } }
DanielGilchrist/p5.js-snake
classes/block.js
JavaScript
gpl-3.0
255
/* * Copyright (C) 2012 MineStar.de * * This file is part of Contao. * * Contao is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * Contao 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 Contao. If not, see <http://www.gnu.org/licenses/>. */ package de.minestar.contao.manager; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.bukkit.entity.Player; import de.minestar.contao.core.Settings; import de.minestar.contao.data.ContaoGroup; import de.minestar.contao.data.User; import de.minestar.core.MinestarCore; import de.minestar.core.units.MinestarPlayer; public class PlayerManager { private Map<String, User> onlineUserMap = new HashMap<String, User>(); private Map<ContaoGroup, TreeSet<User>> groupMap = new HashMap<ContaoGroup, TreeSet<User>>(); public PlayerManager() { for (ContaoGroup cGroup : ContaoGroup.values()) { groupMap.put(cGroup, new TreeSet<User>()); } } public void addUser(User user) { onlineUserMap.put(user.getMinecraftNickname().toLowerCase(), user); groupMap.get(user.getGroup()).add(user); } public void removeUser(String userName) { User user = onlineUserMap.remove(userName.toLowerCase()); groupMap.get(user.getGroup()).remove(user); } public User getUser(Player player) { return getUser(player.getName()); } public User getUser(String userName) { return onlineUserMap.get(userName.toLowerCase()); } public String getGroupAsString(ContaoGroup contaoGroup) { Set<User> groupMember = groupMap.get(contaoGroup); if (groupMember.isEmpty()) return null; StringBuilder sBuilder = new StringBuilder(); // BUILD HEAD sBuilder.append(Settings.getColor(contaoGroup)); sBuilder.append(contaoGroup.getDisplayName()); sBuilder.append('('); sBuilder.append(getGroupSize(contaoGroup)); sBuilder.append(") : "); // ADD USER for (User user : groupMember) { sBuilder.append(user.getMinecraftNickname()); sBuilder.append(", "); } // DELETE THE LAST COMMATA sBuilder.delete(0, sBuilder.length() - 2); return sBuilder.toString(); } public int getGroupSize(ContaoGroup contaoGroup) { return groupMap.get(contaoGroup).size(); } public void changeGroup(User user, ContaoGroup newGroup) { groupMap.get(user.getGroup()).remove(user); groupMap.get(newGroup).add(user); setGroup(user, newGroup); } public void setGroup(User user, ContaoGroup newGroup) { MinestarPlayer mPlayer = MinestarCore.getPlayer(user.getMinecraftNickname()); if (mPlayer != null) { mPlayer.setGroup(newGroup.getMinestarGroup()); } } public boolean canBeFree(User probeUser) { // TODO: Implement requirements return false; } }
Minestar/Contao
src/main/java/de/minestar/contao/manager/PlayerManager.java
Java
gpl-3.0
3,520
package org.grovecity.drizzlesms.jobs.requirements; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import org.grovecity.drizzlesms.service.KeyCachingService; import org.whispersystems.jobqueue.requirements.RequirementListener; import org.whispersystems.jobqueue.requirements.RequirementProvider; public class MasterSecretRequirementProvider implements RequirementProvider { private final BroadcastReceiver newKeyReceiver; private RequirementListener listener; public MasterSecretRequirementProvider(Context context) { this.newKeyReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (listener != null) { listener.onRequirementStatusChanged(); } } }; IntentFilter filter = new IntentFilter(KeyCachingService.NEW_KEY_EVENT); context.registerReceiver(newKeyReceiver, filter, KeyCachingService.KEY_PERMISSION, null); } @Override public void setListener(RequirementListener listener) { this.listener = listener; } }
DrizzleSuite/DrizzleSMS
src/org/grovecity/drizzlesms/jobs/requirements/MasterSecretRequirementProvider.java
Java
gpl-3.0
1,144
/* * Copyright (C) 2017 Josua Frank * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package dfmaster.general; import dfmaster.json.JSONValue; import dfmaster.xml.XMLDocument; import dfmaster.xml.XMLElement; /** * This is the abstract type for all data that can be created or parsed. This * could be as example a {@link JSONValue}, a {@link XMLDocument} or a * {@link XMLElement} * * @author Josua Frank */ public class AData { }
Sharknoon/dfMASTER
dfMASTER/src/main/java/dfmaster/general/AData.java
Java
gpl-3.0
1,113
<?php namespace EasyAjax; /** * EasyAjax\FrontInterface interface * * @package EasyAjax * @author Giuseppe Mazzapica * */ interface FrontInterface { /** * Check the request for valid EasyAjax * * @return bool true if current request is a valid EasyAjax ajax request * @access public */ function is_valid_ajax(); /** * Setup the EasyAjax Instance * * @param object $scope the object scope that will execute action if given * @param string $where can be 'priv', 'nopriv' or 'both'. Limit actions to logged in users or not * @param array $allowed list of allowed actions * @return null * @access public */ function setup( $scope = '', $where = '', $allowed = [ ] ); /** * Check the request and launch EasyAjax\Proxy setup if required * * @return null * @access public */ function register(); }
Giuseppe-Mazzapica/EasyAjax
src/EasyAjax/FrontInterface.php
PHP
gpl-3.0
915
package io.valhala.javamon.pokemon.skeleton; import io.valhala.javamon.pokemon.Pokemon; import io.valhala.javamon.pokemon.type.Type; public abstract class Paras extends Pokemon { public Paras() { super("Paras", 35, 70, 55, 25, 55, true, 46,Type.BUG,Type.GRASS); // TODO Auto-generated constructor stub } }
mirgantrophy/Pokemon
src/io/valhala/javamon/pokemon/skeleton/Paras.java
Java
gpl-3.0
316
define(['backbone', 'underscore'], function (Backbone, _) { return Backbone.Model.extend({ idAttribute: 'username', defaults: { persona: { personaPnombre: '', personaSnombre: '', personaApaterno: '', personaAmaterno: '', dni: '' } }, validate: function (attrs, options) { console.log('persona', attrs.persona); if (_.isUndefined(attrs.persona)) { return { field: 'persona', error: 'Debe definir una persona' }; } if (_.isUndefined(attrs.persona.personaDni) || _.isEmpty(attrs.persona.personaDni.trim()) || attrs.persona.personaDni.trim().length != 8) { return { field: 'persona-personaDni', error: 'El dni es un campo obligatorio y debe tener 8 caracteres.' }; } if (_.isUndefined(attrs.persona.personaPnombre) || _.isEmpty(attrs.persona.personaPnombre.trim())) { return { field: 'persona-personaPnombre', error: 'El primer nombre es un campo obligatorio.' }; } if (_.isUndefined(attrs.persona.personaApaterno) || _.isEmpty(attrs.persona.personaApaterno.trim())) { return { field: 'persona-personaApaterno', error: 'El apellido paterno es un campo obligatorio.' }; } if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) { return { field: 'persona-personaAmaterno', error: 'El apellido materno es un campo obligatorio.' }; } } }); });
jaxkodex/edu-stat
src/main/webapp/resources/js/app/models/docente-model.js
JavaScript
gpl-3.0
1,442
package de.unikiel.inf.comsys.neo4j.inference.sail; /* * #%L * neo4j-sparql-extension * %% * Copyright (C) 2014 Niclas Hoyer * %% * 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 de.unikiel.inf.comsys.neo4j.inference.QueryRewriter; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.parser.ParsedBooleanQuery; import org.openrdf.repository.sail.SailBooleanQuery; import org.openrdf.repository.sail.SailRepositoryConnection; /** * A subclass of {@link SailBooleanQuery} with a public constructor to * pass in a boolean query containing a tuple expression. * * The original constructor of {@link SailBooleanQuery} is protected, thus * it is not possible to create a new boolean query from a parsed query * that is used to create a query from a {@link TupleExpr}. * * @see QueryRewriter */ public class SailBooleanExprQuery extends SailBooleanQuery { public SailBooleanExprQuery(ParsedBooleanQuery booleanQuery, SailRepositoryConnection sailConnection) { super(booleanQuery, sailConnection); } }
niclashoyer/neo4j-sparql-extension
src/main/java/de/unikiel/inf/comsys/neo4j/inference/sail/SailBooleanExprQuery.java
Java
gpl-3.0
1,670
require 'spec_helper' describe SessionsController do render_views context "#create" do it "should redirect to patterns path if user is authenticated" it "should redirect to new_user if user doesn't exist" it "should redirect to new_user if password is incorrect" end end
feministy/appy
spec/controllers/sessions_spec.rb
Ruby
gpl-3.0
290
#include <math.h> #include <stdlib.h> #include "camp_judge.h" #include "game_event.h" #include "monster_ai.h" #include "monster_manager.h" #include "path_algorithm.h" #include "player_manager.h" #include "time_helper.h" #include "partner.h" #include "check_range.h" #include "cached_hit_effect.h" #include "count_skill_damage.h" #include "msgid.h" #include "buff.h" // ▲ 攻击优先级1:攻击范围内,距离伙伴最近的正在攻击主人的所有目标>远一些的正在攻击主人的所有目标>距离伙伴最近的正在攻击伙伴自身的所有目标>远一些的正在攻击伙伴自身的所有目标>主人正在攻击的目标 static unit_struct *choose_target(partner_struct *partner) { unit_struct *ret = NULL; double distance; uint64_t now = time_helper::get_cached_time(); uint64_t t = now - 60 * 1000; struct position *cur_pos = partner->get_pos(); distance = 0xffffffff; for (int i = 0; i < MAX_PARTNER_ATTACK_UNIT; ++i) { if (partner->attack_owner[i].uuid == 0) continue; if (partner->attack_owner[i].time <= t) { partner->attack_owner[i].uuid = 0; continue; } if (!partner->is_unit_in_sight(partner->attack_owner[i].uuid)) continue; unit_struct *target = unit_struct::get_unit_by_uuid(partner->attack_owner[i].uuid); if (!target || !target->is_avaliable() || !target->is_alive()) { partner->attack_owner[i].uuid = 0; continue; } struct position *pos = target->get_pos(); float x = pos->pos_x - cur_pos->pos_x; float z = pos->pos_z - cur_pos->pos_z; if (x * x + z * z <= distance) { distance = x * x + z * z; ret = target; } } if (ret) return ret; for (int i = 0; i < MAX_PARTNER_ATTACK_UNIT; ++i) { if (partner->attack_partner[i].uuid == 0) continue; if (partner->attack_partner[i].time <= t) { partner->attack_partner[i].uuid = 0; continue; } if (!partner->is_unit_in_sight(partner->attack_partner[i].uuid)) continue; unit_struct *target = unit_struct::get_unit_by_uuid(partner->attack_partner[i].uuid); if (!target || !target->is_avaliable() || !target->is_alive()) { partner->attack_partner[i].uuid = 0; continue; } struct position *pos = target->get_pos(); float x = pos->pos_x - cur_pos->pos_x; float z = pos->pos_z - cur_pos->pos_z; if (x * x + z * z <= distance) { distance = x * x + z * z; ret = target; } } if (ret) return ret; for (int i = 0; i < MAX_PARTNER_ATTACK_UNIT; ++i) { if (partner->owner_attack[i].uuid == 0) continue; if (partner->owner_attack[i].time <= t) { partner->owner_attack[i].uuid = 0; continue; } if (!partner->is_unit_in_sight(partner->owner_attack[i].uuid)) continue; unit_struct *target = unit_struct::get_unit_by_uuid(partner->owner_attack[i].uuid); if (!target || !target->is_avaliable() || !target->is_alive()) { partner->owner_attack[i].uuid = 0; continue; } struct position *pos = target->get_pos(); float x = pos->pos_x - cur_pos->pos_x; float z = pos->pos_z - cur_pos->pos_z; if (x * x + z * z <= distance) { distance = x * x + z * z; ret = target; } } if (ret) return ret; return NULL; } int partner_ai_tick_1(partner_struct *partner) { if (partner->data->skill_id != 0 && partner->ai_state == AI_ATTACK_STATE) { partner->do_normal_attack(); partner->data->skill_id = 0; partner->ai_state = AI_PATROL_STATE; return 1; } int skill_index; uint32_t skill_id = partner->choose_skill(&skill_index); if (skill_id == 0) return 1; if (partner->try_friend_skill(skill_id, skill_index)) { return (0); } unit_struct *target = choose_target(partner); if (!target) return 0; return partner->attack_target(skill_id, skill_index, target); // struct position *my_pos = partner->get_pos(); // struct position *his_pos = target->get_pos(); // struct SkillTable *config = get_config_by_id(skill_id, &skill_config); // if (config == NULL) // { // LOG_ERR("%s: partner can not find skill[%u] config", __FUNCTION__, skill_id); // return 1; // } // if (!check_distance_in_range(my_pos, his_pos, config->SkillRange)) // { // //追击 // partner->reset_pos(); // if (get_circle_random_position_v2(partner->scene, my_pos, his_pos, config->SkillRange, &partner->data->move_path.pos[1])) // { // partner->send_patrol_move(); // } // else // { // return (0); // } // partner->data->ontick_time += random() % 1000; // return 1; // } // //主动技能 // if (config->SkillType == 2) // { // struct ActiveSkillTable *act_config = get_config_by_id(config->SkillAffectId, &active_skill_config); // if (!act_config) // { // LOG_ERR("%s: can not find skillaffectid[%lu] config", __FUNCTION__, config->SkillAffectId); // return 1; // } // if (act_config->ActionTime > 0) // { // uint64_t now = time_helper::get_cached_time(); // partner->data->ontick_time = now + act_config->ActionTime;// + 1500; // partner->data->skill_id = skill_id; // partner->data->angle = -(pos_to_angle(his_pos->pos_x - my_pos->pos_x, his_pos->pos_z - my_pos->pos_z)); // // LOG_DEBUG("jacktang: mypos[%.2f][%.2f] hispos[%.2f][%.2f]", my_pos->pos_x, my_pos->pos_z, his_pos->pos_x, his_pos->pos_z); // partner->ai_state = AI_ATTACK_STATE; // partner->m_target = target; // partner->reset_pos(); // partner->cast_skill_to_target(skill_id, target); // return 1; // } // } // partner->reset_pos(); // partner->cast_immediate_skill_to_target(skill_id, target); // //被反弹死了 // if (!partner->data) // return 1; // partner->data->skill_id = 0; // //计算硬直时间 // partner->data->ontick_time += count_skill_delay_time(config); // return 1; } struct partner_ai_interface partner_ai_1_interface = { .on_tick = partner_ai_tick_1, .choose_target = choose_target, };
tsdfsetatata/xserver
Server/game_srv/so_game_srv/partner_ai_1.cpp
C++
gpl-3.0
5,862
package fi.metatavu.edelphi.jsons.queries; import java.util.Locale; import fi.metatavu.edelphi.smvcj.SmvcRuntimeException; import fi.metatavu.edelphi.smvcj.controllers.JSONRequestContext; import fi.metatavu.edelphi.DelfoiActionName; import fi.metatavu.edelphi.EdelfoiStatusCode; import fi.metatavu.edelphi.dao.querydata.QueryReplyDAO; import fi.metatavu.edelphi.dao.querylayout.QueryPageDAO; import fi.metatavu.edelphi.dao.users.UserDAO; import fi.metatavu.edelphi.domainmodel.actions.DelfoiActionScope; import fi.metatavu.edelphi.domainmodel.querydata.QueryReply; import fi.metatavu.edelphi.domainmodel.querylayout.QueryPage; import fi.metatavu.edelphi.domainmodel.resources.Query; import fi.metatavu.edelphi.domainmodel.resources.QueryState; import fi.metatavu.edelphi.domainmodel.users.User; import fi.metatavu.edelphi.i18n.Messages; import fi.metatavu.edelphi.jsons.JSONController; import fi.metatavu.edelphi.query.QueryPageHandler; import fi.metatavu.edelphi.query.QueryPageHandlerFactory; import fi.metatavu.edelphi.utils.ActionUtils; import fi.metatavu.edelphi.utils.QueryDataUtils; public class SaveQueryAnswersJSONRequestController extends JSONController { public SaveQueryAnswersJSONRequestController() { super(); setAccessAction(DelfoiActionName.ACCESS_PANEL, DelfoiActionScope.PANEL); } @Override public void process(JSONRequestContext jsonRequestContext) { UserDAO userDAO = new UserDAO(); QueryPageDAO queryPageDAO = new QueryPageDAO(); QueryReplyDAO queryReplyDAO = new QueryReplyDAO(); Long queryPageId = jsonRequestContext.getLong("queryPageId"); QueryPage queryPage = queryPageDAO.findById(queryPageId); Query query = queryPage.getQuerySection().getQuery(); Messages messages = Messages.getInstance(); Locale locale = jsonRequestContext.getRequest().getLocale(); if (query.getState() == QueryState.CLOSED) throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_CLOSED, messages.getText(locale, "exception.1027.cannotSaveReplyQueryClosed")); if (query.getState() == QueryState.EDIT) { if (!ActionUtils.hasPanelAccess(jsonRequestContext, DelfoiActionName.MANAGE_DELFOI_MATERIALS.toString())) throw new SmvcRuntimeException(EdelfoiStatusCode.CANNOT_SAVE_REPLY_QUERY_IN_EDIT_STATE, messages.getText(locale, "exception.1028.cannotSaveReplyQueryInEditState")); } else { User loggedUser = null; if (jsonRequestContext.isLoggedIn()) loggedUser = userDAO.findById(jsonRequestContext.getLoggedUserId()); QueryReply queryReply = QueryDataUtils.findQueryReply(jsonRequestContext, loggedUser, query); if (queryReply == null) { throw new SmvcRuntimeException(EdelfoiStatusCode.UNKNOWN_REPLICANT, messages.getText(locale, "exception.1026.unknownReplicant")); } queryReplyDAO.updateLastModified(queryReply, loggedUser); QueryDataUtils.storeQueryReplyId(jsonRequestContext.getRequest().getSession(), queryReply); QueryPageHandler queryPageHandler = QueryPageHandlerFactory.getInstance().buildPageHandler(queryPage.getPageType()); queryPageHandler.saveAnswers(jsonRequestContext, queryPage, queryReply); } } }
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/jsons/queries/SaveQueryAnswersJSONRequestController.java
Java
gpl-3.0
3,237
package org.craftercms.studio.api.dto; public class UserTest { public void testGetUserId() throws Exception { } public void testSetUserId() throws Exception { } public void testGetPassword() throws Exception { } public void testSetPassword() throws Exception { } }
craftercms/studio3
api/src/test/java/org/craftercms/studio/api/dto/UserTest.java
Java
gpl-3.0
305
/*********************************************************************** 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.Genetic_Rule_Learning.RMini; import java.util.StringTokenizer; import org.core.Fichero; import java.util.StringTokenizer; /** * <p>Title: Main Class of the Program</p> * * <p>Description: It reads the configuration file (data-set files and parameters) and launch the algorithm</p> * * <p>Company: KEEL</p> * * @author Jesús Jiménez * @version 1.0 */ public class Main { private parseParameters parameters; /** Default Constructor */ public Main() { } /** * It launches the algorithm * @param confFile String it is the filename of the configuration file. */ private void execute(String confFile) { parameters = new parseParameters(); parameters.parseConfigurationFile(confFile); RMini method = new RMini(parameters); method.execute(); } /** * Main Program * @param args It contains the name of the configuration file<br/> * Format:<br/> * <em>algorith = &lt;algorithm name></em><br/> * <em>inputData = "&lt;training file&gt;" "&lt;validation file&gt;" "&lt;test file&gt;"</em> ...<br/> * <em>outputData = "&lt;training file&gt;" "&lt;test file&gt;"</em> ...<br/> * <br/> * <em>seed = value</em> (if used)<br/> * <em>&lt;Parameter1&gt; = &lt;value1&gt;</em><br/> * <em>&lt;Parameter2&gt; = &lt;value2&gt;</em> ... <br/> */ public static void main(String args[]) { Main program = new Main(); System.out.println("Executing Algorithm."); program.execute(args[0]); } }
SCI2SUGR/KEEL
src/keel/Algorithms/Genetic_Rule_Learning/RMini/Main.java
Java
gpl-3.0
2,637
import { Component } from '@angular/core' @Component({ selector: 'gallery', templateUrl: 'app/home/gallery.component.html' }) export class GalleryComponent { }
PoojaM0267/BTMVDemo
BTMV_ng2/app/home/gallery.component.ts
TypeScript
gpl-3.0
172
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::globalPoints Description Calculates points shared by more than two processor patches or cyclic patches. Is used in globalMeshData. (this info is needed for point-edge communication where you do all but these shared points with patch to patch communication but need to do a reduce on these shared points) Works purely topological and using local communication only. Needs: - domain to be one single domain (i.e. all faces can be reached through face-cell walk). - patch face ordering to be ok - f[0] ordering on patch faces to be ok. Works by constructing equivalence lists for all the points on processor patches. These list are procPointList and give processor and meshPoint label on that processor. E.g. @verbatim ((7 93)(4 731)(3 114)) @endverbatim means point 93 on proc7 is connected to point 731 on proc4 and 114 on proc3. It then gets the lowest numbered processor (the 'master') to request a sharedPoint label from processor0 and it redistributes this label back to the other processors in the equivalence list. Algorithm: - get meshPoints of all my points on processor patches and initialize equivalence lists to this. loop - send to all neighbours in relative form: - patchFace - index in face - receive and convert into meshPoints. Add to to my equivalence lists. - mark meshPoints for which information changed. - send data for these meshPoints again endloop until nothing changes At this point one will have complete point-point connectivity for all points on processor patches. Now - remove point equivalences of size 2. These are just normal points shared between two neighbouring procPatches. - collect on each processor points for which it is the master - request number of sharedPointLabels from the Pstream::master. This information gets redistributed to all processors in a similar way as that in which the equivalence lists were collected: - initialize the indices of shared points I am the master for loop - send my known sharedPoints + meshPoints to all neighbours - receive from all neighbour. Find which meshPoint on my processor the sharedpoint is connected to - mark indices for which information has changed endloop until nothing changes. SourceFiles globalPoints.C \*---------------------------------------------------------------------------*/ #ifndef globalPoints_H #define globalPoints_H #include <OpenFOAM/DynamicList.H> #include <OpenFOAM/Map.H> #include <OpenFOAM/labelList.H> #include <OpenFOAM/FixedList.H> #include <OpenFOAM/primitivePatch.H> #include <OpenFOAM/className.H> #include <OpenFOAM/edgeList.H> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward declaration of classes class polyMesh; class polyBoundaryMesh; class cyclicPolyPatch; /*---------------------------------------------------------------------------*\ Class globalPoints Declaration \*---------------------------------------------------------------------------*/ class globalPoints { // Private classes //- Define procPointList as holding a list of meshPoint/processor labels typedef FixedList<label, 2> procPoint; typedef List<procPoint> procPointList; // Private data //- Mesh reference const polyMesh& mesh_; //- Sum of points on processor patches (unfiltered, point on 2 patches // counts as 2) const label nPatchPoints_; //- All points on boundaries and their corresponding connected points // on other processors. DynamicList<procPointList> procPoints_; //- Map from mesh point to index in procPoints Map<label> meshToProcPoint_; //- Shared points used by this processor (= global point number) labelList sharedPointAddr_; //- My meshpoints corresponding to the shared points labelList sharedPointLabels_; //- Total number of shared points. label nGlobalPoints_; // Private Member Functions //- Count all points on processorPatches. Is all points for which // information is collected. static label countPatchPoints(const polyBoundaryMesh&); //- Add information about patchPointI in relative indices to send // buffers (patchFaces, indexInFace etc.) static void addToSend ( const primitivePatch&, const label patchPointI, const procPointList&, DynamicList<label>& patchFaces, DynamicList<label>& indexInFace, DynamicList<procPointList>& allInfo ); //- Merge info from neighbour into my data static bool mergeInfo ( const procPointList& nbrInfo, procPointList& myInfo ); //- Store (and merge) info for meshPointI bool storeInfo(const procPointList& nbrInfo, const label meshPointI); //- Initialize procPoints_ to my patch points. allPoints = true: // seed with all patch points, = false: only boundaryPoints(). void initOwnPoints(const bool allPoints, labelHashSet& changedPoints); //- Send subset of procPoints to neighbours void sendPatchPoints(const labelHashSet& changedPoints) const; //- Receive neighbour points and merge into my procPoints. void receivePatchPoints(labelHashSet& changedPoints); //- Remove entries of size 2 where meshPoint is in provided Map. // Used to remove normal face-face connected points. void remove(const Map<label>&); //- Get indices of point for which I am master (lowest numbered proc) labelList getMasterPoints() const; //- Send subset of shared points to neighbours void sendSharedPoints(const labelList& changedIndices) const; //- Receive shared points and update subset. void receiveSharedPoints(labelList& changedIndices); //- Should move into cyclicPolyPatch but some ordering problem // keeps on giving problems. static edgeList coupledPoints(const cyclicPolyPatch&); //- Disallow default bitwise copy construct globalPoints(const globalPoints&); //- Disallow default bitwise assignment void operator=(const globalPoints&); public: //- Declare name of the class and its debug switch ClassName("globalPoints"); // Constructors //- Construct from mesh globalPoints(const polyMesh& mesh); // Member Functions // Access label nPatchPoints() const { return nPatchPoints_; } const Map<label>& meshToProcPoint() const { return meshToProcPoint_; } //- shared points used by this processor (= global point number) const labelList& sharedPointAddr() const { return sharedPointAddr_; } //- my meshpoints corresponding to the shared points const labelList& sharedPointLabels() const { return sharedPointLabels_; } label nGlobalPoints() const { return nGlobalPoints_; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************ vim: set sw=4 sts=4 et: ************************ //
themiwi/freefoam-debian
src/OpenFOAM/meshes/polyMesh/globalMeshData/globalPoints.H
C++
gpl-3.0
8,920
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; class ParityBackground extends Component { static propTypes = { style: PropTypes.object.isRequired, children: PropTypes.node, className: PropTypes.string, onClick: PropTypes.func }; render () { const { children, className, style, onClick } = this.props; return ( <div className={ className } style={ style } onTouchTap={ onClick }> { children } </div> ); } } function mapStateToProps (_, initProps) { const { gradient, seed, muiTheme } = initProps; let _seed = seed; let _props = { style: muiTheme.parity.getBackgroundStyle(gradient, seed) }; return (state, props) => { const { backgroundSeed } = state.settings; const { seed } = props; const newSeed = seed || backgroundSeed; if (newSeed === _seed) { return _props; } _seed = newSeed; _props = { style: muiTheme.parity.getBackgroundStyle(gradient, newSeed) }; return _props; }; } export default connect( mapStateToProps )(ParityBackground);
pdaian/parity
js/src/ui/ParityBackground/parityBackground.js
JavaScript
gpl-3.0
1,825
/** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ (function ($, require) { var exports = require('piwik/UI'); /** * Creates a new notifications. * * Example: * var UI = require('piwik/UI'); * var notification = new UI.Notification(); * notification.show('My Notification Message', {title: 'Low space', context: 'warning'}); */ var Notification = function () { this.$node = null; }; /** * Makes the notification visible. * * @param {string} message The actual message that will be displayed. Must be set. * @param {Object} [options] * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {bool} [options.animate=true] If enabled, the notification will be faded in. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} * @param {string} [options.placeat] By default, the notification will be displayed in the "stats bar". * You can specify any other CSS selector to place the notifications * wherever you want. */ Notification.prototype.show = function (message, options) { checkMessage(message); options = checkOptions(options); var template = generateNotificationHtmlMarkup(options, message); this.$node = placeNotification(template, options); }; /** * Removes a previously shown notification having the given notification id. * * * @param {string} notificationId The id of a notification that was previously registered. */ Notification.prototype.remove = function (notificationId) { $('[piwik-notification][notification-id=' + notificationId + ']').remove(); }; Notification.prototype.scrollToNotification = function () { if (this.$node) { piwikHelper.lazyScrollTo(this.$node, 250); } }; /** * Shows a notification at a certain point with a quick upwards animation. * * TODO: if the materializecss version matomo uses is updated, should use their toasts. * * @type {Notification} * @param {string} message The actual message that will be displayed. Must be set. * @param {Object} options * @param {string} options.placeat Where to place the notification. Required. * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} */ Notification.prototype.toast = function (message, options) { checkMessage(message); options = checkOptions(options); var $placeat = $(options.placeat); if (!$placeat.length) { throw new Error("A valid selector is required for the placeat option when using Notification.toast()."); } var $template = $(generateNotificationHtmlMarkup(options, message)).hide(); $('body').append($template); compileNotification($template); $template.css({ position: 'absolute', left: $placeat.offset().left, top: $placeat.offset().top }); setTimeout(function () { $template.animate( { top: $placeat.offset().top - $template.height() }, { duration: 300, start: function () { $template.show(); } } ); }); }; exports.Notification = Notification; function generateNotificationHtmlMarkup(options, message) { var attributeMapping = { id: 'notification-id', title: 'notification-title', context: 'context', type: 'type', noclear: 'noclear', class: 'class', toastLength: 'toast-length' }, html = '<div piwik-notification'; for (var key in attributeMapping) { if (attributeMapping.hasOwnProperty(key) && options[key] ) { html += ' ' + attributeMapping[key] + '="' + options[key].toString().replace(/"/g, "&quot;") + '"'; } } html += '>' + message + '</div>'; return html; } function compileNotification($node) { angular.element(document).injector().invoke(function ($compile, $rootScope) { $compile($node)($rootScope.$new(true)); }); } function placeNotification(template, options) { var $notificationNode = $(template); // compile the template in angular compileNotification($notificationNode); if (options.style) { $notificationNode.css(options.style); } var notificationPosition = '#notificationContainer'; var method = 'append'; if (options.placeat) { notificationPosition = options.placeat; } else { // If a modal is open, we want to make sure the error message is visible and therefore show it within the opened modal var modalSelector = '.modal.open .modal-content'; var modalOpen = $(modalSelector); if (modalOpen.length) { notificationPosition = modalSelector; method = 'prepend'; } } $notificationNode = $notificationNode.hide(); $(notificationPosition)[method]($notificationNode); if (false === options.animate) { $notificationNode.show(); } else { $notificationNode.fadeIn(1000); } return $notificationNode; } function checkMessage(message) { if (!message) { throw new Error('No message given, cannot display notification'); } } function checkOptions(options) { if (options && !$.isPlainObject(options)) { throw new Error('Options has the wrong format, cannot display notification'); } else if (!options) { options = {}; } return options; } })(jQuery, require);
piwik/piwik
plugins/CoreHome/javascripts/notification.js
JavaScript
gpl-3.0
7,980
PREP(initCBASettings); PREP(postInit);
Jamesadamar/OPT
[J]OPT.Altis/uav/XEH_PREP.hpp
C++
gpl-3.0
39
/* * Jinx is Copyright 2010-2020 by Jeremy Brooks and Contributors * * Jinx 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. * * Jinx 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 Jinx. If not, see <http://www.gnu.org/licenses/>. */ package net.jeremybrooks.jinx.api; import net.jeremybrooks.jinx.Jinx; import net.jeremybrooks.jinx.JinxException; import net.jeremybrooks.jinx.JinxUtils; import net.jeremybrooks.jinx.response.Response; import net.jeremybrooks.jinx.response.photos.notes.Note; import java.util.Map; import java.util.TreeMap; /** * Provides access to the flickr.photos.notes API methods. * * @author Jeremy Brooks * @see <a href="https://www.flickr.com/services/api/">Flickr API documentation</a> for more details. */ public class PhotosNotesApi { private Jinx jinx; public PhotosNotesApi(Jinx jinx) { this.jinx = jinx; } /** * Add a note to a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages. * <br> * This method requires authentication with 'write' permission. * * @param photoId (Required) The id of the photo to add a note to. * @param noteX (Required) The left coordinate of the note. * @param noteY (Required) The top coordinate of the note. * @param noteWidth (Required) The width of the note. * @param noteHeight (Required) The height of the note. * @param noteText (Required) The text of the note. * @return object with the ID for the newly created note. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.add.html">flickr.photos.notes.add</a> */ public Note add(String photoId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException { JinxUtils.validateParams(photoId, noteText); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.add"); params.put("photo_id", photoId); params.put("note_x", Integer.toString(noteX)); params.put("note_y", Integer.toString(noteY)); params.put("note_w", Integer.toString(noteWidth)); params.put("note_h", Integer.toString(noteHeight)); params.put("note_text", noteText); return jinx.flickrPost(params, Note.class); } /** * Edit a note on a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages. * <br> * This method requires authentication with 'write' permission. * * @param noteId (Required) The id of the note to edit. * @param noteX (Required) The left coordinate of the note. * @param noteY (Required) The top coordinate of the note. * @param noteWidth (Required) The width of the note. * @param noteHeight (Required) The height of the note. * @param noteText (Required) The text of the note. * @return object with the status of the requested operation. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.edit.html">flickr.photos.notes.edit</a> */ public Response edit(String noteId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException { JinxUtils.validateParams(noteId, noteText); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.edit"); params.put("note_id", noteId); params.put("note_x", Integer.toString(noteX)); params.put("note_y", Integer.toString(noteY)); params.put("note_w", Integer.toString(noteWidth)); params.put("note_h", Integer.toString(noteHeight)); params.put("note_text", noteText); return jinx.flickrPost(params, Response.class); } /** * Delete a note from a photo. * <br> * This method requires authentication with 'write' permission. * * @param noteId (Required) The id of the note to delete. * @return object with the status of the requested operation. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.delete.html">flickr.photos.notes.delete</a> */ public Response delete(String noteId) throws JinxException { JinxUtils.validateParams(noteId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.delete"); params.put("note_id", noteId); return jinx.flickrPost(params, Response.class); } }
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/PhotosNotesApi.java
Java
gpl-3.0
5,049
<?php /** * PHPUnit * * Copyright (c) 2002-2009, Sebastian Bergmann <sb@sebastian-bergmann.de>. * 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 Sebastian Bergmann nor the names of his * 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. * * @category Testing * @package PHPUnit * @author Jan Borsodi <jb@ez.no> * @author Sebastian Bergmann <sb@sebastian-bergmann.de> * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version SVN: $Id: Parameters.php 4403 2008-12-31 09:26:51Z sb $ * @link http://www.phpunit.de/ * @since File available since Release 3.0.0 */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Util/Filter.php'; require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php'; require_once 'PHPUnit/Framework/MockObject/Invocation.php'; PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); /** * Invocation matcher which looks for specific parameters in the invocations. * * Checks the parameters of all incoming invocations, the parameter list is * checked against the defined constraints in $parameters. If the constraint * is met it will return true in matches(). * * @category Testing * @package PHPUnit * @author Jan Borsodi <jb@ez.no> * @author Sebastian Bergmann <sb@sebastian-bergmann.de> * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version Release: 3.4.0beta1 * @link http://www.phpunit.de/ * @since Class available since Release 3.0.0 */ class PHPUnit_Framework_MockObject_Matcher_Parameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation { protected $parameters = array(); protected $invocation; public function __construct($parameters) { foreach($parameters as $parameter) { if (!($parameter instanceof PHPUnit_Framework_Constraint)) { $parameter = new PHPUnit_Framework_Constraint_IsEqual($parameter); } $this->parameters[] = $parameter; } } public function toString() { $text = 'with parameter'; foreach($this->parameters as $index => $parameter) { if ($index > 0) { $text .= ' and'; } $text .= ' ' . $index . ' ' . $parameter->toString(); } return $text; } public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) { $this->invocation = $invocation; $this->verify(); return count($invocation->parameters) < count($this->parameters); } public function verify() { if ($this->invocation === NULL) { throw new PHPUnit_Framework_ExpectationFailedException( 'Mocked method does not exist.' ); } if (count($this->invocation->parameters) < count($this->parameters)) { throw new PHPUnit_Framework_ExpectationFailedException( sprintf( 'Parameter count for invocation %s is too low.', $this->invocation->toString() ) ); } foreach ($this->parameters as $i => $parameter) { if (!$parameter->evaluate($this->invocation->parameters[$i])) { $parameter->fail( $this->invocation->parameters[$i], sprintf( 'Parameter %s for invocation %s does not match expected value.', $i, $this->invocation->toString() ) ); } } } } ?>
manusis/dblite
test/lib/phpunit/PHPUnit/Framework/MockObject/Matcher/Parameters.php
PHP
gpl-3.0
5,341
<?php /** * * @version 1.0.9 June 24, 2016 * @package Get Bible API * @author Llewellyn van der Merwe <llewellyn@vdm.io> * @copyright Copyright (C) 2013 Vast Development Method <http://www.vdm.io> * @license GNU General Public License <http://www.gnu.org/copyleft/gpl.html> * **/ defined( '_JEXEC' ) or die( 'Restricted access' ); //Import filesystem libraries. Perhaps not necessary, but does not hurt jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); jimport('joomla.application.component.helper'); class GetbibleModelImport extends JModelLegacy { protected $user; protected $dateSql; protected $book_counter; protected $app_params; protected $local = false; protected $curlError = false; public $availableVersions; public $availableVersionsList; public $installedVersions; public function __construct() { parent::__construct(); // get params $this->app_params = JComponentHelper::getParams('com_getbible'); // get user data $this->user = JFactory::getUser(); // get todays date $this->dateSql = JFactory::getDate()->toSql(); // we need a loger execution time if (ini_set('max_execution_time', 300) === false) { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_INCREASE_EXECUTION_TIME'), 'error'); return false; } // load available verstions $this->getVersionAvailable(); // get installed versions $this->getInstalledVersions(); } protected function populateState() { parent::populateState(); // Get the input data $jinput = JFactory::getApplication()->input; $source = $jinput->post->get('translation', NULL, 'STRING'); $translation = (string) preg_replace('/[^A-Z0-9_\)\(-]/i', '', $source); // Set to state $this->setState('translation', $translation); } public function getVersions() { // reload version list for app $available = $this->availableVersionsList; $alreadyin = $this->installedVersions; if($available){ if ($alreadyin){ $result = array_diff($available, $alreadyin); } else { $result = $available; } if($result){ $setVersions = array(); $setVersions[] = JHtml::_('select.option', '', JText::_('COM_GETBIBLE_PLEASE_SELECT')); foreach ($this->availableVersions as $key => $values){ if(in_array($key, $result)){ $name = $values["versionName"]. ' ('.$values["versionLang"].')'; $setVersions[] = JHtml::_('select.option', $values["fileName"], $name); } } return $setVersions; } JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_ALL_BIBLES_ALREADY_INSTALLED'), 'success'); return false; } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } public function rutime($ru, $rus, $index) { return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000)) - ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000)); } public function getImport() { if ($this->getState('translation')){ // set version $versionFileName = $this->getState('translation'); $versionfix = str_replace("___", "'", $versionFileName); list($versionLang,$versionName,$versionCode,$bidi) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $version = $versionCode; //check input if ($this->checkTranslation($version) && $this->checkFileName($versionFileName)){ // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); if($installOptions){ // get the file $filename = 'https://getbible.net/scriptureinstall/'.$versionFileName.'.txt'; } else { // get localInstallFolder set in params $filename = JPATH_ROOT.'/'.rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/').'/'.$versionFileName.'.txt'; } // load the file $file = new SplFileObject($filename); // start up database $db = JFactory::getDbo(); // load all books $books = $this->setBooks($version); $i = 1; // build query to save if (is_object($file)) { while (! $file->eof()) { $verse = explode("||",$file->fgets()); $found = false; // rename books foreach ($books as $book){ $verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0])); if ($book['nr'] <= 39) { if (strpos($verse[0],'O') !== false) { $search_value = sprintf("%02s", $book['nr']).'O'; } else { $search_value = sprintf("%02s", $book['nr']); } } else { if (strpos($verse[0],'N') !== false) { $search_value = $book['nr'].'N'; } else { $search_value = $book['nr']; } } if ($verse[0] == $search_value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $book_name = $book['name']; $found = true; break; } } if(!$found){ foreach ($books as $book){ $verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0])); foreach($book['book_names'] as $key => $value){ if ($value){ $value = strtoupper(preg_replace('/\s+/', '', $value)); if ($verse[0] == $value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $book_name = $book['name']; $found = true; break; } } } } } if(!$found){ // load all books again as KJV $books = $this->setBooks($version, true); foreach ($books as $book){ foreach($book['book_names'] as $key => $value){ if ($value){ $value = strtoupper(preg_replace('/\s+/', '', $value)); if ($verse[0] == $value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $found = true; break; } } } } } // set data if(isset($verse[3]) && $verse[3]){ $Bible[$verse[0]][$verse[1]][$verse[2]] = $verse[3]; // Create a new query object for this verse. $versObject = new stdClass(); $versObject->version = $version; $versObject->book_nr = $book_nr; $versObject->chapter_nr = $verse[1]; $versObject->verse_nr = $verse[2]; $versObject->verse = $verse[3]; $versObject->access = 1; $versObject->published = 1; $versObject->created_by = $this->user->id; $versObject->created_on = $this->dateSql; // Insert the object into the verses table. $result = JFactory::getDbo()->insertObject('#__getbible_verses', $versObject); } } } // clear from memory unset($file); // save complete books & chapters foreach ($books as $book) { if (isset($book["nr"]) && isset($Bible[$book["nr"]])) { $this->saveChapter($version, $book["nr"], $Bible[$book["nr"]]); $this->saveBooks($version, $book["nr"], $Bible[$book["nr"]]); } } // clear from memory unset($books); // Set version details if(is_array($this->book_counter)){ if(in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){ $testament = 'OT&NT'; } elseif(in_array(1,$this->book_counter) && !in_array(66,$this->book_counter)){ $testament = 'OT'; } elseif(!in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){ $testament = 'NT'; } else { $testament = 'NOT'; } $book_counter = json_encode($this->book_counter); } else { $book_counter = 'error'; $testament = 'error'; } // Create a new query object for this Version. $versionObject = new stdClass(); $versionObject->name = $versionName; $versionObject->bidi = $bidi; $versionObject->language = $versionLang; $versionObject->books_nr = $book_counter; $versionObject->testament = $testament; $versionObject->version = $version; $versionObject->link = $filename; $versionObject->installed = 1; $versionObject->access = 1; $versionObject->published = 1; $versionObject->created_by = $this->user->id; $versionObject->created_on = $this->dateSql; // Insert the object into the versions table. $result = JFactory::getDbo()->insertObject('#__getbible_versions', $versionObject); JFactory::getApplication()->enqueueMessage(JText::sprintf('COM_GETBIBLE_MESSAGE_BIBLE_INSTALLED_SUCCESSFULLY', $versionName)); // reset the local version list. $this->_cpanel(); // if first Bible is installed change the application to load localy with that Bible as the default $this->setLocal(); // clean cache to insure the dropdown removes this installed version. $this->cleanCache('_system'); return true; } else { return false; } } else { return false; } } protected function checkTranslation($version) { // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); $available = $this->availableVersionsList; $alreadyin = $this->installedVersions; if ($available){ if(in_array($version, $available)){ if ($alreadyin){ if(in_array($version, $alreadyin)){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_ALREADY_INSTALLED'), 'error'); return false; }return true; }return true; } JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_NOT_FOUND_ON_GETBIBLE'), 'error'); return false; } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } protected function checkFileName($versionFileName) { $available = $this->availableVersions; $found = false; if ($available){ foreach($available as $file){ if (in_array($versionFileName, $file)){ $found = true; break; } else { $found = false; } } if(!$found){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_NOT_FOUND_ON_GETBIBLE'), 'error'); return false; } else { return $found; } } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } protected function saveChapter($version, $book_nr, $chapters) { if ( $chapters ){ // start up database $db = JFactory::getDbo(); // Create a new query object for this verstion $query = $db->getQuery(true); // set chapter number $chapter_nr = 1; $values = ''; // set the data foreach ($chapters as $chapter) { $setup = NULL; $text = NULL; $ver = 1; foreach($chapter as $verse) { $text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse); $ver++; } $setup = array('chapter'=>$text); $scripture = json_encode($setup); // Insert values. $values[] = $db->quote($version).', '.(int)$book_nr.', '.(int)$chapter_nr.', '.$db->quote($scripture).', 1, 1, '.$this->user->id.', '.$db->quote($this->dateSql); $chapter_nr++; } // clear from memory unset($chapters); // Insert columns. $columns = array( 'version', 'book_nr', 'chapter_nr', 'chapter', 'access', 'published', 'created_by', 'created_on' ); // Prepare the insert query. $query->insert($db->quoteName('#__getbible_chapters')); $query->columns($db->quoteName($columns)); $query->values($values); // Set the query using our newly populated query object and execute it. $db->setQuery($query); $db->query(); } return true; } protected function saveBooks($version, $book_nr, $book) { if (is_array($book) && count($book)){ //set book number $this->book_counter[] = $book_nr; // start up database $db = JFactory::getDbo(); // Create a new query object for this verstion $query = $db->getQuery(true); // set chapter number $chapter_nr = 1; $values = ''; // set the data foreach ($book as $chapter) { $setup = NULL; $text = NULL; $ver = 1; foreach($chapter as $verse) { $text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse); $ver++; } $setupChapter[$chapter_nr] = array('chapter_nr'=>$chapter_nr,'chapter'=>$text); $chapter_nr++; } // clear from memory unset($book); $setup = array('book'=>$setupChapter); $saveBook = json_encode($setup); // Create a new query object for this verstion $query = $db->getQuery(true); // Insert columns. $columns = array('version', 'book_nr', 'book', 'access', 'published', 'created_by', 'created_on'); // Insert values. $values = array($db->quote($version), (int) $book_nr, $db->quote($saveBook), 1, 1, $this->user->id, $db->quote($this->dateSql)); // Prepare the insert query. $query ->insert($db->quoteName('#__getbible_books')) ->columns($db->quoteName($columns)) ->values(implode(',', $values)); //echo nl2br(str_replace('#__','api_',$query)); die; // Set the query using our newly populated query object and execute it. $db->setQuery($query); $db->query(); } return true; } protected function getInstalledVersions() { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName('version')); $query->from($db->quoteName('#__getbible_versions')); $query->order('version ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadColumn(); if ($results){ $this->installedVersions = $results; return true; } return false; } protected function setLocalXML() { jimport( 'joomla.filesystem.folder' ); // get localInstallFolder set in params $path = rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/'); // creat folder JFolder::create(JPATH_ROOT.'/'.$path.'/xml'); // set the file name $filepath = JPATH_ROOT.'/'.$path.'/xml/version.xml.php'; // set folder path $folderpath = JPATH_ROOT.'/'.$path; $fh = fopen($filepath, "w"); if (!is_resource($fh)) { return false; } $data = $this->setPHPforXML($folderpath); if(!fwrite($fh, $data)){ // close file. fclose($fh); return false; } // close file. fclose($fh); // return local file path return JURI::root().$path.'/xml/version.xml.php/versions.xml'; } protected function setPHPforXML($path) { return "<?php foreach (glob(\"".$path."/*.txt\") as \$filename) { \$available[] = str_replace('.txt', '', basename(\$filename)); // do something with \$filename } \$xml = new SimpleXMLElement('<versions/>'); foreach (\$available as \$version) { \$xml->addChild('name', \$version); } header('Content-type: text/xml'); header('Pragma: public'); header('Cache-control: private'); header('Expires: -1'); print(\$xml->asXML()); ?>"; } protected function getVersionAvailable() { // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); if(!$installOptions){ $xml = $this->setLocalXML(); $this->local = true; } else { // check the available versions on getBible $xml = 'https://getbible.net/scriptureinstall/xml/version.xml.php/versions.xml'; } if(@fopen($xml, 'r')){ if (($response_xml_data = file_get_contents($xml))===false){ $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { libxml_use_internal_errors(true); $data = simplexml_load_string($response_xml_data); if (!$data) { $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { foreach ($data->name as $version){ $versionfix = str_replace("___", "'", $version); list($versionLang,$versionName,$versionCode) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $versions[$versionCode]['fileName'] = $version; $versions[$versionCode]['versionName'] = $versionName; $versions[$versionCode]['versionLang'] = $versionLang; $versions[$versionCode]['versionCode'] = $versionCode; $version_list[] = $versionCode; } $this->availableVersions = $versions; $this->availableVersionsList = $version_list; return true; } } } elseif(function_exists('curl_init')){ $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL,$xml); $response_xml_data = curl_exec($ch); if(curl_error($ch)){ $this->curlError = curl_error($ch); } curl_close($ch); $data = simplexml_load_string($response_xml_data); // echo'<pre>';var_dump($data);exit; if (!$data) { $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { foreach ($data->name as $version){ $versionfix = str_replace("___", "'", $version); list($versionLang,$versionName,$versionCode) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $versions[$versionCode]['fileName'] = $version; $versions[$versionCode]['versionName'] = $versionName; $versions[$versionCode]['versionLang'] = $versionLang; $versions[$versionCode]['versionCode'] = $versionCode; $version_list[] = $versionCode; } $this->availableVersions = $versions; $this->availableVersionsList = $version_list; return true; } } else { $this->availableVersions = false; $this->availableVersionsList = false; return false; } } protected function setBooks($version = NULL, $retry = false, $default = 'kjv') { // Get a db connection. $db = JFactory::getDbo(); if ($version){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($version)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); if($results){ foreach ($results as $book){ $books[$book['book_nr']]['nr'] = $book['book_nr']; $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); // if retry do't change name $books[$book['book_nr']]['name'] = $book['book_name']; } } } if(!isset($books)){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($default)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); foreach ($results as $book){ $books[$book['book_nr']]['nr'] = $book['book_nr']; $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); $books[$book['book_nr']]['name'] = $book['book_name']; } } if($retry){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($default)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); foreach ($results as $book){ if(!$books[$book['book_nr']]['nr']){ $books[$book['book_nr']]['nr'] = $book['book_nr']; } $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); if(!$books[$book['book_nr']]['name']){ $books[$book['book_nr']]['name'] = $book['book_name']; } } } return $books; } protected function _cpanel() { // Base this model on the backend version. require_once JPATH_ADMINISTRATOR.'/components/com_getbible/models/cpanel.php'; $cpanel_model = new GetbibleModelCpanel; return $cpanel_model->setCpanel(); } protected function setLocal() { $this->getInstalledVersions(); $versions = $this->installedVersions; $number = count($versions); // only change to local API on install of first Bible if ($number == 1){ // get default Book Name $defaultStartBook = $this->app_params->get('defaultStartBook'); // make sure it is set to the correct name avaliable in this new default version // first get book number $book_nr = $this->getLocalBookNR($defaultStartBook, $versions[0]); // second check if this version has this book and return the book number it has $book_nr = $this->checkVersionBookNR($book_nr, $versions[0]); // third set the book name $defaultStartBook = $this->getLocalDefaultBook($defaultStartBook, $versions[0], $book_nr); // Update Global Settings $params = JComponentHelper::getParams('com_getbible'); $params->set('defaultStartVersion', $versions[0]); $params->set('defaultStartBook', $defaultStartBook); $params->set('jsonQueryOptions', 1); // Get a new database query instance $db = JFactory::getDBO(); $query = $db->getQuery(true); // Build the query $query->update('#__extensions AS a'); $query->set('a.params = ' . $db->quote((string)$params)); $query->where('a.element = "com_getbible"'); // Execute the query // echo nl2br(str_replace('#__','api_',$query)); die; $db->setQuery($query); $db->query(); return true; } return false; } protected function getLocalBookNR($defaultStartBook,$version,$retry = false) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_setbooks AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($version)); $query->where($db->quoteName('a.book_name') . ' = ' . $db->quote($defaultStartBook)); // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $db->loadResult(); } else { // fall back on default if($retry){ return 43; } return $this->getLocalBookNR($defaultStartBook,'kjv',true); } } protected function checkVersionBookNR($book_nr, $defaultVersion) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_books AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $book_nr; } else { // Run the default // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_books AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadColumn(); // set book array $results = array_unique($results); // set book for Old Testament (Psalms) or New Testament (John) if (in_array(43,$results)){ return 43; } elseif(in_array(19,$results)) { return 19; } return false; } } protected function getLocalDefaultBook($defaultStartBook,$defaultVersion,$book_nr,$tryAgain = false) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_name'); $query->from('#__getbible_setbooks AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); if($tryAgain){ $query->where($db->quoteName('a.version') . ' = ' . $db->quote($tryAgain)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); } else { $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); } // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $db->loadResult(); } else { // fall back on default return $this->getLocalDefaultBook($defaultStartBook,$defaultVersion,$book_nr,'kjv'); } } }
getbible/Joomla-3-Component
admin/models/import.php
PHP
gpl-3.0
27,659
package de.jotschi.geo.osm.tags; import org.w3c.dom.Node; public class OsmMember { String type, ref, role; public OsmMember(Node node) { ref = node.getAttributes().getNamedItem("ref").getNodeValue(); role = node.getAttributes().getNamedItem("role").getNodeValue(); type = node.getAttributes().getNamedItem("type").getNodeValue(); } public String getType() { return type; } public String getRef() { return ref; } public String getRole() { return role; } }
Jotschi/libTinyOSM
src/main/java/de/jotschi/geo/osm/tags/OsmMember.java
Java
gpl-3.0
490
/********************* * bio_tune_menu.cpp * *********************/ /**************************************************************************** * Written By Mark Pelletier 2017 - Aleph Objects, Inc. * * Written By Marcio Teixeira 2018 - Aleph Objects, Inc. * * * * 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. * * * * To view a copy of the GNU General Public License, go to the following * * location: <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "../config.h" #if ENABLED(TOUCH_UI_FTDI_EVE) && defined(TOUCH_UI_LULZBOT_BIO) #include "screens.h" using namespace FTDI; using namespace Theme; using namespace ExtUI; void TuneMenu::onRedraw(draw_mode_t what) { #define GRID_ROWS 8 #define GRID_COLS 2 if (what & BACKGROUND) { CommandProcessor cmd; cmd.cmd(CLEAR_COLOR_RGB(bg_color)) .cmd(CLEAR(true,true,true)) .cmd(COLOR_RGB(bg_text_enabled)) .tag(0) .font(font_large) .text( BTN_POS(1,1), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_MENU)); } if (what & FOREGROUND) { CommandProcessor cmd; cmd.colors(normal_btn) .font(font_medium) .enabled( isPrinting()).tag(2).button( BTN_POS(1,2), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_SPEED)) .tag(3).button( BTN_POS(1,3), BTN_SIZE(2,1), GET_TEXT_F(MSG_BED_TEMPERATURE)) .enabled(TERN_(BABYSTEPPING, true)) .tag(4).button( BTN_POS(1,4), BTN_SIZE(2,1), GET_TEXT_F(MSG_NUDGE_NOZZLE)) .enabled(!isPrinting()).tag(5).button( BTN_POS(1,5), BTN_SIZE(2,1), GET_TEXT_F(MSG_MOVE_TO_HOME)) .enabled(!isPrinting()).tag(6).button( BTN_POS(1,6), BTN_SIZE(2,1), GET_TEXT_F(MSG_RAISE_PLUNGER)) .enabled(!isPrinting()).tag(7).button( BTN_POS(1,7), BTN_SIZE(2,1), GET_TEXT_F(MSG_RELEASE_XY_AXIS)) .colors(action_btn) .tag(1).button( BTN_POS(1,8), BTN_SIZE(2,1), GET_TEXT_F(MSG_BACK)); } #undef GRID_COLS #undef GRID_ROWS } bool TuneMenu::onTouchEnd(uint8_t tag) { switch (tag) { case 1: GOTO_PREVIOUS(); break; case 2: GOTO_SCREEN(FeedratePercentScreen); break; case 3: GOTO_SCREEN(TemperatureScreen); break; case 4: GOTO_SCREEN(NudgeNozzleScreen); break; case 5: GOTO_SCREEN(BioConfirmHomeXYZ); break; case 6: SpinnerDialogBox::enqueueAndWait_P(F("G0 E0 F120")); break; case 7: StatusScreen::unlockMotors(); break; default: return false; } return true; } #endif // TOUCH_UI_FTDI_EVE
tetious/Marlin
Marlin/src/lcd/extui/lib/ftdi_eve_touch_ui/screens/bio_tune_menu.cpp
C++
gpl-3.0
3,525
/* * Copyright (C) 2006-2010 - Frictional Games * * This file is part of HPL1 Engine. * * HPL1 Engine 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. * * HPL1 Engine 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 HPL1 Engine. If not, see <http://www.gnu.org/licenses/>. */ #include "scene/Entity3D.h" #include "scene/Node3D.h" #include "math/Math.h" #include "graphics/RenderList.h" #include "system/LowLevelSystem.h" #include "scene/PortalContainer.h" namespace hpl { ////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- iEntity3D::iEntity3D(tString asName) : iEntity(asName) { m_mtxLocalTransform = cMatrixf::Identity; m_mtxWorldTransform = cMatrixf::Identity; mbTransformUpdated = true; mlCount = 0; mlGlobalRenderCount = cRenderList::GetGlobalRenderCount(); msSourceFile = ""; mbApplyTransformToBV = true; mbUpdateBoundingVolume = true; mpParent = NULL; mlIteratorCount =-1; mpCurrentSector = NULL; } iEntity3D::~iEntity3D() { if(mpParent) mpParent->RemoveChild(this); for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it) { iEntity3D *pChild = *it; pChild->mpParent = NULL; } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- cVector3f iEntity3D::GetLocalPosition() { return m_mtxLocalTransform.GetTranslation(); } //----------------------------------------------------------------------- cMatrixf& iEntity3D::GetLocalMatrix() { return m_mtxLocalTransform; } //----------------------------------------------------------------------- cVector3f iEntity3D::GetWorldPosition() { UpdateWorldTransform(); return m_mtxWorldTransform.GetTranslation(); } //----------------------------------------------------------------------- cMatrixf& iEntity3D::GetWorldMatrix() { UpdateWorldTransform(); return m_mtxWorldTransform; } //----------------------------------------------------------------------- void iEntity3D::SetPosition(const cVector3f& avPos) { m_mtxLocalTransform.m[0][3] = avPos.x; m_mtxLocalTransform.m[1][3] = avPos.y; m_mtxLocalTransform.m[2][3] = avPos.z; SetTransformUpdated(); } //----------------------------------------------------------------------- void iEntity3D::SetMatrix(const cMatrixf& a_mtxTransform) { m_mtxLocalTransform = a_mtxTransform; SetTransformUpdated(); } //----------------------------------------------------------------------- void iEntity3D::SetWorldPosition(const cVector3f& avWorldPos) { if(mpParent) { SetPosition(avWorldPos - mpParent->GetWorldPosition()); } else { SetPosition(avWorldPos); } } //----------------------------------------------------------------------- void iEntity3D::SetWorldMatrix(const cMatrixf& a_mtxWorldTransform) { if(mpParent) { SetMatrix(cMath::MatrixMul(cMath::MatrixInverse(mpParent->GetWorldMatrix()), a_mtxWorldTransform)); } else { SetMatrix(a_mtxWorldTransform); } } //----------------------------------------------------------------------- void iEntity3D::SetTransformUpdated(bool abUpdateCallbacks) { mbTransformUpdated = true; mlCount++; //Perhaps not update this yet? This is baaaad! if(mbApplyTransformToBV) mBoundingVolume.SetTransform(GetWorldMatrix()); mbUpdateBoundingVolume = true; //Update children for(tEntity3DListIt EntIt = mlstChildren.begin(); EntIt != mlstChildren.end();++EntIt) { iEntity3D *pChild = *EntIt; pChild->SetTransformUpdated(true); } //Update callbacks if(mlstCallbacks.empty() || abUpdateCallbacks==false) return; tEntityCallbackListIt it = mlstCallbacks.begin(); for(; it!= mlstCallbacks.end(); ++it) { iEntityCallback* pCallback = *it; pCallback->OnTransformUpdate(this); } } //----------------------------------------------------------------------- bool iEntity3D::GetTransformUpdated() { return mbTransformUpdated; } //----------------------------------------------------------------------- int iEntity3D::GetTransformUpdateCount() { return mlCount; } //----------------------------------------------------------------------- void iEntity3D::AddCallback(iEntityCallback *apCallback) { mlstCallbacks.push_back(apCallback); } //----------------------------------------------------------------------- void iEntity3D::RemoveCallback(iEntityCallback *apCallback) { STLFindAndDelete(mlstCallbacks, apCallback); } //----------------------------------------------------------------------- void iEntity3D::AddChild(iEntity3D *apEntity) { if(apEntity==NULL)return; if(apEntity->mpParent != NULL) return; mlstChildren.push_back(apEntity); apEntity->mpParent = this; apEntity->SetTransformUpdated(true); } void iEntity3D::RemoveChild(iEntity3D *apEntity) { for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();) { iEntity3D *pChild = *it; if(pChild == apEntity) { pChild->mpParent = NULL; it = mlstChildren.erase(it); } else { ++it; } } } bool iEntity3D::IsChild(iEntity3D *apEntity) { for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it) { iEntity3D *pChild = *it; if(pChild == apEntity) return true; } return false; } iEntity3D * iEntity3D::GetEntityParent() { return mpParent; } //----------------------------------------------------------------------- bool iEntity3D::IsInSector(cSector *apSector) { //Log("-- %s --\n",msName.c_str()); //bool bShouldReturnTrue = false; if(apSector == GetCurrentSector()) { //Log("Should return true\n"); //bShouldReturnTrue = true; return true; } tRenderContainerDataList *pDataList = GetRenderContainerDataList(); tRenderContainerDataListIt it = pDataList->begin(); for(; it != pDataList->end(); ++it) { iRenderContainerData *pRenderContainerData = *it; cSector *pSector = static_cast<cSector*>(pRenderContainerData); //Log("%s (%d) vs %s (%d)\n",pSector->GetId().c_str(),pSector, apSector->GetId().c_str(),apSector); if(pSector == apSector) { //Log("return true!\n"); return true; } } //if(bShouldReturnTrue)Log(" %s should have returned true. Sectors: %d\n",msName.c_str(), mlstRenderContainerData.size()); //Log("return false!\n"); return false; } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- void iEntity3D::UpdateWorldTransform() { if(mbTransformUpdated) { mbTransformUpdated = false; //first check if there is a node parent if(mpParentNode) { cNode3D* pNode3D = static_cast<cNode3D*>(mpParentNode); m_mtxWorldTransform = cMath::MatrixMul(pNode3D->GetWorldMatrix(), m_mtxLocalTransform); } //If there is no node parent check for entity parent else if(mpParent) { m_mtxWorldTransform = cMath::MatrixMul(mpParent->GetWorldMatrix(), m_mtxLocalTransform); } else { m_mtxWorldTransform = m_mtxLocalTransform; } } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // SAVE OBJECT STUFF ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- kBeginSerializeVirtual(cSaveData_iEntity3D,cSaveData_iEntity) kSerializeVar(m_mtxLocalTransform,eSerializeType_Matrixf) kSerializeVar(mBoundingVolume,eSerializeType_Class) kSerializeVar(msSourceFile,eSerializeType_String) kSerializeVar(mlParentId,eSerializeType_Int32) kSerializeVarContainer(mlstChildren,eSerializeType_Int32) kEndSerialize() //----------------------------------------------------------------------- iSaveData* iEntity3D::CreateSaveData() { return NULL; } //----------------------------------------------------------------------- void iEntity3D::SaveToSaveData(iSaveData *apSaveData) { kSaveData_SaveToBegin(iEntity3D); //Log("-------- Saving %s --------------\n",msName.c_str()); kSaveData_SaveTo(m_mtxLocalTransform); kSaveData_SaveTo(mBoundingVolume); kSaveData_SaveTo(msSourceFile); kSaveData_SaveObject(mpParent,mlParentId); kSaveData_SaveIdList(mlstChildren,tEntity3DListIt,mlstChildren); /*if(mlstChildren.empty()==false) { Log("Children in '%s'/'%s': ",msName.c_str(),GetEntityType().c_str()); for(tEntity3DListIt it=mlstChildren.begin(); it != mlstChildren.end(); ++it) { iEntity3D *pEntity = *it; Log("('%d/%s'/'%s'), ",pEntity->GetSaveObjectId(),pEntity->GetName().c_str(),pEntity->GetEntityType().c_str()); } Log("\n"); }*/ } //----------------------------------------------------------------------- void iEntity3D::LoadFromSaveData(iSaveData *apSaveData) { kSaveData_LoadFromBegin(iEntity3D); //Log("-------- Loading %s --------------\n",msName.c_str()); SetMatrix(pData->m_mtxLocalTransform); //Not sure of this is needed: kSaveData_LoadFrom(mBoundingVolume); kSaveData_LoadFrom(msSourceFile); } //----------------------------------------------------------------------- void iEntity3D::SaveDataSetup(cSaveObjectHandler *apSaveObjectHandler, cGame *apGame) { kSaveData_SetupBegin(iEntity3D); //Log("-------- Setup %s --------------\n",msName.c_str()); //kSaveData_LoadObject(mpParent,mlParentId,iEntity3D*); //kSaveData_LoadIdList(mlstChildren,mlstChildren,iEntity3D*); if(pData->mlParentId!=-1 && mpParent == NULL) { iEntity3D *pParentEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(pData->mlParentId)); if(pParentEntity) pParentEntity->AddChild(this); else Error("Couldn't find parent entity id %d for '%s'\n",pData->mlParentId,GetName().c_str()); } cContainerListIterator<int> it = pData->mlstChildren.GetIterator(); while(it.HasNext()) { int mlId = it.Next(); if(mlId != -1) { iEntity3D *pChildEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(mlId)); if(pChildEntity) AddChild(pChildEntity); else Error("Couldn't find child entity id %d for '%s'\n",mlId,GetName().c_str()); } } SetTransformUpdated(true); } //----------------------------------------------------------------------- }
FrictionalGames/HPL1Engine
sources/scene/Entity3D.cpp
C++
gpl-3.0
11,350
from feeluown.utils.dispatch import Signal from feeluown.gui.widgets.my_music import MyMusicModel class MyMusicItem(object): def __init__(self, text): self.text = text self.clicked = Signal() class MyMusicUiManager: """ .. note:: 目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。 我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic 的上下文。 而 Provider 是比较上层的对象,我们会提供 get_item 这种比较精细的控制方法。 """ def __init__(self, app): self._app = app self._items = [] self.model = MyMusicModel(app) @classmethod def create_item(cls, text): return MyMusicItem(text) def add_item(self, item): self.model.add(item) self._items.append(item) def clear(self): self._items.clear() self.model.clear()
cosven/FeelUOwn
feeluown/gui/uimodels/my_music.py
Python
gpl-3.0
980
(function() { var app = angular.module('article-directive', ['ui.bootstrap.contextMenu']); app.config(function($sceProvider) { // Completely disable SCE. For demonstration purposes only! // Do not use in new projects. $sceProvider.enabled(false); }); app.directive('article', function () { var controller = function () { var vm = this; }; var getSelectionText = function() { if(window.getSelection) { return window.getSelection().toString(); } if(document.selection && document.selection.type != "Control") { return document.selection.createRange().text; } return ""; }; var link = function link(scope, element, attrs) { scope.toggleComments = function () { scope.$broadcast("event:toggle"); } scope.menuOptions = [['Copy', function ($itemScope) { }], null, // Dividier ['Comment', function ($itemScope) { scope.toggleComments(); }]]; }; return { restrict: 'EA', //Default for 1.3+ scope: { text: '@text', url: '@url' }, controller: controller, link: link, controllerAs: 'vm', bindToController: true, //required in 1.3+ with controllerAs templateUrl: '/article/article.html' }; }); }());
lowdev/Article-Annotater
src/main/resources/static/article/angular-article-directive.js
JavaScript
gpl-3.0
1,330
/******************************************************************************* * This file is part of RedReader. * * RedReader 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. * * RedReader 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 RedReader. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.quantumbadger.redreader.io; import org.quantumbadger.redreader.common.collections.WeakReferenceListManager; public class UpdatedVersionListenerNotifier<K, V extends WritableObject<K>> implements WeakReferenceListManager.ArgOperator<UpdatedVersionListener<K, V>, V> { @Override public void operate(final UpdatedVersionListener<K, V> listener, final V data) { listener.onUpdatedVersion(data); } }
QuantumBadger/RedReader
src/main/java/org/quantumbadger/redreader/io/UpdatedVersionListenerNotifier.java
Java
gpl-3.0
1,255
<?php /** * Copyright 2013 Android Holo Colors by Jérôme Van Der Linden * Copyright 2010 Android Asset Studio by Google Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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. */ require_once('common-fastscroll.php'); $color = $_GET['color']; $size = $_GET['size']; $holo = $_GET['holo']; $component = $_GET['component']; if (isset($color) && isset($size) && isset($holo) && isset($component)) { switch ($component) { case "fastscroll": $et = new Fastscroll(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; case "fastscroll-pressed": $et = new FastscrollPressed(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; default: $et = new Fastscroll(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; } $et->generate_image($color, $size, $holo); } ?>
Medialoha/MAB-LAB
libs/asset-studio-colors/widgets/fastscroll/fastscroll.php
PHP
gpl-3.0
1,370
/* * This file is protected by Copyright. Please refer to the COPYRIGHT file * distributed with this source distribution. * * This file is part of GNUHAWK. * * GNUHAWK is free software: you can redistribute it and/or modify is 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. * * GNUHAWK 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 "streams_to_stream_ff_1i_base.h" /******************************************************************************************* AUTO-GENERATED CODE. DO NOT MODIFY The following class functions are for the base class for the component class. To customize any of these functions, do not modify them here. Instead, overload them on the child class ******************************************************************************************/ streams_to_stream_ff_1i_base::streams_to_stream_ff_1i_base(const char *uuid, const char *label) : GnuHawkBlock(uuid, label), serviceThread(0), noutput_items(0), _maintainTimeStamp(false), _throttle(false) { construct(); } void streams_to_stream_ff_1i_base::construct() { Resource_impl::_started = false; loadProperties(); serviceThread = 0; sentEOS = false; inputPortOrder.resize(0);; outputPortOrder.resize(0); PortableServer::ObjectId_var oid; float_in = new bulkio::InFloatPort("float_in"); float_in->setNewStreamListener(this, &streams_to_stream_ff_1i_base::float_in_newStreamCallback); oid = ossie::corba::RootPOA()->activate_object(float_in); float_out = new bulkio::OutFloatPort("float_out"); oid = ossie::corba::RootPOA()->activate_object(float_out); registerInPort(float_in); inputPortOrder.push_back("float_in"); registerOutPort(float_out, float_out->_this()); outputPortOrder.push_back("float_out"); } /******************************************************************************************* Framework-level functions These functions are generally called by the framework to perform housekeeping. *******************************************************************************************/ void streams_to_stream_ff_1i_base::initialize() throw (CF::LifeCycle::InitializeError, CORBA::SystemException) { } void streams_to_stream_ff_1i_base::start() throw (CORBA::SystemException, CF::Resource::StartError) { boost::mutex::scoped_lock lock(serviceThreadLock); if (serviceThread == 0) { float_in->unblock(); serviceThread = new ProcessThread<streams_to_stream_ff_1i_base>(this, 0.1); serviceThread->start(); } if (!Resource_impl::started()) { Resource_impl::start(); } } void streams_to_stream_ff_1i_base::stop() throw (CORBA::SystemException, CF::Resource::StopError) { if ( float_in ) float_in->block(); { boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.clear(); } // release the child thread (if it exists) if (serviceThread != 0) { { boost::mutex::scoped_lock lock(serviceThreadLock); LOG_TRACE( streams_to_stream_ff_1i_base, "Stopping Service Function" ); serviceThread->stop(); } if ( !serviceThread->release()) { throw CF::Resource::StopError(CF::CF_NOTSET, "Processing thread did not die"); } boost::mutex::scoped_lock lock(serviceThreadLock); if ( serviceThread ) { delete serviceThread; } } serviceThread = 0; if (Resource_impl::started()) { Resource_impl::stop(); } LOG_TRACE( streams_to_stream_ff_1i_base, "COMPLETED STOP REQUEST" ); } CORBA::Object_ptr streams_to_stream_ff_1i_base::getPort(const char* _id) throw (CORBA::SystemException, CF::PortSupplier::UnknownPort) { std::map<std::string, Port_Provides_base_impl *>::iterator p_in = inPorts.find(std::string(_id)); if (p_in != inPorts.end()) { if (!strcmp(_id,"float_in")) { bulkio::InFloatPort *ptr = dynamic_cast<bulkio::InFloatPort *>(p_in->second); if (ptr) { return ptr->_this(); } } } std::map<std::string, CF::Port_var>::iterator p_out = outPorts_var.find(std::string(_id)); if (p_out != outPorts_var.end()) { return CF::Port::_duplicate(p_out->second); } throw (CF::PortSupplier::UnknownPort()); } void streams_to_stream_ff_1i_base::releaseObject() throw (CORBA::SystemException, CF::LifeCycle::ReleaseError) { // This function clears the component running condition so main shuts down everything try { stop(); } catch (CF::Resource::StopError& ex) { // TODO - this should probably be logged instead of ignored } // deactivate ports releaseInPorts(); releaseOutPorts(); delete(float_in); delete(float_out); Resource_impl::releaseObject(); } void streams_to_stream_ff_1i_base::loadProperties() { addProperty(item_size, 4, "item_size", "item_size", "readonly", "", "external", "configure"); addProperty(nstreams, 1, "nstreams", "nstreams", "readonly", "", "external", "configure"); } // // Allow for logging // PREPARE_LOGGING(streams_to_stream_ff_1i_base); inline static unsigned int round_up (unsigned int n, unsigned int multiple) { return ((n + multiple - 1) / multiple) * multiple; } inline static unsigned int round_down (unsigned int n, unsigned int multiple) { return (n / multiple) * multiple; } uint32_t streams_to_stream_ff_1i_base::getNOutputStreams() { return 0; } void streams_to_stream_ff_1i_base::setupIOMappings( ) { int ninput_streams = 0; int noutput_streams = 0; std::vector<std::string>::iterator pname; std::string sid(""); int inMode=RealMode; if ( !validGRBlock() ) return; ninput_streams = gr_sptr->get_max_input_streams(); gr_io_signature_sptr g_isig = gr_sptr->input_signature(); noutput_streams = gr_sptr->get_max_output_streams(); gr_io_signature_sptr g_osig = gr_sptr->output_signature(); LOG_DEBUG( streams_to_stream_ff_1i_base, "GNUHAWK IO MAPPINGS IN/OUT " << ninput_streams << "/" << noutput_streams ); // // Someone reset the GR Block so we need to clean up old mappings if they exists // we need to reset the io signatures and check the vlens // if ( _istreams.size() > 0 || _ostreams.size() > 0 ) { LOG_DEBUG( streams_to_stream_ff_1i_base, "RESET INPUT SIGNATURE SIZE:" << _istreams.size() ); IStreamList::iterator istream; for ( int idx=0 ; istream != _istreams.end(); idx++, istream++ ) { // re-add existing stream definitons LOG_DEBUG( streams_to_stream_ff_1i_base, "ADD READ INDEX TO GNU RADIO BLOCK"); if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // setup io signature istream->associate( gr_sptr ); } LOG_DEBUG( streams_to_stream_ff_1i_base, "RESET OUTPUT SIGNATURE SIZE:" << _ostreams.size() ); OStreamList::iterator ostream; for ( int idx=0 ; ostream != _ostreams.end(); idx++, ostream++ ) { // need to evaluate new settings...??? ostream->associate( gr_sptr ); } return; } // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio input stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // Stream Identifiers will be pass along as they are received // LOG_TRACE( streams_to_stream_ff_1i_base, "setupIOMappings INPUT PORTS: " << inPorts.size() ); pname = inputPortOrder.begin(); for( int i=0; pname != inputPortOrder.end(); pname++ ) { // grab ports based on their order in the scd.xml file RH_ProvidesPortMap::iterator p_in = inPorts.find(*pname); if ( p_in != inPorts.end() ) { bulkio::InFloatPort *port = dynamic_cast< bulkio::InFloatPort * >(p_in->second); int mode = inMode; sid = ""; // need to add read index to GNU Radio Block for processing streams when max_input == -1 if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // check if we received SRI during setup BULKIO::StreamSRISequence_var sris = port->activeSRIs(); if ( sris->length() > 0 ) { BULKIO::StreamSRI sri = sris[sris->length()-1]; mode = sri.mode; } std::vector<int> in; io_mapping.push_back( in ); _istreams.push_back( gr_istream< bulkio::InFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( streams_to_stream_ff_1i_base, "ADDING INPUT MAP IDX:" << i << " SID:" << sid ); // increment port counter i++; } } // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio output stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // LOG_TRACE( streams_to_stream_ff_1i_base, "setupIOMappings OutputPorts: " << outPorts.size() ); pname = outputPortOrder.begin(); for( int i=0; pname != outputPortOrder.end(); pname++ ) { // grab ports based on their order in the scd.xml file RH_UsesPortMap::iterator p_out = outPorts.find(*pname); if ( p_out != outPorts.end() ) { bulkio::OutFloatPort *port = dynamic_cast< bulkio::OutFloatPort * >(p_out->second); int idx = -1; BULKIO::StreamSRI sri = createOutputSRI( i, idx ); if (idx == -1) idx = i; if(idx < (int)io_mapping.size()) io_mapping[idx].push_back(i); int mode = sri.mode; sid = sri.streamID; _ostreams.push_back( gr_ostream< bulkio::OutFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( streams_to_stream_ff_1i_base, "ADDING OUTPUT MAP IDX:" << i << " SID:" << sid ); _ostreams[i].setSRI(sri, i ); // increment port counter i++; } } } void streams_to_stream_ff_1i_base::float_in_newStreamCallback( BULKIO::StreamSRI &sri ) { LOG_TRACE( streams_to_stream_ff_1i_base, "START NotifySRI port:stream " << float_in->getName() << "/" << sri.streamID); boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.push_back( std::make_pair( float_in, sri ) ); LOG_TRACE( streams_to_stream_ff_1i_base, "END NotifySRI QUEUE " << _sriQueue.size() << " port:stream " << float_in->getName() << "/" << sri.streamID); } void streams_to_stream_ff_1i_base::processStreamIdChanges() { boost::mutex::scoped_lock lock(_sriMutex); LOG_TRACE( streams_to_stream_ff_1i_base, "processStreamIDChanges QUEUE: " << _sriQueue.size() ); if ( _sriQueue.size() == 0 ) return; std::string sid(""); if ( validGRBlock() ) { IStreamList::iterator istream; int idx=0; std::string sid(""); int mode=0; SRIQueue::iterator item = _sriQueue.begin(); for ( ; item != _sriQueue.end(); item++ ) { idx = 0; sid = ""; mode= item->second.mode; sid = item->second.streamID; istream = _istreams.begin(); for ( ; istream != _istreams.end(); idx++, istream++ ) { if ( istream->port == item->first ) { LOG_DEBUG( streams_to_stream_ff_1i_base, " SETTING IN_STREAM ID/STREAM_ID :" << idx << "/" << sid ); istream->sri(true); istream->spe(mode); LOG_DEBUG( streams_to_stream_ff_1i_base, " SETTING OUT_STREAM ID/STREAM_ID :" << idx << "/" << sid ); setOutputStreamSRI( idx, item->second ); } } } _sriQueue.clear(); } else { LOG_WARN( streams_to_stream_ff_1i_base, " NEW STREAM ID, NO GNU RADIO BLOCK DEFINED, SRI QUEUE SIZE:" << _sriQueue.size() ); } } BULKIO::StreamSRI streams_to_stream_ff_1i_base::createOutputSRI( int32_t oidx ) { // for each output stream set the SRI context BULKIO::StreamSRI sri = BULKIO::StreamSRI(); sri.hversion = 1; sri.xstart = 0.0; sri.xdelta = 1; sri.xunits = BULKIO::UNITS_TIME; sri.subsize = 0; sri.ystart = 0.0; sri.ydelta = 0.0; sri.yunits = BULKIO::UNITS_NONE; sri.mode = 0; std::ostringstream t; t << naming_service_name.c_str() << "_" << oidx; std::string sid = t.str(); sri.streamID = CORBA::string_dup(sid.c_str()); return sri; } BULKIO::StreamSRI streams_to_stream_ff_1i_base::createOutputSRI( int32_t oidx, int32_t &in_idx) { return createOutputSRI( oidx ); } void streams_to_stream_ff_1i_base::adjustOutputRate(BULKIO::StreamSRI &sri ) { if ( validGRBlock() ) { double ret=sri.xdelta*gr_sptr->relative_rate(); /** ret = ret / gr_sptr->interpolation(); **/ LOG_TRACE( streams_to_stream_ff_1i_base, "ADJUSTING SRI.XDELTA FROM/TO: " << sri.xdelta << "/" << ret ); sri.xdelta = ret; } } streams_to_stream_ff_1i_base::TimeDuration streams_to_stream_ff_1i_base::getTargetDuration() { TimeDuration t_drate;; uint64_t samps=0; double xdelta=1.0; double trate=1.0; if ( _ostreams.size() > 0 ) { samps= _ostreams[0].nelems(); xdelta= _ostreams[0].sri.xdelta; } trate = samps*xdelta; uint64_t sec = (uint64_t)trunc(trate); uint64_t usec = (uint64_t)((trate-sec)*1e6); t_drate = boost::posix_time::seconds(sec) + boost::posix_time::microseconds(usec); LOG_TRACE( streams_to_stream_ff_1i_base, " SEC/USEC " << sec << "/" << usec << "\n" << " target_duration " << t_drate ); return t_drate; } streams_to_stream_ff_1i_base::TimeDuration streams_to_stream_ff_1i_base::calcThrottle( TimeMark &start_time, TimeMark &end_time ) { TimeDuration delta; TimeDuration target_duration = getTargetDuration(); if ( start_time.is_not_a_date_time() == false ) { TimeDuration s_dtime= end_time - start_time; delta = target_duration - s_dtime; delta /= 4; LOG_TRACE( streams_to_stream_ff_1i_base, " s_time/t_dime " << s_dtime << "/" << target_duration << "\n" << " delta " << delta ); } return delta; } template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int streams_to_stream_ff_1i_base::_transformerServiceFunction( typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams , typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams ) { typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList; typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList; boost::mutex::scoped_lock lock(serviceThreadLock); if ( validGRBlock() == false ) { // create our processing block, and setup property notifiers createBlock(); LOG_DEBUG( streams_to_stream_ff_1i_base, " FINISHED BUILDING GNU RADIO BLOCK"); } //process any Stream ID changes this could affect number of io streams processStreamIdChanges(); if ( !validGRBlock() || istreams.size() == 0 || ostreams.size() == 0 ) { LOG_WARN( streams_to_stream_ff_1i_base, "NO STREAMS ATTACHED TO BLOCK..." ); return NOOP; } _input_ready.resize( istreams.size() ); _ninput_items_required.resize( istreams.size() ); _ninput_items.resize( istreams.size() ); _input_items.resize( istreams.size() ); _output_items.resize( ostreams.size() ); // // RESOLVE: need to look at forecast strategy, // 1) see how many read items are necessary for N number of outputs // 2) read input data and see how much output we can produce // // // Grab available data from input streams // typename _OStreamList::iterator ostream; typename _IStreamList::iterator istream = istreams.begin(); int nitems=0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { // note this a blocking read that can cause deadlocks nitems = istream->read(); if ( istream->overrun() ) { LOG_WARN( streams_to_stream_ff_1i_base, " NOT KEEPING UP WITH STREAM ID:" << istream->streamID ); } if ( istream->sriChanged() ) { // RESOLVE - need to look at how SRI changes can affect Gnu Radio BLOCK state LOG_DEBUG( streams_to_stream_ff_1i_base, "SRI CHANGED, STREAMD IDX/ID: " << idx << "/" << istream->pkt->streamID ); setOutputStreamSRI( idx, istream->pkt->SRI ); } } LOG_TRACE( streams_to_stream_ff_1i_base, "READ NITEMS: " << nitems ); if ( nitems <= 0 && !_istreams[0].eos() ) { return NOOP; } bool eos = false; int nout = 0; bool workDone = false; while ( nout > -1 && serviceThread->threadRunning() ) { eos = false; nout = _forecastAndProcess( eos, istreams, ostreams ); if ( nout > -1 ) { workDone = true; // we chunked on data so move read pointer.. istream = istreams.begin(); for ( ; istream != istreams.end(); istream++ ) { int idx=std::distance( istreams.begin(), istream ); // if we processed data for this stream if ( _input_ready[idx] ) { size_t nitems = 0; try { nitems = gr_sptr->nitems_read( idx ); } catch(...){} if ( nitems > istream->nitems() ) { LOG_WARN( streams_to_stream_ff_1i_base, "WORK CONSUMED MORE DATA THAN AVAILABLE, READ/AVAILABLE " << nitems << "/" << istream->nitems() ); nitems = istream->nitems(); } istream->consume( nitems ); LOG_TRACE( streams_to_stream_ff_1i_base, " CONSUME READ DATA ITEMS/REMAIN " << nitems << "/" << istream->nitems()); } } gr_sptr->reset_read_index(); } // check for not enough data return if ( nout == -1 ) { // check for end of stream istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++) { if ( istream->eos() ) { eos=true; } } if ( eos ) { LOG_TRACE( streams_to_stream_ff_1i_base, "EOS SEEN, SENDING DOWNSTREAM " ); _forecastAndProcess( eos, istreams, ostreams); } } } if ( eos ) { istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++ ) { int idx=std::distance( istreams.begin(), istream ); LOG_DEBUG( streams_to_stream_ff_1i_base, " CLOSING INPUT STREAM IDX:" << idx ); istream->close(); } // close remaining output streams ostream = ostreams.begin(); for ( ; eos && ostream != ostreams.end(); ostream++ ) { int idx=std::distance( ostreams.begin(), ostream ); LOG_DEBUG( streams_to_stream_ff_1i_base, " CLOSING OUTPUT STREAM IDX:" << idx ); ostream->close(); } } // // set the read pointers of the GNU Radio Block to start at the beginning of the // supplied buffers // gr_sptr->reset_read_index(); LOG_TRACE( streams_to_stream_ff_1i_base, " END OF TRANSFORM SERVICE FUNCTION....." << noutput_items ); if ( nout == -1 && eos == false && !workDone ) { return NOOP; } else { return NORMAL; } } template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int streams_to_stream_ff_1i_base::_forecastAndProcess( bool &eos, typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams , typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams ) { typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList; typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList; typename _OStreamList::iterator ostream; typename _IStreamList::iterator istream = istreams.begin(); int nout = 0; bool dataReady = false; if ( !eos ) { uint64_t max_items_avail = 0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { LOG_TRACE( streams_to_stream_ff_1i_base, "GET MAX ITEMS: STREAM:"<< idx << " NITEMS/SCALARS:" << istream->nitems() << "/" << istream->_data.size() ); max_items_avail = std::max( istream->nitems(), max_items_avail ); } if ( max_items_avail == 0 ) { LOG_TRACE( streams_to_stream_ff_1i_base, "DATA CHECK - MAX ITEMS NOUTPUT/MAX_ITEMS:" << noutput_items << "/" << max_items_avail); return -1; } // // calc number of output elements based on input items available // noutput_items = 0; if ( !gr_sptr->fixed_rate() ) { noutput_items = round_down((int32_t) (max_items_avail * gr_sptr->relative_rate()), gr_sptr->output_multiple()); LOG_TRACE( streams_to_stream_ff_1i_base, " VARIABLE FORECAST NOUTPUT == " << noutput_items ); } else { istream = istreams.begin(); for ( int i=0; istream != istreams.end(); i++, istream++ ) { int t_noutput_items = gr_sptr->fixed_rate_ninput_to_noutput( istream->nitems() ); if ( gr_sptr->output_multiple_set() ) { t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple()); } if ( t_noutput_items > 0 ) { if ( noutput_items == 0 ) { noutput_items = t_noutput_items; } if ( t_noutput_items <= noutput_items ) { noutput_items = t_noutput_items; } } } LOG_TRACE( streams_to_stream_ff_1i_base, " FIXED FORECAST NOUTPUT/output_multiple == " << noutput_items << "/" << gr_sptr->output_multiple()); } // // ask the block how much input they need to produce noutput_items... // if enough data is available to process then set the dataReady flag // int32_t outMultiple = gr_sptr->output_multiple(); while ( !dataReady && noutput_items >= outMultiple ) { // // ask the block how much input they need to produce noutput_items... // gr_sptr->forecast(noutput_items, _ninput_items_required); LOG_TRACE( streams_to_stream_ff_1i_base, "--> FORECAST IN/OUT " << _ninput_items_required[0] << "/" << noutput_items ); istream = istreams.begin(); uint32_t dr_cnt=0; for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) { // check if buffer has enough elements _input_ready[idx] = false; if ( istream->nitems() >= (uint64_t)_ninput_items_required[idx] ) { _input_ready[idx] = true; dr_cnt++; } LOG_TRACE( streams_to_stream_ff_1i_base, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" << istream->nelems() << "/" << istream->nitems() << "/" << _ninput_items_required[idx] << "/" << _input_ready[idx]); } if ( dr_cnt < istreams.size() ) { if ( outMultiple > 1 ) { noutput_items -= outMultiple; } else { noutput_items /= 2; } } else { dataReady = true; } LOG_TRACE( streams_to_stream_ff_1i_base, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady ); } // check if data is ready... if ( !dataReady ) { LOG_TRACE( streams_to_stream_ff_1i_base, "DATA CHECK - NOT ENOUGH DATA AVAIL/REQ:" << _istreams[0].nitems() << "/" << _ninput_items_required[0] ); return -1; } // reset looping variables int ritems = 0; int nitems = 0; // reset caching vectors _output_items.clear(); _input_items.clear(); _ninput_items.clear(); istream = istreams.begin(); for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) { // check if the stream is ready if ( !_input_ready[idx] ) { continue; } // get number of items remaining try { ritems = gr_sptr->nitems_read( idx ); } catch(...){ // something bad has happened, we are missing an input stream LOG_ERROR( streams_to_stream_ff_1i_base, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" << istream->streamID ); return -2; } nitems = istream->nitems() - ritems; LOG_TRACE( streams_to_stream_ff_1i_base, " ISTREAM: IDX:" << idx << " ITEMS AVAIL/READ/REQ " << nitems << "/" << ritems << "/" << _ninput_items_required[idx] ); if ( nitems >= _ninput_items_required[idx] && nitems > 0 ) { //remove eos checks ...if ( nitems < _ninput_items_required[idx] ) nitems=0; _ninput_items.push_back( nitems ); _input_items.push_back( (const void *) (istream->read_pointer(ritems)) ); } } // // setup output buffer vector based on noutput.. // ostream = ostreams.begin(); for( ; ostream != ostreams.end(); ostream++ ) { ostream->resize(noutput_items); _output_items.push_back((void*)(ostream->write_pointer()) ); } nout=0; if ( _input_items.size() != 0 && serviceThread->threadRunning() ) { LOG_TRACE( streams_to_stream_ff_1i_base, " CALLING WORK.....N_OUT:" << noutput_items << " N_IN:" << nitems << " ISTREAMS:" << _input_items.size() << " OSTREAMS:" << _output_items.size()); nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items); LOG_TRACE( streams_to_stream_ff_1i_base, "RETURN WORK ..... N_OUT:" << nout); } // check for stop condition from work method if ( nout < gr_block::WORK_DONE ) { LOG_WARN( streams_to_stream_ff_1i_base, "WORK RETURNED STOP CONDITION..." << nout ); nout=0; eos = true; } } if (nout != 0 or eos ) { noutput_items = nout; LOG_TRACE( streams_to_stream_ff_1i_base, " WORK RETURNED: NOUT : " << nout << " EOS:" << eos); ostream = ostreams.begin(); typename IN_PORT_TYPE::dataTransfer *pkt=NULL; for ( int idx=0 ; ostream != ostreams.end(); idx++, ostream++ ) { pkt=NULL; int inputIdx = idx; if ( (size_t)(inputIdx) >= istreams.size() ) { for ( inputIdx= istreams.size()-1; inputIdx > -1; inputIdx--) { if ( istreams[inputIdx].pkt != NULL ) { pkt = istreams[inputIdx].pkt; break; } } } else { pkt = istreams[inputIdx].pkt; } LOG_TRACE( streams_to_stream_ff_1i_base, "PUSHING DATA ITEMS/STREAM_ID " << ostream->nitems() << "/" << ostream->streamID ); if ( _maintainTimeStamp ) { // set time stamp for output samples based on input time stamp if ( ostream->nelems() == 0 ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "SEED - TS SRI: xdelta:" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM WRITE: maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "SEED - TS frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif ostream->setTimeStamp( pkt->T, _maintainTimeStamp ); } // write out samples, and set next time stamp based on xdelta and noutput_items ostream->write ( noutput_items, eos ); } else { // use incoming packet's time stamp to forward if ( pkt ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "PKT - TS maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << pkt->T.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << pkt->T.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << pkt->T.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << pkt->T.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "PKT - TS frac:" << std::setprecision(12) << pkt->T.tfsec ); #endif ostream->write( noutput_items, eos, pkt->T ); } else { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM TOD maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM TOD frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif // use time of day as time stamp ostream->write( noutput_items, eos, _maintainTimeStamp ); } } } // for ostreams } return nout; }
RedhawkSDR/integration-gnuhawk
components/streams_to_stream_ff_1i/cpp/streams_to_stream_ff_1i_base.cpp
C++
gpl-3.0
31,922
/* Copyright (C) 2014 PencilBlue, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Interface for managing topics */ function ManageTopics() {} //inheritance util.inherits(ManageTopics, pb.BaseController); var SUB_NAV_KEY = 'manage_topics'; ManageTopics.prototype.render = function(cb) { var self = this; var dao = new pb.DAO(); dao.query('topic', pb.DAO.ANYWHERE, pb.DAO.PROJECT_ALL).then(function(topics) { if (util.isError(topics)) { //TODO handle this } //none to manage if(topics.length === 0) { self.redirect('/admin/content/topics/new', cb); return; } //currently, mongo cannot do case-insensitive sorts. We do it manually //until a solution for https://jira.mongodb.org/browse/SERVER-90 is merged. topics.sort(function(a, b) { var x = a.name.toLowerCase(); var y = b.name.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); var angularObjects = pb.js.getAngularObjects( { navigation: pb.AdminNavigation.get(self.session, ['content', 'topics'], self.ls), pills: pb.AdminSubnavService.get(SUB_NAV_KEY, self.ls, SUB_NAV_KEY), topics: topics }); self.setPageName(self.ls.get('MANAGE_TOPICS')); self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false)); self.ts.load('admin/content/topics/manage_topics', function(err, data) { var result = '' + data; cb({content: result}); }); }); }; ManageTopics.getSubNavItems = function(key, ls, data) { return [{ name: SUB_NAV_KEY, title: ls.get('MANAGE_TOPICS'), icon: 'refresh', href: '/admin/content/topics' }, { name: 'import_topics', title: '', icon: 'upload', href: '/admin/content/topics/import' }, { name: 'new_topic', title: '', icon: 'plus', href: '/admin/content/topics/new' }]; }; //register admin sub-nav pb.AdminSubnavService.registerFor(SUB_NAV_KEY, ManageTopics.getSubNavItems); //exports module.exports = ManageTopics;
shihokoui/pencilblue
plugins/pencilblue/controllers/admin/content/topics/manage_topics.js
JavaScript
gpl-3.0
2,715
/* Copyright David Strachan Buchan 2013 * This file is part of BounceBallGame. BounceBallGame 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. BounceBallGame 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 BounceBallGame. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.ashndave; import javax.swing.JFrame; import uk.co.ashndave.game.GameLoop; import uk.co.ashndave.game.Renderable; import uk.co.ashndave.game.Updateable; public class KeepyUppy { private static final String BriefLicence1 = "Copyright (C) 2013 David Strachan Buchan."; private static final String BriefLicence2 = "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>."; private static final String BriefLicence3 = "This is free software: you are free to change and redistribute it."; private static final String BriefLicence4 = "There is NO WARRANTY, to the extent permitted by law."; private static final String BriefLicence5 = "Written by David Strachan Buchan."; private static final String[] BriefLicence = new String[]{BriefLicence1, BriefLicence2,BriefLicence3,BriefLicence4,BriefLicence5}; private Thread animator; private GameLoop looper; private GamePanel gamePanel; private static KeepyUppy game; /** * @param args */ public static void main(String[] args) { printLicence(); game = new KeepyUppy(); javax.swing.SwingUtilities.invokeLater(new Runnable(){ public void run(){ game.createAndShowGUI(); } }); } private static void printLicence() { for(String licence : BriefLicence) { System.out.println(licence); } } protected void createAndShowGUI() { gamePanel = new GamePanel(); looper = new GameLoop(gamePanel, gamePanel); JFrame frame = new JFrame("Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gamePanel); frame.pack(); frame.setVisible(true); animator = new Thread(looper); animator.start(); } }
davidsbuchan/BounceBallGame
src/uk/co/ashndave/KeepyUppy.java
Java
gpl-3.0
2,378
<?php namespace spf\swoole\worker; interface IWebSocketWorker { public function onStart($server, $workerId); public function onShutdown($server, $workerId); public function onTask($server, $taskId, $fromId, $data); public function onFinish($server, $taskId, $data); public function onOpen($server, $request); public function onClose(); public function onMessage($server, $frame); }
zhangjunlei26/spf
vendor/spf/swoole/worker/IWebSocketWorker.php
PHP
gpl-3.0
419
// // UDPConnection.hpp for server in /home/galibe_s/rendu/Spider/server/core // // Made by stephane galibert // Login <galibe_s@epitech.net> // // Started on Sun Nov 6 17:00:50 2016 stephane galibert // Last update Thu Nov 10 12:34:21 2016 stephane galibert // #pragma once #include <iostream> #include <string> #include <queue> #include <memory> #include <boost/bind.hpp> #include "AConnection.hpp" class ConnectionManager; class UDPConnection : public AConnection { public: UDPConnection(boost::asio::io_service &io_service, RequestHandler &reqHandler, PluginManager &pluginManager, ConnectionManager &cm, ServerConfig &config, int port); virtual ~UDPConnection(void); virtual void start(void); virtual void write(Packet *packet); virtual void addLog(std::string const& toadd); virtual void connectDB(void); virtual void disconnectDB(void); virtual void broadcast(std::string const& msg); virtual void kill(void); protected: virtual void do_write(boost::system::error_code const& ec, size_t len); virtual void do_read(boost::system::error_code const& ec, size_t len); virtual void do_handshake(boost::system::error_code const& ec); void write(void); void read(void); boost::asio::ip::udp::socket _socket; boost::asio::ip::udp::endpoint _endpoint; boost::asio::streambuf _read; std::queue<Packet *> _toWrites; };
Stephouuu/Spider
server/core/UDPConnection.hpp
C++
gpl-3.0
1,378
<?php /* * Central de conhecimento FEJESP * Contato: ti@fejesp.org.br * Autor: Guilherme de Oliveira Souza (http://sitegui.com.br) * Data: 07/08/2013 */ // Retorna a árvore inicial para um dado caminho $caminho = @$_GET['caminho']; $pastas = preg_split('@/@', $caminho, -1, PREG_SPLIT_NO_EMPTY); $arvore = array('' => NULL); $nivelAtual = &$arvore['']; $pai = 0; for ($i=0; $i<count($pastas); $i++) { // Carrega cada nível da árvore, a partir da raiz $nivelAtual = array(); $subpastas = Query::query(false, NULL, 'SELECT id, nome, visibilidade, criador FROM pastas WHERE pai=? AND id!=0 ORDER BY nome', $pai); $achou = false; foreach ($subpastas as $dados) if (verificarVisibilidade('pasta', $dados['id'], $dados['visibilidade'], $dados['criador'])) { $nivelAtual[$dados['nome']] = NULL; if ($dados['nome'] == $pastas[$i]) { $achou = true; $pai = $dados['id']; } } // Verifica se a pasta está no caminho if (!$achou) retornarErro(); $nivelAtual = &$nivelAtual[$pastas[$i]]; } retornar($arvore);
fejesp/centralConhecimento
ajax/getArvoreInicial.php
PHP
gpl-3.0
1,039
function print_last_modif_date(v) { document.write("Last updated " + v.substr(7, 19)); }
francois-a/fastqtl
doc/script/print_last_modif_date.js
JavaScript
gpl-3.0
89
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License 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. */ package org.apache.sshd.common; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.Pair; /** * A wrapper that exposes a read-only {@link Map} access to the system * properties. Any attempt to modify it will throw {@link UnsupportedOperationException}. * The mapper uses the {@link #SYSPROPS_MAPPED_PREFIX} to filter and access' * only these properties, ignoring all others * * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ public final class SyspropsMapWrapper implements Map<String, Object> { /** * Prefix of properties used by the mapper to identify SSHD related settings */ public static final String SYSPROPS_MAPPED_PREFIX = "org.apache.sshd.config"; /** * The one and only wrapper instance */ public static final SyspropsMapWrapper INSTANCE = new SyspropsMapWrapper(); /** * A {@link PropertyResolver} with no parent that exposes the system properties */ public static final PropertyResolver SYSPROPS_RESOLVER = new PropertyResolver() { @Override public Map<String, Object> getProperties() { return SyspropsMapWrapper.INSTANCE; } @Override public PropertyResolver getParentPropertyResolver() { return null; } @Override public String toString() { return "SYSPROPS"; } }; private SyspropsMapWrapper() { super(); } @Override public void clear() { throw new UnsupportedOperationException("sysprops#clear() N/A"); } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public boolean containsValue(Object value) { // not the most efficient implementation, but we do not expect it to be called much Properties props = System.getProperties(); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (Objects.equals(v, value)) { return true; } } return false; } @Override public Set<Entry<String, Object>> entrySet() { Properties props = System.getProperties(); // return a copy in order to avoid concurrent modifications Set<Entry<String, Object>> entries = new TreeSet<Entry<String, Object>>(Pair.<String, Object>byKeyEntryComparator()); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (v != null) { entries.add(new Pair<>(getUnmappedSyspropKey(key), v)); } } return entries; } @Override public Object get(Object key) { return (key instanceof String) ? System.getProperty(getMappedSyspropKey(key)) : null; } @Override public boolean isEmpty() { return GenericUtils.isEmpty(keySet()); } @Override public Set<String> keySet() { Properties props = System.getProperties(); Set<String> keys = new TreeSet<>(); // filter out any non-SSHD properties for (String key : props.stringPropertyNames()) { if (isMappedSyspropKey(key)) { keys.add(getUnmappedSyspropKey(key)); } } return keys; } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("sysprops#put(" + key + ")[" + value + "] N/A"); } @Override public void putAll(Map<? extends String, ? extends Object> m) { throw new UnsupportedOperationException("sysprops#putAll(" + m + ") N/A"); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("sysprops#remove(" + key + ") N/A"); } @Override public int size() { return GenericUtils.size(keySet()); } @Override public Collection<Object> values() { Properties props = System.getProperties(); // return a copy in order to avoid concurrent modifications List<Object> values = new ArrayList<>(props.size()); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (v != null) { values.add(v); } } return values; } @Override public String toString() { return Objects.toString(System.getProperties(), null); } /** * @param key Key to be tested * @return {@code true} if key starts with {@link #SYSPROPS_MAPPED_PREFIX} * and continues with a dot followed by some characters */ public static boolean isMappedSyspropKey(String key) { return (GenericUtils.length(key) > (SYSPROPS_MAPPED_PREFIX.length() + 1)) && key.startsWith(SYSPROPS_MAPPED_PREFIX) && (key.charAt(SYSPROPS_MAPPED_PREFIX.length()) == '.'); } /** * @param key Key to be transformed * @return The &quot;pure&quot; key name if a mapped one, same as input otherwise * @see #isMappedSyspropKey(String) */ public static String getUnmappedSyspropKey(Object key) { String s = Objects.toString(key); return isMappedSyspropKey(s) ? s.substring(SYSPROPS_MAPPED_PREFIX.length() + 1 /* skip dot */) : s; } /** * @param key The original key * @return A key prefixed by {@link #SYSPROPS_MAPPED_PREFIX} * @see #isMappedSyspropKey(String) */ public static String getMappedSyspropKey(Object key) { return SYSPROPS_MAPPED_PREFIX + "." + key; } }
Niky4000/UsefulUtils
projects/ssh/apache_mina/apache-sshd-1.2.0/sshd-core/src/main/java/org/apache/sshd/common/SyspropsMapWrapper.java
Java
gpl-3.0
6,908
package com.baeldung.jhipster5.web.rest; import com.baeldung.jhipster5.BookstoreApp; import com.baeldung.jhipster5.config.Constants; import com.baeldung.jhipster5.domain.Authority; import com.baeldung.jhipster5.domain.User; import com.baeldung.jhipster5.repository.AuthorityRepository; import com.baeldung.jhipster5.repository.UserRepository; import com.baeldung.jhipster5.security.AuthoritiesConstants; import com.baeldung.jhipster5.service.MailService; import com.baeldung.jhipster5.service.UserService; import com.baeldung.jhipster5.service.dto.PasswordChangeDTO; import com.baeldung.jhipster5.service.dto.UserDTO; import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM; import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the AccountResource REST controller. * * @see AccountResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) public class AccountResourceIntTest { @Autowired private UserRepository userRepository; @Autowired private AuthorityRepository authorityRepository; @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private HttpMessageConverter<?>[] httpMessageConverters; @Autowired private ExceptionTranslator exceptionTranslator; @Mock private UserService mockUserService; @Mock private MailService mockMailService; private MockMvc restMvc; private MockMvc restUserMockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(mockMailService).sendActivationEmail(any()); AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); AccountResource accountUserMockResource = new AccountResource(userRepository, mockUserService, mockMailService); this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) .setMessageConverters(httpMessageConverters) .setControllerAdvice(exceptionTranslator) .build(); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) .setControllerAdvice(exceptionTranslator) .build(); } @Test public void testNonAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("")); } @Test public void testAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser("test"); return request; }) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("test")); } @Test public void testGetExistingAccount() throws Exception { Set<Authority> authorities = new HashSet<>(); Authority authority = new Authority(); authority.setName(AuthoritiesConstants.ADMIN); authorities.add(authority); User user = new User(); user.setLogin("test"); user.setFirstName("john"); user.setLastName("doe"); user.setEmail("john.doe@jhipster.com"); user.setImageUrl("http://placehold.it/50x50"); user.setLangKey("en"); user.setAuthorities(authorities); when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.login").value("test")) .andExpect(jsonPath("$.firstName").value("john")) .andExpect(jsonPath("$.lastName").value("doe")) .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) .andExpect(jsonPath("$.langKey").value("en")) .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); } @Test public void testGetUnknownAccount() throws Exception { when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isInternalServerError()); } @Test @Transactional public void testRegisterValid() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("test-register-valid"); validUser.setPassword("password"); validUser.setFirstName("Alice"); validUser.setLastName("Test"); validUser.setEmail("test-register-valid@example.com"); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); } @Test @Transactional public void testRegisterInvalidLogin() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("funky-log!n");// <-- invalid invalidUser.setPassword("password"); invalidUser.setFirstName("Funky"); invalidUser.setLastName("One"); invalidUser.setEmail("funky@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidEmail() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("password"); invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("invalid");// <-- invalid invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("123");// password with only 3 digits invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterNullPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword(null);// invalid null password invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterDuplicateLogin() throws Exception { // First registration ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("alice"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Something"); firstUser.setEmail("alice@example.com"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Duplicate login, different email ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin(firstUser.getLogin()); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail("alice2@example.com"); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setCreatedBy(firstUser.getCreatedBy()); secondUser.setCreatedDate(firstUser.getCreatedDate()); secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // First user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); // Second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); assertThat(testUser.isPresent()).isTrue(); testUser.get().setActivated(true); userRepository.save(testUser.get()); // Second (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterDuplicateEmail() throws Exception { // First user ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("test-register-duplicate-email"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Test"); firstUser.setEmail("test-register-duplicate-email@example.com"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Register first user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser1.isPresent()).isTrue(); // Duplicate email, different login ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin("test-register-duplicate-email-2"); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail(firstUser.getEmail()); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser2.isPresent()).isFalse(); Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); assertThat(testUser3.isPresent()).isTrue(); // Duplicate email - with uppercase email address ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); userWithUpperCaseEmail.setId(firstUser.getId()); userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); userWithUpperCaseEmail.setPassword(firstUser.getPassword()); userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); userWithUpperCaseEmail.setLastName(firstUser.getLastName()); userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register third (not activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) .andExpect(status().isCreated()); Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); assertThat(testUser4.isPresent()).isTrue(); assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); testUser4.get().setActivated(true); userService.updateUser((new UserDTO(testUser4.get()))); // Register 4th (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterAdminIsIgnored() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("badguy"); validUser.setPassword("password"); validUser.setFirstName("Bad"); validUser.setLastName("Guy"); validUser.setEmail("badguy@example.com"); validUser.setActivated(true); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); Optional<User> userDup = userRepository.findOneByLogin("badguy"); assertThat(userDup.isPresent()).isTrue(); assertThat(userDup.get().getAuthorities()).hasSize(1) .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); } @Test @Transactional public void testActivateAccount() throws Exception { final String activationKey = "some activation key"; User user = new User(); user.setLogin("activate-account"); user.setEmail("activate-account@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(false); user.setActivationKey(activationKey); userRepository.saveAndFlush(user); restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) .andExpect(status().isOk()); user = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(user.getActivated()).isTrue(); } @Test @Transactional public void testActivateAccountWithWrongKey() throws Exception { restMvc.perform(get("/api/activate?key=wrongActivationKey")) .andExpect(status().isInternalServerError()); } @Test @Transactional @WithMockUser("save-account") public void testSaveAccount() throws Exception { User user = new User(); user.setLogin("save-account"); user.setEmail("save-account@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-account@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); assertThat(updatedUser.getActivated()).isEqualTo(true); assertThat(updatedUser.getAuthorities()).isEmpty(); } @Test @Transactional @WithMockUser("save-invalid-email") public void testSaveInvalidEmail() throws Exception { User user = new User(); user.setLogin("save-invalid-email"); user.setEmail("save-invalid-email@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("invalid email"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); } @Test @Transactional @WithMockUser("save-existing-email") public void testSaveExistingEmail() throws Exception { User user = new User(); user.setLogin("save-existing-email"); user.setEmail("save-existing-email@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); User anotherUser = new User(); anotherUser.setLogin("save-existing-email2"); anotherUser.setEmail("save-existing-email2@example.com"); anotherUser.setPassword(RandomStringUtils.random(60)); anotherUser.setActivated(true); userRepository.saveAndFlush(anotherUser); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-existing-email2@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); } @Test @Transactional @WithMockUser("save-existing-email-and-login") public void testSaveExistingEmailAndLogin() throws Exception { User user = new User(); user.setLogin("save-existing-email-and-login"); user.setEmail("save-existing-email-and-login@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-existing-email-and-login@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); } @Test @Transactional @WithMockUser("change-password-wrong-existing-password") public void testChangePasswordWrongExistingPassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-wrong-existing-password"); user.setEmail("change-password-wrong-existing-password@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password") public void testChangePassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password"); user.setEmail("change-password@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password-too-small") public void testChangePasswordTooSmall() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-small"); user.setEmail("change-password-too-small@example.com"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-too-long") public void testChangePasswordTooLong() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-long"); user.setEmail("change-password-too-long@example.com"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-empty") public void testChangePasswordEmpty() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-empty"); user.setEmail("change-password-empty@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional public void testRequestPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@example.com")) .andExpect(status().isOk()); } @Test @Transactional public void testRequestPasswordResetUpperCaseEmail() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@EXAMPLE.COM")) .andExpect(status().isOk()); } @Test public void testRequestPasswordResetWrongEmail() throws Exception { restMvc.perform( post("/api/account/reset-password/init") .content("password-reset-wrong-email@example.com")) .andExpect(status().isBadRequest()); } @Test @Transactional public void testFinishPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset"); user.setEmail("finish-password-reset@example.com"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); } @Test @Transactional public void testFinishPasswordResetTooSmall() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset-too-small"); user.setEmail("finish-password-reset-too-small@example.com"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key too small"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("foo"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); } @Test @Transactional public void testFinishPasswordResetWrongKey() throws Exception { KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey("wrong reset key"); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isInternalServerError()); } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/web/rest/AccountResourceIntTest.java
Java
gpl-3.0
34,406
import { defineMessages } from 'react-intl'; export default defineMessages({ save: { id: 'cboard.components.FormDialog.save', defaultMessage: 'Save' }, cancel: { id: 'cboard.components.FormDialog.cancel', defaultMessage: 'Cancel' } });
shayc/cboard
src/components/UI/FormDialog/FormDialog.messages.js
JavaScript
gpl-3.0
261
<?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/>. /** * Defines various restore steps that will be used by common tasks in restore * * @package core_backup * @subpackage moodle2 * @category backup * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * delete old directories and conditionally create backup_temp_ids table */ class restore_create_and_clean_temp_stuff extends restore_execution_step { protected function define_execution() { $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally // If the table already exists, it's because restore_prechecks have been executed in the same // request (without problems) and it already contains a bunch of preloaded information (users...) // that we aren't going to execute again if ($exists) { // Inform plan about preloaded information $this->task->set_preloaded_information(); } // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_contextid(); $newitemid = context_course::instance($this->get_courseid())->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_system_contextid(); $newitemid = context_system::instance()->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-course-id to new-course-id mapping, we need that available since the beginning $itemid = $this->task->get_old_courseid(); $newitemid = $this->get_courseid(); restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid); } } /** * delete the temp dir used by backup/restore (conditionally), * delete old directories and drop temp ids table */ class restore_drop_and_clean_temp_stuff extends restore_execution_step { protected function define_execution() { global $CFG; restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table $progress = $this->task->get_progress(); $progress->start_progress('Deleting backup dir'); backup_helper::delete_old_backup_dirs(strtotime('-1 week'), $progress); // Delete > 1 week old temp dirs. if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir } $progress->end_progress(); } } /** * Restore calculated grade items, grade categories etc */ class restore_gradebook_structure_step extends restore_structure_step { /** * To conditionally decide if this step must be executed * Note the "settings" conditions are evaluated in the * corresponding task. Here we check for other conditions * not being restore settings (files, site settings...) */ protected function execute_condition() { global $CFG, $DB; if ($this->get_courseid() == SITEID) { return false; } // No gradebook info found, don't execute $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Some module present in backup file isn't available to restore // in this site, don't execute if ($this->task->is_missing_modules()) { return false; } // Some activity has been excluded to be restored, don't execute if ($this->task->is_excluding_activities()) { return false; } // There should only be one grade category (the 1 associated with the course itself) // If other categories already exist we're restoring into an existing course. // Restoring categories into a course with an existing category structure is unlikely to go well $category = new stdclass(); $category->courseid = $this->get_courseid(); $catcount = $DB->count_records('grade_categories', (array)$category); if ($catcount>1) { return false; } // Arrived here, execute the step return true; } protected function define_structure() { $paths = array(); $userinfo = $this->task->get_setting_value('users'); $paths[] = new restore_path_element('gradebook', '/gradebook'); $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category'); $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item'); if ($userinfo) { $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade'); } $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter'); $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting'); return $paths; } protected function process_gradebook($data) { } protected function process_grade_item($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->course = $this->get_courseid(); $data->courseid = $this->get_courseid(); if ($data->itemtype=='manual') { // manual grade items store category id in categoryid $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL); // if mapping failed put in course's grade category if (NULL == $data->categoryid) { $coursecat = grade_category::fetch_course_category($this->get_courseid()); $data->categoryid = $coursecat->id; } } else if ($data->itemtype=='course') { // course grade item stores their category id in iteminstance $coursecat = grade_category::fetch_course_category($this->get_courseid()); $data->iteminstance = $coursecat->id; } else if ($data->itemtype=='category') { // category grade items store their category id in iteminstance $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL); } else { throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype); } $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL); $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL); $data->locktime = $this->apply_date_offset($data->locktime); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $coursecategory = $newitemid = null; //course grade item should already exist so updating instead of inserting if($data->itemtype=='course') { //get the ID of the already created grade item $gi = new stdclass(); $gi->courseid = $this->get_courseid(); $gi->itemtype = $data->itemtype; //need to get the id of the grade_category that was automatically created for the course $category = new stdclass(); $category->courseid = $this->get_courseid(); $category->parent = null; //course category fullname starts out as ? but may be edited //$category->fullname = '?'; $coursecategory = $DB->get_record('grade_categories', (array)$category); $gi->iteminstance = $coursecategory->id; $existinggradeitem = $DB->get_record('grade_items', (array)$gi); if (!empty($existinggradeitem)) { $data->id = $newitemid = $existinggradeitem->id; $DB->update_record('grade_items', $data); } } else if ($data->itemtype == 'manual') { // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists. $gi = array( 'itemtype' => $data->itemtype, 'courseid' => $data->courseid, 'itemname' => $data->itemname, 'categoryid' => $data->categoryid, ); $newitemid = $DB->get_field('grade_items', 'id', $gi); } if (empty($newitemid)) { //in case we found the course category but still need to insert the course grade item if ($data->itemtype=='course' && !empty($coursecategory)) { $data->iteminstance = $coursecategory->id; } $newitemid = $DB->insert_record('grade_items', $data); } $this->set_mapping('grade_item', $oldid, $newitemid); } protected function process_grade_grade($data) { global $DB; $data = (object)$data; $oldid = $data->id; $olduserid = $data->userid; $data->itemid = $this->get_new_parentid('grade_item'); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->locktime = $this->apply_date_offset($data->locktime); // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled? $data->overridden = $this->apply_date_offset($data->overridden); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid)); if ($gradeexists) { $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } else { $newitemid = $DB->insert_record('grade_grades', $data); $this->set_mapping('grade_grades', $oldid, $newitemid); } } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } protected function process_grade_category($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->course = $this->get_courseid(); $data->courseid = $data->course; $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $newitemid = null; //no parent means a course level grade category. That may have been created when the course was created if(empty($data->parent)) { //parent was being saved as 0 when it should be null $data->parent = null; //get the already created course level grade category $category = new stdclass(); $category->courseid = $this->get_courseid(); $category->parent = null; $coursecategory = $DB->get_record('grade_categories', (array)$category); if (!empty($coursecategory)) { $data->id = $newitemid = $coursecategory->id; $DB->update_record('grade_categories', $data); } } // Add a warning about a removed setting. if (!empty($data->aggregatesubcats)) { set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1); } //need to insert a course category if (empty($newitemid)) { $newitemid = $DB->insert_record('grade_categories', $data); } $this->set_mapping('grade_category', $oldid, $newitemid); } protected function process_grade_letter($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->contextid = context_course::instance($this->get_courseid())->id; $gradeletter = (array)$data; unset($gradeletter['id']); if (!$DB->record_exists('grade_letters', $gradeletter)) { $newitemid = $DB->insert_record('grade_letters', $data); } else { $newitemid = $data->id; } $this->set_mapping('grade_letter', $oldid, $newitemid); } protected function process_grade_setting($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->courseid = $this->get_courseid(); if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) { $newitemid = $DB->insert_record('grade_settings', $data); } else { $newitemid = $data->id; } $this->set_mapping('grade_setting', $oldid, $newitemid); } /** * put all activity grade items in the correct grade category and mark all for recalculation */ protected function after_execute() { global $DB; $conditions = array( 'backupid' => $this->get_restoreid(), 'itemname' => 'grade_item'//, //'itemid' => $itemid ); $rs = $DB->get_recordset('backup_ids_temp', $conditions); // We need this for calculation magic later on. $mappings = array(); if (!empty($rs)) { foreach($rs as $grade_item_backup) { // Store the oldid with the new id. $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid; $updateobj = new stdclass(); $updateobj->id = $grade_item_backup->newitemid; //if this is an activity grade item that needs to be put back in its correct category if (!empty($grade_item_backup->parentitemid)) { $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null); if (!is_null($oldcategoryid)) { $updateobj->categoryid = $oldcategoryid; $DB->update_record('grade_items', $updateobj); } } else { //mark course and category items as needing to be recalculated $updateobj->needsupdate=1; $DB->update_record('grade_items', $updateobj); } } } $rs->close(); // We need to update the calculations for calculated grade items that may reference old // grade item ids using ##gi\d+##. // $mappings can be empty, use 0 if so (won't match ever) list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0); $sql = "SELECT gi.id, gi.calculation FROM {grade_items} gi WHERE gi.id {$sql} AND calculation IS NOT NULL"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $gradeitem) { // Collect all of the used grade item id references if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) { // This calculation doesn't reference any other grade items... EASY! continue; } // For this next bit we are going to do the replacement of id's in two steps: // 1. We will replace all old id references with a special mapping reference. // 2. We will replace all mapping references with id's // Why do we do this? // Because there potentially there will be an overlap of ids within the query and we // we substitute the wrong id.. safest way around this is the two step system $calculationmap = array(); $mapcount = 0; foreach ($matches[1] as $match) { // Check that the old id is known to us, if not it was broken to begin with and will // continue to be broken. if (!array_key_exists($match, $mappings)) { continue; } // Our special mapping key $mapping = '##MAPPING'.$mapcount.'##'; // The old id that exists within the calculation now $oldid = '##gi'.$match.'##'; // The new id that we want to replace the old one with. $newid = '##gi'.$mappings[$match].'##'; // Replace in the special mapping key $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation); // And record the mapping $calculationmap[$mapping] = $newid; $mapcount++; } // Iterate all special mappings for this calculation and replace in the new id's foreach ($calculationmap as $mapping => $newid) { $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation); } // Update the calculation now that its being remapped $DB->update_record('grade_items', $gradeitem); } $rs->close(); // Need to correct the grade category path and parent $conditions = array( 'courseid' => $this->get_courseid() ); $rs = $DB->get_recordset('grade_categories', $conditions); // Get all the parents correct first as grade_category::build_path() loads category parents from the DB foreach ($rs as $gc) { if (!empty($gc->parent)) { $grade_category = new stdClass(); $grade_category->id = $gc->id; $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent); $DB->update_record('grade_categories', $grade_category); } } $rs->close(); // Now we can rebuild all the paths $rs = $DB->get_recordset('grade_categories', $conditions); foreach ($rs as $gc) { $grade_category = new stdClass(); $grade_category->id = $gc->id; $grade_category->path = grade_category::build_path($gc); $grade_category->depth = substr_count($grade_category->path, '/') - 1; $DB->update_record('grade_categories', $grade_category); } $rs->close(); // Restore marks items as needing update. Update everything now. grade_regrade_final_grades($this->get_courseid()); } } /** * Step in charge of restoring the grade history of a course. * * The execution conditions are itendical to {@link restore_gradebook_structure_step} because * we do not want to restore the history if the gradebook and its content has not been * restored. At least for now. */ class restore_grade_history_structure_step extends restore_structure_step { protected function execute_condition() { global $CFG, $DB; if ($this->get_courseid() == SITEID) { return false; } // No gradebook info found, don't execute. $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Some module present in backup file isn't available to restore in this site, don't execute. if ($this->task->is_missing_modules()) { return false; } // Some activity has been excluded to be restored, don't execute. if ($this->task->is_excluding_activities()) { return false; } // There should only be one grade category (the 1 associated with the course itself). $category = new stdclass(); $category->courseid = $this->get_courseid(); $catcount = $DB->count_records('grade_categories', (array)$category); if ($catcount > 1) { return false; } // Arrived here, execute the step. return true; } protected function define_structure() { $paths = array(); // Settings to use. $userinfo = $this->get_setting_value('users'); $history = $this->get_setting_value('grade_histories'); if ($userinfo && $history) { $paths[] = new restore_path_element('grade_grade', '/grade_history/grade_grades/grade_grade'); } return $paths; } protected function process_grade_grade($data) { global $DB; $data = (object)($data); $olduserid = $data->userid; unset($data->id); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { // Do not apply the date offsets as this is history. $data->itemid = $this->get_mappingid('grade_item', $data->itemid); $data->oldid = $this->get_mappingid('grade_grades', $data->oldid); $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); $DB->insert_record('grade_grades_history', $data); } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } } /** * decode all the interlinks present in restored content * relying 100% in the restore_decode_processor that handles * both the contents to modify and the rules to be applied */ class restore_decode_interlinks extends restore_execution_step { protected function define_execution() { // Get the decoder (from the plan) $decoder = $this->task->get_decoder(); restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules // And launch it, everything will be processed $decoder->execute(); } } /** * first, ensure that we have no gaps in section numbers * and then, rebuid the course cache */ class restore_rebuild_course_cache extends restore_execution_step { protected function define_execution() { global $DB; // Although there is some sort of auto-recovery of missing sections // present in course/formats... here we check that all the sections // from 0 to MAX(section->section) exist, creating them if necessary $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid())); // Iterate over all sections for ($i = 0; $i <= $maxsection; $i++) { // If the section $i doesn't exist, create it if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) { $sectionrec = array( 'course' => $this->get_courseid(), 'section' => $i); $DB->insert_record('course_sections', $sectionrec); // missing section created } } // Rebuild cache now that all sections are in place rebuild_course_cache($this->get_courseid()); cache_helper::purge_by_event('changesincourse'); cache_helper::purge_by_event('changesincoursecat'); } } /** * Review all the tasks having one after_restore method * executing it to perform some final adjustments of information * not available when the task was executed. */ class restore_execute_after_restore extends restore_execution_step { protected function define_execution() { // Simply call to the execute_after_restore() method of the task // that always is the restore_final_task $this->task->launch_execute_after_restore(); } } /** * Review all the (pending) block positions in backup_ids, matching by * contextid, creating positions as needed. This is executed by the * final task, once all the contexts have been created */ class restore_review_pending_block_positions extends restore_execution_step { protected function define_execution() { global $DB; // Get all the block_position objects pending to match $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); // Process block positions, creating them or accumulating for final step foreach($rs as $posrec) { // Get the complete position object out of the info field. $position = backup_controller_dbops::decode_backup_temp_info($posrec->info); // If position is for one already mapped (known) contextid // process it now, creating the position, else nothing to // do, position finally discarded if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) { $position->contextid = $newctx->newitemid; // Create the block position $DB->insert_record('block_positions', $position); } } $rs->close(); } } /** * Updates the availability data for course modules and sections. * * Runs after the restore of all course modules, sections, and grade items has * completed. This is necessary in order to update IDs that have changed during * restore. * * @package core_backup * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class restore_update_availability extends restore_execution_step { protected function define_execution() { global $CFG, $DB; // Note: This code runs even if availability is disabled when restoring. // That will ensure that if you later turn availability on for the site, // there will be no incorrect IDs. (It doesn't take long if the restored // data does not contain any availability information.) // Get modinfo with all data after resetting cache. rebuild_course_cache($this->get_courseid(), true); $modinfo = get_fast_modinfo($this->get_courseid()); // Get the date offset for this restore. $dateoffset = $this->apply_date_offset(1) - 1; // Update all sections that were restored. $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); $sectionsbyid = null; foreach ($rs as $rec) { if (is_null($sectionsbyid)) { $sectionsbyid = array(); foreach ($modinfo->get_section_info_all() as $section) { $sectionsbyid[$section->id] = $section; } } if (!array_key_exists($rec->newitemid, $sectionsbyid)) { // If the section was not fully restored for some reason // (e.g. due to an earlier error), skip it. $this->get_logger()->process('Section not fully restored: id ' . $rec->newitemid, backup::LOG_WARNING); continue; } $section = $sectionsbyid[$rec->newitemid]; if (!is_null($section->availability)) { $info = new \core_availability\info_section($section); $info->update_after_restore($this->get_restoreid(), $this->get_courseid(), $this->get_logger(), $dateoffset); } } $rs->close(); // Update all modules that were restored. $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); foreach ($rs as $rec) { if (!array_key_exists($rec->newitemid, $modinfo->cms)) { // If the module was not fully restored for some reason // (e.g. due to an earlier error), skip it. $this->get_logger()->process('Module not fully restored: id ' . $rec->newitemid, backup::LOG_WARNING); continue; } $cm = $modinfo->get_cm($rec->newitemid); if (!is_null($cm->availability)) { $info = new \core_availability\info_module($cm); $info->update_after_restore($this->get_restoreid(), $this->get_courseid(), $this->get_logger(), $dateoffset); } } $rs->close(); } } /** * Process legacy module availability records in backup_ids. * * Matches course modules and grade item id once all them have been already restored. * Only if all matchings are satisfied the availability condition will be created. * At the same time, it is required for the site to have that functionality enabled. * * This step is included only to handle legacy backups (2.6 and before). It does not * do anything for newer backups. * * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ class restore_process_course_modules_availability extends restore_execution_step { protected function define_execution() { global $CFG, $DB; // Site hasn't availability enabled if (empty($CFG->enableavailability)) { return; } // Do both modules and sections. foreach (array('module', 'section') as $table) { // Get all the availability objects to process. $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); // Process availabilities, creating them if everything matches ok. foreach ($rs as $availrec) { $allmatchesok = true; // Get the complete legacy availability object. $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info); // Note: This code used to update IDs, but that is now handled by the // current code (after restore) instead of this legacy code. // Get showavailability option. $thingid = ($table === 'module') ? $availability->coursemoduleid : $availability->coursesectionid; $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), $table . '_showavailability', $thingid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availability object is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_' . $table . 's', 'availability', array('id' => $thingid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_condition( $currentvalue, $availability, $show); $DB->set_field('course_' . $table . 's', 'availability', $newvalue, array('id' => $thingid)); } } $rs->close(); } } /* * Execution step that, *conditionally* (if there isn't preloaded information) * will load the inforef files for all the included course/section/activity tasks * to backup_temp_ids. They will be stored with "xxxxref" as itemname */ class restore_load_included_inforef_records extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } // Get all the included tasks $tasks = restore_dbops::get_included_tasks($this->get_restoreid()); $progress = $this->task->get_progress(); $progress->start_progress($this->get_name(), count($tasks)); foreach ($tasks as $task) { // Load the inforef.xml file if exists $inforefpath = $task->get_taskbasepath() . '/inforef.xml'; if (file_exists($inforefpath)) { // Load each inforef file to temp_ids. restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress); } } $progress->end_progress(); } } /* * Execution step that will load all the needed files into backup_files_temp * - info: contains the whole original object (times, names...) * (all them being original ids as loaded from xml) */ class restore_load_included_files extends restore_structure_step { protected function define_structure() { $file = new restore_path_element('file', '/files/file'); return array($file); } /** * Process one <file> element from files.xml * * @param array $data the element data */ public function process_file($data) { $data = (object)$data; // handy // load it if needed: // - it it is one of the annotated inforef files (course/section/activity/block) // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever) // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use, // but then we'll need to change it to load plugins itself (because this is executed too early in restore) $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id); $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' || $data->component == 'grouping' || $data->component == 'grade' || $data->component == 'question' || substr($data->component, 0, 5) == 'qtype'); if ($isfileref || $iscomponent) { restore_dbops::set_backup_files_record($this->get_restoreid(), $data); } } } /** * Execution step that, *conditionally* (if there isn't preloaded information), * will load all the needed roles to backup_temp_ids. They will be stored with * "role" itemname. Also it will perform one automatic mapping to roles existing * in the target site, based in permissions of the user performing the restore, * archetypes and other bits. At the end, each original role will have its associated * target role or 0 if it's going to be skipped. Note we wrap everything over one * restore_dbops method, as far as the same stuff is going to be also executed * by restore prechecks */ class restore_load_and_map_roles extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded return; } $file = $this->get_basepath() . '/roles.xml'; // Load needed toles to temp_ids restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file); // Process roles, mapping/skipping. Any error throws exception // Note we pass controller's info because it can contain role mapping information // about manual mappings performed by UI restore_dbops::process_included_roles($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_info()->role_mappings); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * and users have been selected in settings, will load all the needed users * to backup_temp_ids. They will be stored with "user" itemname and with * their original contextid as paremitemid */ class restore_load_included_users extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do return; } $file = $this->get_basepath() . '/users.xml'; // Load needed users to temp_ids. restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress()); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * and users have been selected in settings, will process all the needed users * in order to decide and perform any action with them (create / map / error) * Note: Any error will cause exception, as far as this is the same processing * than the one into restore prechecks (that should have stopped process earlier) */ class restore_process_included_users extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do return; } restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress()); } } /** * Execution step that will create all the needed users as calculated * by @restore_process_included_users (those having newiteind = 0) */ class restore_create_included_users extends restore_execution_step { protected function define_execution() { restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->task->get_userid(), $this->task->get_progress()); } } /** * Structure step that will create all the needed groups and groupings * by loading them from the groups.xml file performing the required matches. * Note group members only will be added if restoring user info */ class restore_groups_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('group', '/groups/group'); $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping'); $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group'); return $paths; } // Processing functions go here public function process_group($data) { global $DB; $data = (object)$data; // handy $data->courseid = $this->get_courseid(); // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another a group in the same course $context = context_course::instance($data->courseid); if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) { unset($data->idnumber); } } else { unset($data->idnumber); } $oldid = $data->id; // need this saved for later $restorefiles = false; // Only if we end creating the group // Search if the group already exists (by name & description) in the target course $description_clause = ''; $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); if (!empty($data->description)) { $description_clause = ' AND ' . $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); $params['description'] = $data->description; } if (!$groupdb = $DB->get_record_sql("SELECT * FROM {groups} WHERE courseid = :courseid AND name = :grname $description_clause", $params)) { // group doesn't exist, create $newitemid = $DB->insert_record('groups', $data); $restorefiles = true; // We'll restore the files } else { // group exists, use it $newitemid = $groupdb->id; } // Save the id mapping $this->set_mapping('group', $oldid, $newitemid, $restorefiles); // Invalidate the course group data cache just in case. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); } public function process_grouping($data) { global $DB; $data = (object)$data; // handy $data->courseid = $this->get_courseid(); // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another a grouping in the same course $context = context_course::instance($data->courseid); if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) { unset($data->idnumber); } } else { unset($data->idnumber); } $oldid = $data->id; // need this saved for later $restorefiles = false; // Only if we end creating the grouping // Search if the grouping already exists (by name & description) in the target course $description_clause = ''; $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); if (!empty($data->description)) { $description_clause = ' AND ' . $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); $params['description'] = $data->description; } if (!$groupingdb = $DB->get_record_sql("SELECT * FROM {groupings} WHERE courseid = :courseid AND name = :grname $description_clause", $params)) { // grouping doesn't exist, create $newitemid = $DB->insert_record('groupings', $data); $restorefiles = true; // We'll restore the files } else { // grouping exists, use it $newitemid = $groupingdb->id; } // Save the id mapping $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles); // Invalidate the course group data cache just in case. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); } public function process_grouping_group($data) { global $CFG; require_once($CFG->dirroot.'/group/lib.php'); $data = (object)$data; groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded); } protected function after_execute() { // Add group related files, matching with "group" mappings $this->add_related_files('group', 'icon', 'group'); $this->add_related_files('group', 'description', 'group'); // Add grouping related files, matching with "grouping" mappings $this->add_related_files('grouping', 'description', 'grouping'); // Invalidate the course group data. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid())); } } /** * Structure step that will create all the needed group memberships * by loading them from the groups.xml file performing the required matches. */ class restore_groups_members_structure_step extends restore_structure_step { protected $plugins = null; protected function define_structure() { $paths = array(); // Add paths here if ($this->get_setting_value('users')) { $paths[] = new restore_path_element('group', '/groups/group'); $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member'); } return $paths; } public function process_group($data) { $data = (object)$data; // handy // HACK ALERT! // Not much to do here, this groups mapping should be already done from restore_groups_structure_step. // Let's fake internal state to make $this->get_new_parentid('group') work. $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id)); } public function process_member($data) { global $DB, $CFG; require_once("$CFG->dirroot/group/lib.php"); // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled. $data = (object)$data; // handy // get parent group->id $data->groupid = $this->get_new_parentid('group'); // map user newitemid and insert if not member already if ($data->userid = $this->get_mappingid('user', $data->userid)) { if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) { // Check the component, if any, exists. if (empty($data->component)) { groups_add_member($data->groupid, $data->userid); } else if ((strpos($data->component, 'enrol_') === 0)) { // Deal with enrolment groups - ignore the component and just find out the instance via new id, // it is possible that enrolment was restored using different plugin type. if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid); } } } } else { $dir = core_component::get_component_directory($data->component); if ($dir and is_dir($dir)) { if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) { return; } } // Bad luck, plugin could not restore the data, let's add normal membership. groups_add_member($data->groupid, $data->userid); $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead."; $this->log($message, backup::LOG_WARNING); } } } } } /** * Structure step that will create all the needed scales * by loading them from the scales.xml */ class restore_scales_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('scale', '/scales_definition/scale'); return $paths; } protected function process_scale($data) { global $DB; $data = (object)$data; $restorefiles = false; // Only if we end creating the group $oldid = $data->id; // need this saved for later // Look for scale (by 'scale' both in standard (course=0) and current course // with priority to standard scales (ORDER clause) // scale is not course unique, use get_record_sql to suppress warning // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc'); $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale); if (!$scadb = $DB->get_record_sql("SELECT * FROM {scale} WHERE courseid IN (0, :courseid) AND $compare_scale_clause ORDER BY courseid", $params, IGNORE_MULTIPLE)) { // Remap the user if possible, defaut to user performing the restore if not $userid = $this->get_mappingid('user', $data->userid); $data->userid = $userid ? $userid : $this->task->get_userid(); // Remap the course if course scale $data->courseid = $data->courseid ? $this->get_courseid() : 0; // If global scale (course=0), check the user has perms to create it // falling to course scale if not $systemctx = context_system::instance(); if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } // scale doesn't exist, create $newitemid = $DB->insert_record('scale', $data); $restorefiles = true; // We'll restore the files } else { // scale exists, use it $newitemid = $scadb->id; } // Save the id mapping (with files support at system context) $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); } protected function after_execute() { // Add scales related files, matching with "scale" mappings $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid()); } } /** * Structure step that will create all the needed outocomes * by loading them from the outcomes.xml */ class restore_outcomes_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome'); return $paths; } protected function process_outcome($data) { global $DB; $data = (object)$data; $restorefiles = false; // Only if we end creating the group $oldid = $data->id; // need this saved for later // Look for outcome (by shortname both in standard (courseid=null) and current course // with priority to standard outcomes (ORDER clause) // outcome is not course unique, use get_record_sql to suppress warning $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname); if (!$outdb = $DB->get_record_sql('SELECT * FROM {grade_outcomes} WHERE shortname = :shortname AND (courseid = :courseid OR courseid IS NULL) ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) { // Remap the user $userid = $this->get_mappingid('user', $data->usermodified); $data->usermodified = $userid ? $userid : $this->task->get_userid(); // Remap the scale $data->scaleid = $this->get_mappingid('scale', $data->scaleid); // Remap the course if course outcome $data->courseid = $data->courseid ? $this->get_courseid() : null; // If global outcome (course=null), check the user has perms to create it // falling to course outcome if not $systemctx = context_system::instance(); if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } // outcome doesn't exist, create $newitemid = $DB->insert_record('grade_outcomes', $data); $restorefiles = true; // We'll restore the files } else { // scale exists, use it $newitemid = $outdb->id; } // Set the corresponding grade_outcomes_courses record $outcourserec = new stdclass(); $outcourserec->courseid = $this->get_courseid(); $outcourserec->outcomeid = $newitemid; if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) { $DB->insert_record('grade_outcomes_courses', $outcourserec); } // Save the id mapping (with files support at system context) $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); } protected function after_execute() { // Add outcomes related files, matching with "outcome" mappings $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid()); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * will load all the question categories and questions (header info only) * to backup_temp_ids. They will be stored with "question_category" and * "question" itemnames and with their original contextid and question category * id as paremitemids */ class restore_load_categories_and_questions extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } $file = $this->get_basepath() . '/questions.xml'; restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file); } } /** * Execution step that, *conditionally* (if there isn't preloaded information) * will process all the needed categories and questions * in order to decide and perform any action with them (create / map / error) * Note: Any error will cause exception, as far as this is the same processing * than the one into restore prechecks (that should have stopped process earlier) */ class restore_process_categories_and_questions extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite()); } } /** * Structure step that will read the section.xml creating/updating sections * as needed, rebuilding course cache and other friends */ class restore_section_structure_step extends restore_structure_step { protected function define_structure() { global $CFG; $paths = array(); $section = new restore_path_element('section', '/section'); $paths[] = $section; if ($CFG->enableavailability) { $paths[] = new restore_path_element('availability', '/section/availability'); $paths[] = new restore_path_element('availability_field', '/section/availability_field'); } $paths[] = new restore_path_element('course_format_options', '/section/course_format_options'); // Apply for 'format' plugins optional paths at section level $this->add_plugin_structure('format', $section); // Apply for 'local' plugins optional paths at section level $this->add_plugin_structure('local', $section); return $paths; } public function process_section($data) { global $CFG, $DB; $data = (object)$data; $oldid = $data->id; // We'll need this later $restorefiles = false; // Look for the section $section = new stdclass(); $section->course = $this->get_courseid(); $section->section = $data->number; // Section doesn't exist, create it with all the info from backup if (!$secrec = $DB->get_record('course_sections', (array)$section)) { $section->name = $data->name; $section->summary = $data->summary; $section->summaryformat = $data->summaryformat; $section->sequence = ''; $section->visible = $data->visible; if (empty($CFG->enableavailability)) { // Process availability information only if enabled. $section->availability = null; } else { $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null; // Include legacy [<2.7] availability data if provided. if (is_null($section->availability)) { $section->availability = \core_availability\info::convert_legacy_fields( $data, true); } } $newitemid = $DB->insert_record('course_sections', $section); $restorefiles = true; // Section exists, update non-empty information } else { $section->id = $secrec->id; if ((string)$secrec->name === '') { $section->name = $data->name; } if (empty($secrec->summary)) { $section->summary = $data->summary; $section->summaryformat = $data->summaryformat; $restorefiles = true; } // Don't update availability (I didn't see a useful way to define // whether existing or new one should take precedence). $DB->update_record('course_sections', $section); $newitemid = $secrec->id; } // Annotate the section mapping, with restorefiles option if needed $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles); // set the new course_section id in the task $this->task->set_sectionid($newitemid); // If there is the legacy showavailability data, store this for later use. // (This data is not present when restoring 'new' backups.) if (isset($data->showavailability)) { // Cache the showavailability flag using the backup_ids data field. restore_dbops::set_backup_ids_record($this->get_restoreid(), 'section_showavailability', $newitemid, 0, null, (object)array('showavailability' => $data->showavailability)); } // Commented out. We never modify course->numsections as far as that is used // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x) // Note: We keep the code here, to know about and because of the possibility of making this // optional based on some setting/attribute in the future // If needed, adjust course->numsections //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) { // if ($numsections < $section->section) { // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid())); // } //} } /** * Process the legacy availability table record. This table does not exist * in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ public function process_availability($data) { $data = (object)$data; // Simply going to store the whole availability record now, we'll process // all them later in the final task (once all activities have been restored) // Let's call the low level one to be able to store the whole object. $data->coursesectionid = $this->task->get_sectionid(); restore_dbops::set_backup_ids_record($this->get_restoreid(), 'section_availability', $data->id, 0, null, $data); } /** * Process the legacy availability fields table record. This table does not * exist in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ public function process_availability_field($data) { global $DB; $data = (object)$data; // Mark it is as passed by default $passed = true; $customfieldid = null; // If a customfield has been used in order to pass we must be able to match an existing // customfield by name (data->customfield) and type (data->customfieldtype) if (is_null($data->customfield) xor is_null($data->customfieldtype)) { // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both. // If one is null but the other isn't something clearly went wrong and we'll skip this condition. $passed = false; } else if (!is_null($data->customfield)) { $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype); $customfieldid = $DB->get_field('user_info_field', 'id', $params); $passed = ($customfieldid !== false); } if ($passed) { // Create the object to insert into the database $availfield = new stdClass(); $availfield->coursesectionid = $this->task->get_sectionid(); $availfield->userfield = $data->userfield; $availfield->customfieldid = $customfieldid; $availfield->operator = $data->operator; $availfield->value = $data->value; // Get showavailability option. $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'section_showavailability', $availfield->coursesectionid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availfield object is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_sections', 'availability', array('id' => $availfield->coursesectionid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_field_condition( $currentvalue, $availfield, $show); $DB->set_field('course_sections', 'availability', $newvalue, array('id' => $availfield->coursesectionid)); } } public function process_course_format_options($data) { global $DB; $data = (object)$data; $oldid = $data->id; unset($data->id); $data->sectionid = $this->task->get_sectionid(); $data->courseid = $this->get_courseid(); $newid = $DB->insert_record('course_format_options', $data); $this->set_mapping('course_format_options', $oldid, $newid); } protected function after_execute() { // Add section related files, with 'course_section' itemid to match $this->add_related_files('course', 'section', 'course_section'); } } /** * Structure step that will read the course.xml file, loading it and performing * various actions depending of the site/restore settings. Note that target * course always exist before arriving here so this step will be updating * the course record (never inserting) */ class restore_course_structure_step extends restore_structure_step { /** * @var bool this gets set to true by {@link process_course()} if we are * restoring an old coures that used the legacy 'module security' feature. * If so, we have to do more work in {@link after_execute()}. */ protected $legacyrestrictmodules = false; /** * @var array Used when {@link $legacyrestrictmodules} is true. This is an * array with array keys the module names ('forum', 'quiz', etc.). These are * the modules that are allowed according to the data in the backup file. * In {@link after_execute()} we then have to prevent adding of all the other * types of activity. */ protected $legacyallowedmodules = array(); protected function define_structure() { $course = new restore_path_element('course', '/course'); $category = new restore_path_element('category', '/course/category'); $tag = new restore_path_element('tag', '/course/tags/tag'); $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module'); // Apply for 'format' plugins optional paths at course level $this->add_plugin_structure('format', $course); // Apply for 'theme' plugins optional paths at course level $this->add_plugin_structure('theme', $course); // Apply for 'report' plugins optional paths at course level $this->add_plugin_structure('report', $course); // Apply for 'course report' plugins optional paths at course level $this->add_plugin_structure('coursereport', $course); // Apply for plagiarism plugins optional paths at course level $this->add_plugin_structure('plagiarism', $course); // Apply for local plugins optional paths at course level $this->add_plugin_structure('local', $course); return array($course, $category, $tag, $allowed_module); } /** * Processing functions go here * * @global moodledatabase $DB * @param stdClass $data */ public function process_course($data) { global $CFG, $DB; $data = (object)$data; $fullname = $this->get_setting_value('course_fullname'); $shortname = $this->get_setting_value('course_shortname'); $startdate = $this->get_setting_value('course_startdate'); // Calculate final course names, to avoid dupes list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname); // Need to change some fields before updating the course record $data->id = $this->get_courseid(); $data->fullname = $fullname; $data->shortname= $shortname; // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another course on this site. $context = context::instance_by_id($this->task->get_contextid()); if (!empty($data->idnumber) && has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid()) && $this->task->is_samesite() && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) { // Do not reset idnumber. } else { $data->idnumber = ''; } // Any empty value for course->hiddensections will lead to 0 (default, show collapsed). // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532 if (empty($data->hiddensections)) { $data->hiddensections = 0; } // Set legacyrestrictmodules to true if the course was resticting modules. If so // then we will need to process restricted modules after execution. $this->legacyrestrictmodules = !empty($data->restrictmodules); $data->startdate= $this->apply_date_offset($data->startdate); if ($data->defaultgroupingid) { $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid); } if (empty($CFG->enablecompletion)) { $data->enablecompletion = 0; $data->completionstartonenrol = 0; $data->completionnotify = 0; } $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search if (!array_key_exists($data->lang, $languages)) { $data->lang = ''; } $themes = get_list_of_themes(); // Get themes for quick search later if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) { $data->theme = ''; } // Check if this is an old SCORM course format. if ($data->format == 'scorm') { $data->format = 'singleactivity'; $data->activitytype = 'scorm'; } // Course record ready, update it $DB->update_record('course', $data); course_get_format($data)->update_course_format_options($data); // Role name aliases restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid()); } public function process_category($data) { // Nothing to do with the category. UI sets it before restore starts } public function process_tag($data) { global $CFG, $DB; $data = (object)$data; if (!empty($CFG->usetags)) { // if enabled in server // TODO: This is highly inneficient. Each time we add one tag // we fetch all the existing because tag_set() deletes them // so everything must be reinserted on each call $tags = array(); $existingtags = tag_get_tags('course', $this->get_courseid()); // Re-add all the existitng tags foreach ($existingtags as $existingtag) { $tags[] = $existingtag->rawname; } // Add the one being restored $tags[] = $data->rawname; // Send all the tags back to the course tag_set('course', $this->get_courseid(), $tags, 'core', context_course::instance($this->get_courseid())->id); } } public function process_allowed_module($data) { $data = (object)$data; // Backwards compatiblity support for the data that used to be in the // course_allowed_modules table. if ($this->legacyrestrictmodules) { $this->legacyallowedmodules[$data->modulename] = 1; } } protected function after_execute() { global $DB; // Add course related files, without itemid to match $this->add_related_files('course', 'summary', null); $this->add_related_files('course', 'overviewfiles', null); // Deal with legacy allowed modules. if ($this->legacyrestrictmodules) { $context = context_course::instance($this->get_courseid()); list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities'); list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config'); foreach ($managerroleids as $roleid) { unset($roleids[$roleid]); } foreach (core_component::get_plugin_list('mod') as $modname => $notused) { if (isset($this->legacyallowedmodules[$modname])) { // Module is allowed, no worries. continue; } $capability = 'mod/' . $modname . ':addinstance'; foreach ($roleids as $roleid) { assign_capability($capability, CAP_PREVENT, $roleid, $context); } } } } } /** * Execution step that will migrate legacy files if present. */ class restore_course_legacy_files_step extends restore_execution_step { public function define_execution() { global $DB; // Do a check for legacy files and skip if there are none. $sql = 'SELECT count(*) FROM {backup_files_temp} WHERE backupid = ? AND contextid = ? AND component = ? AND filearea = ?'; $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy'); if ($DB->count_records_sql($sql, $params)) { $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid())); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course', 'legacy', $this->task->get_old_contextid(), $this->task->get_userid()); } } } /* * Structure step that will read the roles.xml file (at course/activity/block levels) * containing all the role_assignments and overrides for that context. If corresponding to * one mapped role, they will be applied to target context. Will observe the role_assignments * setting to decide if ras are restored. * * Note: this needs to be executed after all users are enrolled. */ class restore_ras_and_caps_structure_step extends restore_structure_step { protected $plugins = null; protected function define_structure() { $paths = array(); // Observe the role_assignments setting if ($this->get_setting_value('role_assignments')) { $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment'); } $paths[] = new restore_path_element('override', '/roles/role_overrides/override'); return $paths; } /** * Assign roles * * This has to be called after enrolments processing. * * @param mixed $data * @return void */ public function process_assignment($data) { global $DB; $data = (object)$data; // Check roleid, userid are one of the mapped ones if (!$newroleid = $this->get_mappingid('role', $data->roleid)) { return; } if (!$newuserid = $this->get_mappingid('user', $data->userid)) { return; } if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) { // Only assign roles to not deleted users return; } if (!$contextid = $this->task->get_contextid()) { return; } if (empty($data->component)) { // assign standard manual roles // TODO: role_assign() needs one userid param to be able to specify our restore userid role_assign($newroleid, $newuserid, $contextid); } else if ((strpos($data->component, 'enrol_') === 0)) { // Deal with enrolment roles - ignore the component and just find out the instance via new id, // it is possible that enrolment was restored using different plugin type. if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid); } } } } else { $data->roleid = $newroleid; $data->userid = $newuserid; $data->contextid = $contextid; $dir = core_component::get_component_directory($data->component); if ($dir and is_dir($dir)) { if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) { return; } } // Bad luck, plugin could not restore the data, let's add normal membership. role_assign($data->roleid, $data->userid, $data->contextid); $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead."; $this->log($message, backup::LOG_WARNING); } } public function process_override($data) { $data = (object)$data; // Check roleid is one of the mapped ones $newroleid = $this->get_mappingid('role', $data->roleid); // If newroleid and context are valid assign it via API (it handles dupes and so on) if ($newroleid && $this->task->get_contextid()) { // TODO: assign_capability() needs one userid param to be able to specify our restore userid // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ??? assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid()); } } } /** * If no instances yet add default enrol methods the same way as when creating new course in UI. */ class restore_default_enrolments_step extends restore_execution_step { public function define_execution() { global $DB; // No enrolments in front page. if ($this->get_courseid() == SITEID) { return; } $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST); if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) { // Something already added instances, do not add default instances. $plugins = enrol_get_plugins(true); foreach ($plugins as $plugin) { $plugin->restore_sync_course($course); } } else { // Looks like a newly created course. enrol_course_updated(true, $course, null); } } } /** * This structure steps restores the enrol plugins and their underlying * enrolments, performing all the mappings and/or movements required */ class restore_enrolments_structure_step extends restore_structure_step { protected $enrolsynced = false; protected $plugins = null; protected $originalstatus = array(); /** * Conditionally decide if this step should be executed. * * This function checks the following parameter: * * 1. the course/enrolments.xml file exists * * @return bool true is safe to execute, false otherwise */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore enrolments info return false; } return true; } protected function define_structure() { $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol'); $enrolment = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment'); // Attach local plugin stucture to enrol element. $this->add_plugin_structure('enrol', $enrol); return array($enrol, $enrolment); } /** * Create enrolment instances. * * This has to be called after creation of roles * and before adding of role assignments. * * @param mixed $data * @return void */ public function process_enrol($data) { global $DB; $data = (object)$data; $oldid = $data->id; // We'll need this later. unset($data->id); $this->originalstatus[$oldid] = $data->status; if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) { $this->set_mapping('enrol', $oldid, 0); return; } if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if (!$this->enrolsynced) { // Make sure that all plugin may create instances and enrolments automatically // before the first instance restore - this is suitable especially for plugins // that synchronise data automatically using course->idnumber or by course categories. foreach ($this->plugins as $plugin) { $plugin->restore_sync_course($courserec); } $this->enrolsynced = true; } // Map standard fields - plugin has to process custom fields manually. $data->roleid = $this->get_mappingid('role', $data->roleid); $data->courseid = $courserec->id; if ($this->get_setting_value('enrol_migratetomanual')) { unset($data->sortorder); // Remove useless sortorder from <2.4 backups. if (!enrol_is_enabled('manual')) { $this->set_mapping('enrol', $oldid, 0); return; } if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) { $instance = reset($instances); $this->set_mapping('enrol', $oldid, $instance->id); } else { if ($data->enrol === 'manual') { $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data); } else { $instanceid = $this->plugins['manual']->add_default_instance($courserec); } $this->set_mapping('enrol', $oldid, $instanceid); } } else { if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) { $this->set_mapping('enrol', $oldid, 0); $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments"; $this->log($message, backup::LOG_WARNING); return; } if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) { // Let's keep the sortorder in old backups. } else { // Prevent problems with colliding sortorders in old backups, // new 2.4 backups do not need sortorder because xml elements are ordered properly. unset($data->sortorder); } // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type. $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid); } } /** * Create user enrolments. * * This has to be called after creation of enrolment instances * and before adding of role assignments. * * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards. * * @param mixed $data * @return void */ public function process_enrolment($data) { global $DB; if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } $data = (object)$data; // Process only if parent instance have been mapped. if ($enrolid = $this->get_new_parentid('enrol')) { $oldinstancestatus = ENROL_INSTANCE_ENABLED; $oldenrolid = $this->get_old_parentid('enrol'); if (isset($this->originalstatus[$oldenrolid])) { $oldinstancestatus = $this->originalstatus[$oldenrolid]; } if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { // And only if user is a mapped one. if ($userid = $this->get_mappingid('user', $data->userid)) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus); } } } } } } /** * Make sure the user restoring the course can actually access it. */ class restore_fix_restorer_access_step extends restore_execution_step { protected function define_execution() { global $CFG, $DB; if (!$userid = $this->task->get_userid()) { return; } if (empty($CFG->restorernewroleid)) { // Bad luck, no fallback role for restorers specified return; } $courseid = $this->get_courseid(); $context = context_course::instance($courseid); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Current user may access the course (admin, category manager or restored teacher enrolment usually) return; } // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled role_assign($CFG->restorernewroleid, $userid, $context); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Extra role is enough, yay! return; } // The last chance is to create manual enrol if it does not exist and and try to enrol the current user, // hopefully admin selected suitable $CFG->restorernewroleid ... if (!enrol_is_enabled('manual')) { return; } if (!$enrol = enrol_get_plugin('manual')) { return; } if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) { $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0)); $enrol->add_instance($course, $fields); } enrol_try_internal_enrol($courseid, $userid); } } /** * This structure steps restores the filters and their configs */ class restore_filters_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active'); $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config'); return $paths; } public function process_active($data) { $data = (object)$data; if (strpos($data->filter, 'filter/') === 0) { $data->filter = substr($data->filter, 7); } else if (strpos($data->filter, '/') !== false) { // Unsupported old filter. return; } if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do return; } filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active); } public function process_config($data) { $data = (object)$data; if (strpos($data->filter, 'filter/') === 0) { $data->filter = substr($data->filter, 7); } else if (strpos($data->filter, '/') !== false) { // Unsupported old filter. return; } if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do return; } filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value); } } /** * This structure steps restores the comments * Note: Cannot use the comments API because defaults to USER->id. * That should change allowing to pass $userid */ class restore_comments_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('comment', '/comments/comment'); return $paths; } public function process_comment($data) { global $DB; $data = (object)$data; // First of all, if the comment has some itemid, ask to the task what to map $mapping = false; if ($data->itemid) { $mapping = $this->task->get_comment_mapping_itemname($data->commentarea); $data->itemid = $this->get_mappingid($mapping, $data->itemid); } // Only restore the comment if has no mapping OR we have found the matching mapping if (!$mapping || $data->itemid) { // Only if user mapping and context $data->userid = $this->get_mappingid('user', $data->userid); if ($data->userid && $this->task->get_contextid()) { $data->contextid = $this->task->get_contextid(); // Only if there is another comment with same context/user/timecreated $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated); if (!$DB->record_exists('comments', $params)) { $DB->insert_record('comments', $data); } } } } } /** * This structure steps restores the badges and their configs */ class restore_badges_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks the following parameters: * * 1. Badges and course badges are enabled on the site. * 2. The course/badges.xml file exists. * 3. All modules are restorable. * 4. All modules are marked for restore. * * @return bool True is safe to execute, false otherwise */ protected function execute_condition() { global $CFG; // First check is badges and course level badges are enabled on this site. if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) { // Disabled, don't restore course badges. return false; } // Check if badges.xml is included in the backup. $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course badges. return false; } // Check we are able to restore all backed up modules. if ($this->task->is_missing_modules()) { return false; } // Finally check all modules within the backup are being restored. if ($this->task->is_excluding_activities()) { return false; } return true; } protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('badge', '/badges/badge'); $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion'); $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter'); $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award'); return $paths; } public function process_badge($data) { global $DB, $CFG; require_once($CFG->libdir . '/badgeslib.php'); $data = (object)$data; $data->usercreated = $this->get_mappingid('user', $data->usercreated); if (empty($data->usercreated)) { $data->usercreated = $this->task->get_userid(); } $data->usermodified = $this->get_mappingid('user', $data->usermodified); if (empty($data->usermodified)) { $data->usermodified = $this->task->get_userid(); } // We'll restore the badge image. $restorefiles = true; $courseid = $this->get_courseid(); $params = array( 'name' => $data->name, 'description' => $data->description, 'timecreated' => $this->apply_date_offset($data->timecreated), 'timemodified' => $this->apply_date_offset($data->timemodified), 'usercreated' => $data->usercreated, 'usermodified' => $data->usermodified, 'issuername' => $data->issuername, 'issuerurl' => $data->issuerurl, 'issuercontact' => $data->issuercontact, 'expiredate' => $this->apply_date_offset($data->expiredate), 'expireperiod' => $data->expireperiod, 'type' => BADGE_TYPE_COURSE, 'courseid' => $courseid, 'message' => $data->message, 'messagesubject' => $data->messagesubject, 'attachment' => $data->attachment, 'notification' => $data->notification, 'status' => BADGE_STATUS_INACTIVE, 'nextcron' => $this->apply_date_offset($data->nextcron) ); $newid = $DB->insert_record('badge', $params); $this->set_mapping('badge', $data->id, $newid, $restorefiles); } public function process_criterion($data) { global $DB; $data = (object)$data; $params = array( 'badgeid' => $this->get_new_parentid('badge'), 'criteriatype' => $data->criteriatype, 'method' => $data->method ); $newid = $DB->insert_record('badge_criteria', $params); $this->set_mapping('criterion', $data->id, $newid); } public function process_parameter($data) { global $DB, $CFG; require_once($CFG->libdir . '/badgeslib.php'); $data = (object)$data; $criteriaid = $this->get_new_parentid('criterion'); // Parameter array that will go to database. $params = array(); $params['critid'] = $criteriaid; $oldparam = explode('_', $data->name); if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) { $module = $this->get_mappingid('course_module', $oldparam[1]); $params['name'] = $oldparam[0] . '_' . $module; $params['value'] = $oldparam[0] == 'module' ? $module : $data->value; } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) { $params['name'] = $oldparam[0] . '_' . $this->get_courseid(); $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value; } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) { $role = $this->get_mappingid('role', $data->value); if (!empty($role)) { $params['name'] = 'role_' . $role; $params['value'] = $role; } else { return; } } if (!$DB->record_exists('badge_criteria_param', $params)) { $DB->insert_record('badge_criteria_param', $params); } } public function process_manual_award($data) { global $DB; $data = (object)$data; $role = $this->get_mappingid('role', $data->issuerrole); if (!empty($role)) { $award = array( 'badgeid' => $this->get_new_parentid('badge'), 'recipientid' => $this->get_mappingid('user', $data->recipientid), 'issuerid' => $this->get_mappingid('user', $data->issuerid), 'issuerrole' => $role, 'datemet' => $this->apply_date_offset($data->datemet) ); // Skip the manual award if recipient or issuer can not be mapped to. if (empty($award['recipientid']) || empty($award['issuerid'])) { return; } $DB->insert_record('badge_manual_award', $award); } } protected function after_execute() { // Add related files. $this->add_related_files('badges', 'badgeimage', 'badge'); } } /** * This structure steps restores the calendar events */ class restore_calendarevents_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('calendarevents', '/events/event'); return $paths; } public function process_calendarevents($data) { global $DB, $SITE, $USER; $data = (object)$data; $oldid = $data->id; $restorefiles = true; // We'll restore the files // Find the userid and the groupid associated with the event. $data->userid = $this->get_mappingid('user', $data->userid); if ($data->userid === false) { // Blank user ID means that we are dealing with module generated events such as quiz starting times. // Use the current user ID for these events. $data->userid = $USER->id; } if (!empty($data->groupid)) { $data->groupid = $this->get_mappingid('group', $data->groupid); if ($data->groupid === false) { return; } } // Handle events with empty eventtype //MDL-32827 if(empty($data->eventtype)) { if ($data->courseid == $SITE->id) { // Site event $data->eventtype = "site"; } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) { // Course assingment event $data->eventtype = "due"; } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event $data->eventtype = "course"; } else if ($data->groupid) { // Group event $data->eventtype = "group"; } else if ($data->userid) { // User event $data->eventtype = "user"; } else { return; } } $params = array( 'name' => $data->name, 'description' => $data->description, 'format' => $data->format, 'courseid' => $this->get_courseid(), 'groupid' => $data->groupid, 'userid' => $data->userid, 'repeatid' => $data->repeatid, 'modulename' => $data->modulename, 'eventtype' => $data->eventtype, 'timestart' => $this->apply_date_offset($data->timestart), 'timeduration' => $data->timeduration, 'visible' => $data->visible, 'uuid' => $data->uuid, 'sequence' => $data->sequence, 'timemodified' => $this->apply_date_offset($data->timemodified)); if ($this->name == 'activity_calendar') { $params['instance'] = $this->task->get_activityid(); } else { $params['instance'] = 0; } $sql = "SELECT id FROM {event} WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . " AND courseid = ? AND repeatid = ? AND modulename = ? AND timestart = ? AND timeduration = ? AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255); $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']); $result = $DB->record_exists_sql($sql, $arg); if (empty($result)) { $newitemid = $DB->insert_record('event', $params); $this->set_mapping('event', $oldid, $newitemid); $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles); } } protected function after_execute() { // Add related files $this->add_related_files('calendar', 'event_description', 'event_description'); } } class restore_course_completion_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks parameters that are not immediate settings to ensure * that the enviroment is suitable for the restore of course completion info. * * This function checks the following four parameters: * * 1. Course completion is enabled on the site * 2. The backup includes course completion information * 3. All modules are restorable * 4. All modules are marked for restore. * * @return bool True is safe to execute, false otherwise */ protected function execute_condition() { global $CFG; // First check course completion is enabled on this site if (empty($CFG->enablecompletion)) { // Disabled, don't restore course completion return false; } // No course completion on the front page. if ($this->get_courseid() == SITEID) { return false; } // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course completion return false; } // Check we are able to restore all backed up modules if ($this->task->is_missing_modules()) { return false; } // Finally check all modules within the backup are being restored. if ($this->task->is_excluding_activities()) { return false; } return true; } /** * Define the course completion structure * * @return array Array of restore_path_element */ protected function define_structure() { // To know if we are including user completion info $userinfo = $this->get_setting_value('userscompletion'); $paths = array(); $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria'); $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd'); if ($userinfo) { $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl'); $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions'); } return $paths; } /** * Process course completion criteria * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_criteria($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); // Apply the date offset to the time end field $data->timeend = $this->apply_date_offset($data->timeend); // Map the role from the criteria if (!empty($data->role)) { $data->role = $this->get_mappingid('role', $data->role); } $skipcriteria = false; // If the completion criteria is for a module we need to map the module instance // to the new module id. if (!empty($data->moduleinstance) && !empty($data->module)) { $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance); if (empty($data->moduleinstance)) { $skipcriteria = true; } } else { $data->module = null; $data->moduleinstance = null; } // We backup the course shortname rather than the ID so that we can match back to the course if (!empty($data->courseinstanceshortname)) { $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname)); if (!$courseinstanceid) { $skipcriteria = true; } } else { $courseinstanceid = null; } $data->courseinstance = $courseinstanceid; if (!$skipcriteria) { $params = array( 'course' => $data->course, 'criteriatype' => $data->criteriatype, 'enrolperiod' => $data->enrolperiod, 'courseinstance' => $data->courseinstance, 'module' => $data->module, 'moduleinstance' => $data->moduleinstance, 'timeend' => $data->timeend, 'gradepass' => $data->gradepass, 'role' => $data->role ); $newid = $DB->insert_record('course_completion_criteria', $params); $this->set_mapping('course_completion_criteria', $data->id, $newid); } } /** * Processes course compltion criteria complete records * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_crit_compl($data) { global $DB; $data = (object)$data; // This may be empty if criteria could not be restored $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid); $data->course = $this->get_courseid(); $data->userid = $this->get_mappingid('user', $data->userid); if (!empty($data->criteriaid) && !empty($data->userid)) { $params = array( 'userid' => $data->userid, 'course' => $data->course, 'criteriaid' => $data->criteriaid, 'timecompleted' => $this->apply_date_offset($data->timecompleted) ); if (isset($data->gradefinal)) { $params['gradefinal'] = $data->gradefinal; } if (isset($data->unenroled)) { $params['unenroled'] = $data->unenroled; } $DB->insert_record('course_completion_crit_compl', $params); } } /** * Process course completions * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completions($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); $data->userid = $this->get_mappingid('user', $data->userid); if (!empty($data->userid)) { $params = array( 'userid' => $data->userid, 'course' => $data->course, 'timeenrolled' => $this->apply_date_offset($data->timeenrolled), 'timestarted' => $this->apply_date_offset($data->timestarted), 'timecompleted' => $this->apply_date_offset($data->timecompleted), 'reaggregate' => $data->reaggregate ); $existing = $DB->get_record('course_completions', array( 'userid' => $data->userid, 'course' => $data->course )); // MDL-46651 - If cron writes out a new record before we get to it // then we should replace it with the Truth data from the backup. // This may be obsolete after MDL-48518 is resolved if ($existing) { $params['id'] = $existing->id; $DB->update_record('course_completions', $params); } else { $DB->insert_record('course_completions', $params); } } } /** * Process course completion aggregate methods * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_aggr_methd($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); // Only create the course_completion_aggr_methd records if // the target course has not them defined. MDL-28180 if (!$DB->record_exists('course_completion_aggr_methd', array( 'course' => $data->course, 'criteriatype' => $data->criteriatype))) { $params = array( 'course' => $data->course, 'criteriatype' => $data->criteriatype, 'method' => $data->method, 'value' => $data->value, ); $DB->insert_record('course_completion_aggr_methd', $params); } } } /** * This structure step restores course logs (cmid = 0), delegating * the hard work to the corresponding {@link restore_logs_processor} passing the * collection of {@link restore_log_rule} rules to be observed as they are defined * by the task. Note this is only executed based in the 'logs' setting. * * NOTE: This is executed by final task, to have all the activities already restored * * NOTE: Not all course logs are being restored. For now only 'course' and 'user' * records are. There are others like 'calendar' and 'upload' that will be handled * later. * * NOTE: All the missing actions (not able to be restored) are sent to logs for * debugging purposes */ class restore_course_logs_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks the following parameter: * * 1. the course/logs.xml file exists * * @return bool true is safe to execute, false otherwise */ protected function execute_condition() { // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course logs return false; } return true; } protected function define_structure() { $paths = array(); // Simple, one plain level of information contains them $paths[] = new restore_path_element('log', '/logs/log'); return $paths; } protected function process_log($data) { global $DB; $data = (object)($data); $data->time = $this->apply_date_offset($data->time); $data->userid = $this->get_mappingid('user', $data->userid); $data->course = $this->get_courseid(); $data->cmid = 0; // For any reason user wasn't remapped ok, stop processing this if (empty($data->userid)) { return; } // Everything ready, let's delegate to the restore_logs_processor // Set some fixed values that will save tons of DB requests $values = array( 'course' => $this->get_courseid()); // Get instance and process log record $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); // If we have data, insert it, else something went wrong in the restore_logs_processor if ($data) { if (empty($data->url)) { $data->url = ''; } if (empty($data->info)) { $data->info = ''; } // Store the data in the legacy log table if we are still using it. $manager = get_log_manager(); if (method_exists($manager, 'legacy_add_to_log')) { $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, $data->info, $data->cmid, $data->userid); } } } } /** * This structure step restores activity logs, extending {@link restore_course_logs_structure_step} * sharing its same structure but modifying the way records are handled */ class restore_activity_logs_structure_step extends restore_course_logs_structure_step { protected function process_log($data) { global $DB; $data = (object)($data); $data->time = $this->apply_date_offset($data->time); $data->userid = $this->get_mappingid('user', $data->userid); $data->course = $this->get_courseid(); $data->cmid = $this->task->get_moduleid(); // For any reason user wasn't remapped ok, stop processing this if (empty($data->userid)) { return; } // Everything ready, let's delegate to the restore_logs_processor // Set some fixed values that will save tons of DB requests $values = array( 'course' => $this->get_courseid(), 'course_module' => $this->task->get_moduleid(), $this->task->get_modulename() => $this->task->get_activityid()); // Get instance and process log record $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); // If we have data, insert it, else something went wrong in the restore_logs_processor if ($data) { if (empty($data->url)) { $data->url = ''; } if (empty($data->info)) { $data->info = ''; } // Store the data in the legacy log table if we are still using it. $manager = get_log_manager(); if (method_exists($manager, 'legacy_add_to_log')) { $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, $data->info, $data->cmid, $data->userid); } } } } /** * Defines the restore step for advanced grading methods attached to the activity module */ class restore_activity_grading_structure_step extends restore_structure_step { /** * This step is executed only if the grading file is present */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } return true; } /** * Declares paths in the grading.xml file we are interested in */ protected function define_structure() { $paths = array(); $userinfo = $this->get_setting_value('userinfo'); $area = new restore_path_element('grading_area', '/areas/area'); $paths[] = $area; // attach local plugin stucture to $area element $this->add_plugin_structure('local', $area); $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition'); $paths[] = $definition; $this->add_plugin_structure('gradingform', $definition); // attach local plugin stucture to $definition element $this->add_plugin_structure('local', $definition); if ($userinfo) { $instance = new restore_path_element('grading_instance', '/areas/area/definitions/definition/instances/instance'); $paths[] = $instance; $this->add_plugin_structure('gradingform', $instance); // attach local plugin stucture to $intance element $this->add_plugin_structure('local', $instance); } return $paths; } /** * Processes one grading area element * * @param array $data element data */ protected function process_grading_area($data) { global $DB; $task = $this->get_task(); $data = (object)$data; $oldid = $data->id; $data->component = 'mod_'.$task->get_modulename(); $data->contextid = $task->get_contextid(); $newid = $DB->insert_record('grading_areas', $data); $this->set_mapping('grading_area', $oldid, $newid); } /** * Processes one grading definition element * * @param array $data element data */ protected function process_grading_definition($data) { global $DB; $task = $this->get_task(); $data = (object)$data; $oldid = $data->id; $data->areaid = $this->get_new_parentid('grading_area'); $data->copiedfromid = null; $data->timecreated = time(); $data->usercreated = $task->get_userid(); $data->timemodified = $data->timecreated; $data->usermodified = $data->usercreated; $newid = $DB->insert_record('grading_definitions', $data); $this->set_mapping('grading_definition', $oldid, $newid, true); } /** * Processes one grading form instance element * * @param array $data element data */ protected function process_grading_instance($data) { global $DB; $data = (object)$data; // new form definition id $newformid = $this->get_new_parentid('grading_definition'); // get the name of the area we are restoring to $sql = "SELECT ga.areaname FROM {grading_definitions} gd JOIN {grading_areas} ga ON gd.areaid = ga.id WHERE gd.id = ?"; $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST); // get the mapped itemid - the activity module is expected to define the mappings // for each gradable area $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid); $oldid = $data->id; $data->definitionid = $newformid; $data->raterid = $this->get_mappingid('user', $data->raterid); $data->itemid = $newitemid; $newid = $DB->insert_record('grading_instances', $data); $this->set_mapping('grading_instance', $oldid, $newid); } /** * Final operations when the database records are inserted */ protected function after_execute() { // Add files embedded into the definition description $this->add_related_files('grading', 'description', 'grading_definition'); } } /** * This structure step restores the grade items associated with one activity * All the grade items are made child of the "course" grade item but the original * categoryid is saved as parentitemid in the backup_ids table, so, when restoring * the complete gradebook (categories and calculations), that information is * available there */ class restore_activity_grades_structure_step extends restore_structure_step { /** * No grades in front page. * @return bool */ protected function execute_condition() { return ($this->get_courseid() != SITEID); } protected function define_structure() { $paths = array(); $userinfo = $this->get_setting_value('userinfo'); $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item'); $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter'); if ($userinfo) { $paths[] = new restore_path_element('grade_grade', '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade'); } return $paths; } protected function process_grade_item($data) { global $DB; $data = (object)($data); $oldid = $data->id; // We'll need these later $oldparentid = $data->categoryid; $courseid = $this->get_courseid(); // make sure top course category exists, all grade items will be associated // to it. Later, if restoring the whole gradebook, categories will be introduced $coursecat = grade_category::fetch_course_category($courseid); $coursecatid = $coursecat->id; // Get the categoryid to be used $idnumber = null; if (!empty($data->idnumber)) { // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop) // so the best is to keep the ones already in the gradebook // Potential problem: duplicates if same items are restored more than once. :-( // This needs to be fixed in some way (outcomes & activities with multiple items) // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber; // In any case, verify always for uniqueness $sql = "SELECT cm.id FROM {course_modules} cm WHERE cm.course = :courseid AND cm.idnumber = :idnumber AND cm.id <> :cmid"; $params = array( 'courseid' => $courseid, 'idnumber' => $data->idnumber, 'cmid' => $this->task->get_moduleid() ); if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) { $idnumber = $data->idnumber; } } unset($data->id); $data->categoryid = $coursecatid; $data->courseid = $this->get_courseid(); $data->iteminstance = $this->task->get_activityid(); $data->idnumber = $idnumber; $data->scaleid = $this->get_mappingid('scale', $data->scaleid); $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $gradeitem = new grade_item($data, false); $gradeitem->insert('restore'); //sortorder is automatically assigned when inserting. Re-instate the previous sortorder $gradeitem->sortorder = $data->sortorder; $gradeitem->update('restore'); // Set mapping, saving the original category id into parentitemid // gradebook restore (final task) will need it to reorganise items $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid); } protected function process_grade_grade($data) { $data = (object)($data); $olduserid = $data->userid; $oldid = $data->id; unset($data->id); $data->itemid = $this->get_new_parentid('grade_item'); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled? $data->overridden = $this->apply_date_offset($data->overridden); $grade = new grade_grade($data, false); $grade->insert('restore'); $this->set_mapping('grade_grades', $oldid, $grade->id); } else { debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"); } } /** * process activity grade_letters. Note that, while these are possible, * because grade_letters are contextid based, in practice, only course * context letters can be defined. So we keep here this method knowing * it won't be executed ever. gradebook restore will restore course letters. */ protected function process_grade_letter($data) { global $DB; $data['contextid'] = $this->task->get_contextid(); $gradeletter = (object)$data; // Check if it exists before adding it unset($data['id']); if (!$DB->record_exists('grade_letters', $data)) { $newitemid = $DB->insert_record('grade_letters', $gradeletter); } // no need to save any grade_letter mapping } public function after_restore() { // Fix grade item's sortorder after restore, as it might have duplicates. $courseid = $this->get_task()->get_courseid(); grade_item::fix_duplicate_sortorder($courseid); } } /** * Step in charge of restoring the grade history of an activity. * * This step is added to the task regardless of the setting 'grade_histories'. * The reason is to allow for a more flexible step in case the logic needs to be * split accross different settings to control the history of items and/or grades. */ class restore_activity_grade_history_structure_step extends restore_structure_step { /** * This step is executed only if the grade history file is present. */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } return true; } protected function define_structure() { $paths = array(); // Settings to use. $userinfo = $this->get_setting_value('userinfo'); $history = $this->get_setting_value('grade_histories'); if ($userinfo && $history) { $paths[] = new restore_path_element('grade_grade', '/grade_history/grade_grades/grade_grade'); } return $paths; } protected function process_grade_grade($data) { global $DB; $data = (object) $data; $olduserid = $data->userid; unset($data->id); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { // Do not apply the date offsets as this is history. $data->itemid = $this->get_mappingid('grade_item', $data->itemid); $data->oldid = $this->get_mappingid('grade_grades', $data->oldid); $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); $DB->insert_record('grade_grades_history', $data); } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } } /** * This structure steps restores one instance + positions of one block * Note: Positions corresponding to one existing context are restored * here, but all the ones having unknown contexts are sent to backup_ids * for a later chance to be restored at the end (final task) */ class restore_block_instance_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position'); return $paths; } public function process_block($data) { global $DB, $CFG; $data = (object)$data; // Handy $oldcontextid = $data->contextid; $oldid = $data->id; $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array(); // Look for the parent contextid if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) { throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid); } // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple() // If there is already one block of that type in the parent context // and the block is not multiple, stop processing // Use blockslib loader / method executor if (!$bi = block_instance($data->blockname)) { return false; } if (!$bi->instance_allow_multiple()) { // The block cannot be added twice, so we will check if the same block is already being // displayed on the same page. For this, rather than mocking a page and using the block_manager // we use a similar query to the one in block_manager::load_blocks(), this will give us // a very good idea of the blocks already displayed in the context. $params = array( 'blockname' => $data->blockname ); // Context matching test. $context = context::instance_by_id($data->parentcontextid); $contextsql = 'bi.parentcontextid = :contextid'; $params['contextid'] = $context->id; $parentcontextids = $context->get_parent_context_ids(); if ($parentcontextids) { list($parentcontextsql, $parentcontextparams) = $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED); $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))"; $params = array_merge($params, $parentcontextparams); } // Page type pattern test. $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern); list($pagetypepatternsql, $pagetypepatternparams) = $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED); $params = array_merge($params, $pagetypepatternparams); // Sub page pattern test. $subpagepatternsql = 'bi.subpagepattern IS NULL'; if ($data->subpagepattern !== null) { $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)"; $params['subpagepattern'] = $data->subpagepattern; } $exists = $DB->record_exists_sql("SELECT bi.id FROM {block_instances} bi JOIN {block} b ON b.name = bi.blockname WHERE bi.blockname = :blockname AND $contextsql AND bi.pagetypepattern $pagetypepatternsql AND $subpagepatternsql", $params); if ($exists) { // There is at least one very similar block visible on the page where we // are trying to restore the block. In these circumstances the block API // would not allow the user to add another instance of the block, so we // apply the same rule here. return false; } } // If there is already one block of that type in the parent context // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata // stop processing $params = array( 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid, 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern, 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion); if ($birecs = $DB->get_records('block_instances', $params)) { foreach($birecs as $birec) { if ($birec->configdata == $data->configdata) { return false; } } } // Set task old contextid, blockid and blockname once we know them $this->task->set_old_contextid($oldcontextid); $this->task->set_old_blockid($oldid); $this->task->set_blockname($data->blockname); // Let's look for anything within configdata neededing processing // (nulls and uses of legacy file.php) if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) { $configdata = (array)unserialize(base64_decode($data->configdata)); foreach ($configdata as $attribute => $value) { if (in_array($attribute, $attrstotransform)) { $configdata[$attribute] = $this->contentprocessor->process_cdata($value); } } $data->configdata = base64_encode(serialize((object)$configdata)); } // Create the block instance $newitemid = $DB->insert_record('block_instances', $data); // Save the mapping (with restorefiles support) $this->set_mapping('block_instance', $oldid, $newitemid, true); // Create the block context $newcontextid = context_block::instance($newitemid)->id; // Save the block contexts mapping and sent it to task $this->set_mapping('context', $oldcontextid, $newcontextid); $this->task->set_contextid($newcontextid); $this->task->set_blockid($newitemid); // Restore block fileareas if declared $component = 'block_' . $this->task->get_blockname(); foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed $this->add_related_files($component, $filearea, null); } // Process block positions, creating them or accumulating for final step foreach($positions as $position) { $position = (object)$position; $position->blockinstanceid = $newitemid; // The instance is always the restored one // If position is for one already mapped (known) contextid // process it now, creating the position if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) { $position->contextid = $newpositionctxid; // Create the block position $DB->insert_record('block_positions', $position); // The position belongs to an unknown context, send it to backup_ids // to process them as part of the final steps of restore. We send the // whole $position object there, hence use the low level method. } else { restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position); } } } } /** * Structure step to restore common course_module information * * This step will process the module.xml file for one activity, in order to restore * the corresponding information to the course_modules table, skipping various bits * of information based on CFG settings (groupings, completion...) in order to fullfill * all the reqs to be able to create the context to be used by all the rest of steps * in the activity restore task */ class restore_module_structure_step extends restore_structure_step { protected function define_structure() { global $CFG; $paths = array(); $module = new restore_path_element('module', '/module'); $paths[] = $module; if ($CFG->enableavailability) { $paths[] = new restore_path_element('availability', '/module/availability_info/availability'); $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field'); } // Apply for 'format' plugins optional paths at module level $this->add_plugin_structure('format', $module); // Apply for 'plagiarism' plugins optional paths at module level $this->add_plugin_structure('plagiarism', $module); // Apply for 'local' plugins optional paths at module level $this->add_plugin_structure('local', $module); return $paths; } protected function process_module($data) { global $CFG, $DB; $data = (object)$data; $oldid = $data->id; $this->task->set_old_moduleversion($data->version); $data->course = $this->task->get_courseid(); $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename)); // Map section (first try by course_section mapping match. Useful in course and section restores) $data->section = $this->get_mappingid('course_section', $data->sectionid); if (!$data->section) { // mapping failed, try to get section by sectionnumber matching $params = array( 'course' => $this->get_courseid(), 'section' => $data->sectionnumber); $data->section = $DB->get_field('course_sections', 'id', $params); } if (!$data->section) { // sectionnumber failed, try to get first section in course $params = array( 'course' => $this->get_courseid()); $data->section = $DB->get_field('course_sections', 'MIN(id)', $params); } if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1 $sectionrec = array( 'course' => $this->get_courseid(), 'section' => 0); $DB->insert_record('course_sections', $sectionrec); // section 0 $sectionrec = array( 'course' => $this->get_courseid(), 'section' => 1); $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1 } $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness $data->idnumber = ''; } if (empty($CFG->enablecompletion)) { // completion $data->completion = 0; $data->completiongradeitemnumber = null; $data->completionview = 0; $data->completionexpected = 0; } else { $data->completionexpected = $this->apply_date_offset($data->completionexpected); } if (empty($CFG->enableavailability)) { $data->availability = null; } // Backups that did not include showdescription, set it to default 0 // (this is not totally necessary as it has a db default, but just to // be explicit). if (!isset($data->showdescription)) { $data->showdescription = 0; } $data->instance = 0; // Set to 0 for now, going to create it soon (next step) if (empty($data->availability)) { // If there are legacy availablility data fields (and no new format data), // convert the old fields. $data->availability = \core_availability\info::convert_legacy_fields( $data, false); } else if (!empty($data->groupmembersonly)) { // There is current availability data, but it still has groupmembersonly // as well (2.7 backups), convert just that part. require_once($CFG->dirroot . '/lib/db/upgradelib.php'); $data->availability = upgrade_group_members_only($data->groupingid, $data->availability); } // course_module record ready, insert it $newitemid = $DB->insert_record('course_modules', $data); // save mapping $this->set_mapping('course_module', $oldid, $newitemid); // set the new course_module id in the task $this->task->set_moduleid($newitemid); // we can now create the context safely $ctxid = context_module::instance($newitemid)->id; // set the new context id in the task $this->task->set_contextid($ctxid); // update sequence field in course_section if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) { $sequence .= ',' . $newitemid; } else { $sequence = $newitemid; } $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section)); // If there is the legacy showavailability data, store this for later use. // (This data is not present when restoring 'new' backups.) if (isset($data->showavailability)) { // Cache the showavailability flag using the backup_ids data field. restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_showavailability', $newitemid, 0, null, (object)array('showavailability' => $data->showavailability)); } } /** * Process the legacy availability table record. This table does not exist * in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ protected function process_availability($data) { $data = (object)$data; // Simply going to store the whole availability record now, we'll process // all them later in the final task (once all activities have been restored) // Let's call the low level one to be able to store the whole object $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data); } /** * Process the legacy availability fields table record. This table does not * exist in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ protected function process_availability_field($data) { global $DB; $data = (object)$data; // Mark it is as passed by default $passed = true; $customfieldid = null; // If a customfield has been used in order to pass we must be able to match an existing // customfield by name (data->customfield) and type (data->customfieldtype) if (!empty($data->customfield) xor !empty($data->customfieldtype)) { // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both. // If one is null but the other isn't something clearly went wrong and we'll skip this condition. $passed = false; } else if (!empty($data->customfield)) { $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype); $customfieldid = $DB->get_field('user_info_field', 'id', $params); $passed = ($customfieldid !== false); } if ($passed) { // Create the object to insert into the database $availfield = new stdClass(); $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid $availfield->userfield = $data->userfield; $availfield->customfieldid = $customfieldid; $availfield->operator = $data->operator; $availfield->value = $data->value; // Get showavailability option. $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_showavailability', $availfield->coursemoduleid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availfieldobject is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_modules', 'availability', array('id' => $availfield->coursemoduleid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_field_condition( $currentvalue, $availfield, $show); $DB->set_field('course_modules', 'availability', $newvalue, array('id' => $availfield->coursemoduleid)); } } } /** * Structure step that will process the user activity completion * information if all these conditions are met: * - Target site has completion enabled ($CFG->enablecompletion) * - Activity includes completion info (file_exists) */ class restore_userscompletion_structure_step extends restore_structure_step { /** * To conditionally decide if this step must be executed * Note the "settings" conditions are evaluated in the * corresponding task. Here we check for other conditions * not being restore settings (files, site settings...) */ protected function execute_condition() { global $CFG; // Completion disabled in this site, don't execute if (empty($CFG->enablecompletion)) { return false; } // No completion on the front page. if ($this->get_courseid() == SITEID) { return false; } // No user completion info found, don't execute $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Arrived here, execute the step return true; } protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('completion', '/completions/completion'); return $paths; } protected function process_completion($data) { global $DB; $data = (object)$data; $data->coursemoduleid = $this->task->get_moduleid(); $data->userid = $this->get_mappingid('user', $data->userid); $data->timemodified = $this->apply_date_offset($data->timemodified); // Find the existing record $existing = $DB->get_record('course_modules_completion', array( 'coursemoduleid' => $data->coursemoduleid, 'userid' => $data->userid), 'id, timemodified'); // Check we didn't already insert one for this cmid and userid // (there aren't supposed to be duplicates in that field, but // it was possible until MDL-28021 was fixed). if ($existing) { // Update it to these new values, but only if the time is newer if ($existing->timemodified < $data->timemodified) { $data->id = $existing->id; $DB->update_record('course_modules_completion', $data); } } else { // Normal entry where it doesn't exist already $DB->insert_record('course_modules_completion', $data); } } } /** * Abstract structure step, parent of all the activity structure steps. Used to suuport * the main <activity ...> tag and process it. Also provides subplugin support for * activities. */ abstract class restore_activity_structure_step extends restore_structure_step { protected function add_subplugin_structure($subplugintype, $element) { global $CFG; // Check the requested subplugintype is a valid one $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php'; if (!file_exists($subpluginsfile)) { throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename()); } include($subpluginsfile); if (!array_key_exists($subplugintype, $subplugins)) { throw new restore_step_exception('incorrect_subplugin_type', $subplugintype); } // Get all the restore path elements, looking across all the subplugin dirs $subpluginsdirs = core_component::get_plugin_list($subplugintype); foreach ($subpluginsdirs as $name => $subpluginsdir) { $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin'; $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php'; if (file_exists($restorefile)) { require_once($restorefile); $restoresubplugin = new $classname($subplugintype, $name, $this); // Add subplugin paths to the step $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element)); } } } /** * As far as activity restore steps are implementing restore_subplugin stuff, they need to * have the parent task available for wrapping purposes (get course/context....) * @return restore_task */ public function get_task() { return $this->task; } /** * Adds support for the 'activity' path that is common to all the activities * and will be processed globally here */ protected function prepare_activity_structure($paths) { $paths[] = new restore_path_element('activity', '/activity'); return $paths; } /** * Process the activity path, informing the task about various ids, needed later */ protected function process_activity($data) { $data = (object)$data; $this->task->set_old_contextid($data->contextid); // Save old contextid in task $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping $this->task->set_old_activityid($data->id); // Save old activityid in task } /** * This must be invoked immediately after creating the "module" activity record (forum, choice...) * and will adjust the new activity id (the instance) in various places */ protected function apply_activity_instance($newitemid) { global $DB; $this->task->set_activityid($newitemid); // Save activity id in task // Apply the id to course_sections->instanceid $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid())); // Do the mapping for modulename, preparing it for files by oldcontext $modulename = $this->task->get_modulename(); $oldid = $this->task->get_old_activityid(); $this->set_mapping($modulename, $oldid, $newitemid, true); } } /** * Structure step in charge of creating/mapping all the qcats and qs * by parsing the questions.xml file and checking it against the * results calculated by {@link restore_process_categories_and_questions} * and stored in backup_ids_temp */ class restore_create_categories_and_questions extends restore_structure_step { /** @var array $cachecategory store a question category */ protected $cachedcategory = null; protected function define_structure() { $category = new restore_path_element('question_category', '/question_categories/question_category'); $question = new restore_path_element('question', '/question_categories/question_category/questions/question'); $hint = new restore_path_element('question_hint', '/question_categories/question_category/questions/question/question_hints/question_hint'); $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag'); // Apply for 'qtype' plugins optional paths at question level $this->add_plugin_structure('qtype', $question); // Apply for 'local' plugins optional paths at question level $this->add_plugin_structure('local', $question); return array($category, $question, $hint, $tag); } protected function process_question_category($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Check we have one mapping for this category if (!$mapping = $this->get_mapping('question_category', $oldid)) { return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped } // Check we have to create the category (newitemid = 0) if ($mapping->newitemid) { return; // newitemid != 0, this category is going to be mapped. Nothing to do } // Arrived here, newitemid = 0, we need to create the category // we'll do it at parentitemid context, but for CONTEXT_MODULE // categories, that will be created at CONTEXT_COURSE and moved // to module context later when the activity is created if ($mapping->info->contextlevel == CONTEXT_MODULE) { $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid()); } $data->contextid = $mapping->parentitemid; // Let's create the question_category and save mapping $newitemid = $DB->insert_record('question_categories', $data); $this->set_mapping('question_category', $oldid, $newitemid); // Also annotate them as question_category_created, we need // that later when remapping parents $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid); } protected function process_question($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Check we have one mapping for this question if (!$questionmapping = $this->get_mapping('question', $oldid)) { return; // No mapping = this question doesn't need to be created/mapped } // Get the mapped category (cannot use get_new_parentid() because not // all the categories have been created, so it is not always available // Instead we get the mapping for the question->parentitemid because // we have loaded qcatids there for all parsed questions $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid); // In the past, there were some very sloppy values of penalty. Fix them. if ($data->penalty >= 0.33 && $data->penalty <= 0.34) { $data->penalty = 0.3333333; } if ($data->penalty >= 0.66 && $data->penalty <= 0.67) { $data->penalty = 0.6666667; } if ($data->penalty >= 1) { $data->penalty = 1; } $userid = $this->get_mappingid('user', $data->createdby); $data->createdby = $userid ? $userid : $this->task->get_userid(); $userid = $this->get_mappingid('user', $data->modifiedby); $data->modifiedby = $userid ? $userid : $this->task->get_userid(); // With newitemid = 0, let's create the question if (!$questionmapping->newitemid) { $newitemid = $DB->insert_record('question', $data); $this->set_mapping('question', $oldid, $newitemid); // Also annotate them as question_created, we need // that later when remapping parents (keeping the old categoryid as parentid) $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid); } else { // By performing this set_mapping() we make get_old/new_parentid() to work for all the // children elements of the 'question' one (so qtype plugins will know the question they belong to) $this->set_mapping('question', $oldid, $questionmapping->newitemid); } // Note, we don't restore any question files yet // as far as the CONTEXT_MODULE categories still // haven't their contexts to be restored to // The {@link restore_create_question_files}, executed in the final step // step will be in charge of restoring all the question files } protected function process_question_hint($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Detect if the question is created or mapped $oldquestionid = $this->get_old_parentid('question'); $newquestionid = $this->get_new_parentid('question'); $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false; // If the question has been created by restore, we need to create its question_answers too if ($questioncreated) { // Adjust some columns $data->questionid = $newquestionid; // Insert record $newitemid = $DB->insert_record('question_hints', $data); // The question existed, we need to map the existing question_hints } else { // Look in question_hints by hint text matching $sql = 'SELECT id FROM {question_hints} WHERE questionid = ? AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255); $params = array($newquestionid, $data->hint); $newitemid = $DB->get_field_sql($sql, $params); // Not able to find the hint, let's try cleaning the hint text // of all the question's hints in DB as slower fallback. MDL-33863. if (!$newitemid) { $potentialhints = $DB->get_records('question_hints', array('questionid' => $newquestionid), '', 'id, hint'); foreach ($potentialhints as $potentialhint) { // Clean in the same way than {@link xml_writer::xml_safe_utf8()}. $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars. $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending. if ($cleanhint === $data->hint) { $newitemid = $data->id; } } } // If we haven't found the newitemid, something has gone really wrong, question in DB // is missing hints, exception if (!$newitemid) { $info = new stdClass(); $info->filequestionid = $oldquestionid; $info->dbquestionid = $newquestionid; $info->hint = $data->hint; throw new restore_step_exception('error_question_hint_missing_in_db', $info); } } // Create mapping (I'm not sure if this is really needed?) $this->set_mapping('question_hint', $oldid, $newitemid); } protected function process_tag($data) { global $CFG, $DB; $data = (object)$data; $newquestion = $this->get_new_parentid('question'); if (!empty($CFG->usetags)) { // if enabled in server // TODO: This is highly inefficient. Each time we add one tag // we fetch all the existing because tag_set() deletes them // so everything must be reinserted on each call $tags = array(); $existingtags = tag_get_tags('question', $newquestion); // Re-add all the existitng tags foreach ($existingtags as $existingtag) { $tags[] = $existingtag->rawname; } // Add the one being restored $tags[] = $data->rawname; // Get the category, so we can then later get the context. $categoryid = $this->get_new_parentid('question_category'); if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) { $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid)); } // Send all the tags back to the question tag_set('question', $newquestion, $tags, 'core_question', $this->cachedcategory->contextid); } } protected function after_execute() { global $DB; // First of all, recode all the created question_categories->parent fields $qcats = $DB->get_records('backup_ids_temp', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_category_created')); foreach ($qcats as $qcat) { $newparent = 0; $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid)); // Get new parent (mapped or created, so we look in quesiton_category mappings) if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_category', 'itemid' => $dbcat->parent))) { // contextids must match always, as far as we always include complete qbanks, just check it $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent)); if ($dbcat->contextid == $newparentctxid) { $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id)); } else { $newparent = 0; // No ctx match for both cats, no parent relationship } } // Here with $newparent empty, problem with contexts or remapping, set it to top cat if (!$newparent) { $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id)); } } // Now, recode all the created question->parent fields $qs = $DB->get_records('backup_ids_temp', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_created')); foreach ($qs as $q) { $newparent = 0; $dbq = $DB->get_record('question', array('id' => $q->newitemid)); // Get new parent (mapped or created, so we look in question mappings) if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question', 'itemid' => $dbq->parent))) { $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id)); } } // Note, we don't restore any question files yet // as far as the CONTEXT_MODULE categories still // haven't their contexts to be restored to // The {@link restore_create_question_files}, executed in the final step // step will be in charge of restoring all the question files } } /** * Execution step that will move all the CONTEXT_MODULE question categories * created at early stages of restore in course context (because modules weren't * created yet) to their target module (matching by old-new-contextid mapping) */ class restore_move_module_questions_categories extends restore_execution_step { protected function define_execution() { global $DB; $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE); foreach ($contexts as $contextid => $contextlevel) { // Only if context mapping exists (i.e. the module has been restored) if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) { // Update all the qcats having their parentitemid set to the original contextid $modulecats = $DB->get_records_sql("SELECT itemid, newitemid FROM {backup_ids_temp} WHERE backupid = ? AND itemname = 'question_category' AND parentitemid = ?", array($this->get_restoreid(), $contextid)); foreach ($modulecats as $modulecat) { $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid)); // And set new contextid also in question_category mapping (will be // used by {@link restore_create_question_files} later restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid); } } } } } /** * Execution step that will create all the question/answers/qtype-specific files for the restored * questions. It must be executed after {@link restore_move_module_questions_categories} * because only then each question is in its final category and only then the * contexts can be determined. */ class restore_create_question_files extends restore_execution_step { /** @var array Question-type specific component items cache. */ private $qtypecomponentscache = array(); /** * Preform the restore_create_question_files step. */ protected function define_execution() { global $DB; // Track progress, as this task can take a long time. $progress = $this->task->get_progress(); $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE); // Parentitemids of question_createds in backup_ids_temp are the category it is in. // MUST use a recordset, as there is no unique key in the first (or any) column. $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype FROM {backup_ids_temp} bi JOIN {question} q ON q.id = bi.newitemid WHERE bi.backupid = ? AND bi.itemname = 'question_created' ORDER BY categoryid ASC", array($this->get_restoreid())); $currentcatid = -1; foreach ($catqtypes as $categoryid => $row) { $qtype = $row->qtype; // Check if we are in a new category. if ($currentcatid !== $categoryid) { // Report progress for each category. $progress->progress(); if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $categoryid)) { // Something went really wrong, cannot find the question_category for the question_created records. debugging('Error fetching target context for question', DEBUG_DEVELOPER); continue; } // Calculate source and target contexts. $oldctxid = $qcatmapping->info->contextid; $newctxid = $qcatmapping->parentitemid; $this->send_common_files($oldctxid, $newctxid, $progress); $currentcatid = $categoryid; } $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress); } $catqtypes->close(); $progress->end_progress(); } /** * Send the common question files to a new context. * * @param int $oldctxid Old context id. * @param int $newctxid New context id. * @param \core\progress $progress Progress object to use. */ private function send_common_files($oldctxid, $newctxid, $progress) { // Add common question files (question and question_answer ones). restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer', $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback', $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint', $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); } /** * Send the question type specific files to a new context. * * @param text $qtype The qtype name to send. * @param int $oldctxid Old context id. * @param int $newctxid New context id. * @param \core\progress $progress Progress object to use. */ private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) { if (!isset($this->qtypecomponentscache[$qtype])) { $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype); } $components = $this->qtypecomponentscache[$qtype]; foreach ($components as $component => $fileareas) { foreach ($fileareas as $filearea => $mapping) { restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea, $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress); } } } } /** * Try to restore aliases and references to external files. * * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}. * We expect that all regular (non-alias) files have already been restored. Make sure * there is no restore step executed after this one that would call send_files_to_pool() again. * * You may notice we have hardcoded support for Server files, Legacy course files * and user Private files here at the moment. This could be eventually replaced with a set of * callbacks in the future if needed. * * @copyright 2012 David Mudrak <david@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class restore_process_file_aliases_queue extends restore_execution_step { /** @var array internal cache for {@link choose_repository()} */ private $cachereposbyid = array(); /** @var array internal cache for {@link choose_repository()} */ private $cachereposbytype = array(); /** * What to do when this step is executed. */ protected function define_execution() { global $DB; $this->log('processing file aliases queue', backup::LOG_DEBUG); $fs = get_file_storage(); // Load the queue. $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'), '', 'info'); // Iterate over aliases in the queue. foreach ($rs as $record) { $info = backup_controller_dbops::decode_backup_temp_info($record->info); // Try to pick a repository instance that should serve the alias. $repository = $this->choose_repository($info); if (is_null($repository)) { $this->notify_failure($info, 'unable to find a matching repository instance'); continue; } if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') { // Aliases to Server files and Legacy course files may refer to a file // contained in the backup file or to some existing file (if we are on the // same site). try { $reference = file_storage::unpack_reference($info->oldfile->reference); } catch (Exception $e) { $this->notify_failure($info, 'invalid reference field format'); continue; } // Let's see if the referred source file was also included in the backup. $candidates = $DB->get_recordset('backup_files_temp', array( 'backupid' => $this->get_restoreid(), 'contextid' => $reference['contextid'], 'component' => $reference['component'], 'filearea' => $reference['filearea'], 'itemid' => $reference['itemid'], ), '', 'info, newcontextid, newitemid'); $source = null; foreach ($candidates as $candidate) { $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info); if ($candidateinfo->filename === $reference['filename'] and $candidateinfo->filepath === $reference['filepath'] and !is_null($candidate->newcontextid) and !is_null($candidate->newitemid) ) { $source = $candidateinfo; $source->contextid = $candidate->newcontextid; $source->itemid = $candidate->newitemid; break; } } $candidates->close(); if ($source) { // We have an alias that refers to another file also included in // the backup. Let us change the reference field so that it refers // to the restored copy of the original file. $reference = file_storage::pack_reference($source); // Send the new alias to the filepool. $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { // This is a reference to some moodle file that was not contained in the backup // file. If we are restoring to the same site, keep the reference untouched // and restore the alias as is if the referenced file exists. if ($this->task->is_samesite()) { if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) { $reference = file_storage::pack_reference($reference); $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { $this->notify_failure($info, 'referenced file not found'); continue; } // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'referenced file not included'); continue; } } } else if ($info->oldfile->repositorytype === 'user') { if ($this->task->is_samesite()) { // For aliases to user Private files at the same site, we have a chance to check // if the referenced file still exists. try { $reference = file_storage::unpack_reference($info->oldfile->reference); } catch (Exception $e) { $this->notify_failure($info, 'invalid reference field format'); continue; } if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) { $reference = file_storage::pack_reference($reference); $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { $this->notify_failure($info, 'referenced file not found'); continue; } // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'restoring at another site'); continue; } } else { // This is a reference to some external file such as in boxnet or dropbox. // If we are restoring to the same site, keep the reference untouched and // restore the alias as is. if ($this->task->is_samesite()) { $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference); $this->notify_success($info); continue; // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'restoring at another site'); continue; } } } $rs->close(); } /** * Choose the repository instance that should handle the alias. * * At the same site, we can rely on repository instance id and we just * check it still exists. On other site, try to find matching Server files or * Legacy course files repository instance. Return null if no matching * repository instance can be found. * * @param stdClass $info * @return repository|null */ private function choose_repository(stdClass $info) { global $DB, $CFG; require_once($CFG->dirroot.'/repository/lib.php'); if ($this->task->is_samesite()) { // We can rely on repository instance id. if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) { return $this->cachereposbyid[$info->oldfile->repositoryid]; } $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1); try { $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID); return $this->cachereposbyid[$info->oldfile->repositoryid]; } catch (Exception $e) { $this->cachereposbyid[$info->oldfile->repositoryid] = null; return null; } } else { // We can rely on repository type only. if (empty($info->oldfile->repositorytype)) { return null; } if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) { return $this->cachereposbytype[$info->oldfile->repositorytype]; } $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1); // Both Server files and Legacy course files repositories have a single // instance at the system context to use. Let us try to find it. if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') { $sql = "SELECT ri.id FROM {repository} r JOIN {repository_instances} ri ON ri.typeid = r.id WHERE r.type = ? AND ri.contextid = ?"; $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID)); if (empty($ris)) { return null; } $repoids = array_keys($ris); $repoid = reset($repoids); try { $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID); return $this->cachereposbytype[$info->oldfile->repositorytype]; } catch (Exception $e) { $this->cachereposbytype[$info->oldfile->repositorytype] = null; return null; } } $this->cachereposbytype[$info->oldfile->repositorytype] = null; return null; } } /** * Let the user know that the given alias was successfully restored * * @param stdClass $info */ private function notify_success(stdClass $info) { $filedesc = $this->describe_alias($info); $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1); } /** * Let the user know that the given alias can't be restored * * @param stdClass $info * @param string $reason detailed reason to be logged */ private function notify_failure(stdClass $info, $reason = '') { $filedesc = $this->describe_alias($info); if ($reason) { $reason = ' ('.$reason.')'; } $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1); $this->add_result_item('file_aliases_restore_failures', $filedesc); } /** * Return a human readable description of the alias file * * @param stdClass $info * @return string */ private function describe_alias(stdClass $info) { $filedesc = $this->expected_alias_location($info->newfile); if (!is_null($info->oldfile->source)) { $filedesc .= ' ('.$info->oldfile->source.')'; } return $filedesc; } /** * Return the expected location of a file * * Please note this may and may not work as a part of URL to pluginfile.php * (depends on how the given component/filearea deals with the itemid). * * @param stdClass $filerecord * @return string */ private function expected_alias_location($filerecord) { $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea; if (!is_null($filerecord->itemid)) { $filedesc .= '/'.$filerecord->itemid; } $filedesc .= $filerecord->filepath.$filerecord->filename; return $filedesc; } /** * Append a value to the given resultset * * @param string $name name of the result containing a list of values * @param mixed $value value to add as another item in that result */ private function add_result_item($name, $value) { $results = $this->task->get_results(); if (isset($results[$name])) { if (!is_array($results[$name])) { throw new coding_exception('Unable to append a result item into a non-array structure.'); } $current = $results[$name]; $current[] = $value; $this->task->add_result(array($name => $current)); } else { $this->task->add_result(array($name => array($value))); } } } /** * Abstract structure step, to be used by all the activities using core questions stuff * (like the quiz module), to support qtype plugins, states and sessions */ abstract class restore_questions_activity_structure_step extends restore_activity_structure_step { /** @var array question_attempt->id to qtype. */ protected $qtypes = array(); /** @var array question_attempt->id to questionid. */ protected $newquestionids = array(); /** * Attach below $element (usually attempts) the needed restore_path_elements * to restore question_usages and all they contain. * * If you use the $nameprefix parameter, then you will need to implement some * extra methods in your class, like * * protected function process_{nameprefix}question_attempt($data) { * $this->restore_question_usage_worker($data, '{nameprefix}'); * } * protected function process_{nameprefix}question_attempt($data) { * $this->restore_question_attempt_worker($data, '{nameprefix}'); * } * protected function process_{nameprefix}question_attempt_step($data) { * $this->restore_question_attempt_step_worker($data, '{nameprefix}'); * } * * @param restore_path_element $element the parent element that the usages are stored inside. * @param array $paths the paths array that is being built. * @param string $nameprefix should match the prefix passed to the corresponding * backup_questions_activity_structure_step::add_question_usages call. */ protected function add_question_usages($element, &$paths, $nameprefix = '') { // Check $element is restore_path_element if (! $element instanceof restore_path_element) { throw new restore_step_exception('element_must_be_restore_path_element', $element); } // Check $paths is one array if (!is_array($paths)) { throw new restore_step_exception('paths_must_be_array', $paths); } $paths[] = new restore_path_element($nameprefix . 'question_usage', $element->get_path() . "/{$nameprefix}question_usage"); $paths[] = new restore_path_element($nameprefix . 'question_attempt', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt"); $paths[] = new restore_path_element($nameprefix . 'question_attempt_step', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step", true); $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable"); } /** * Process question_usages */ protected function process_question_usage($data) { $this->restore_question_usage_worker($data, ''); } /** * Process question_attempts */ protected function process_question_attempt($data) { $this->restore_question_attempt_worker($data, ''); } /** * Process question_attempt_steps */ protected function process_question_attempt_step($data) { $this->restore_question_attempt_step_worker($data, ''); } /** * This method does the acutal work for process_question_usage or * process_{nameprefix}_question_usage. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_usage_worker($data, $nameprefix) { global $DB; // Clear our caches. $this->qtypes = array(); $this->newquestionids = array(); $data = (object)$data; $oldid = $data->id; $oldcontextid = $this->get_task()->get_old_contextid(); $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid()); // Everything ready, insert (no mapping needed) $newitemid = $DB->insert_record('question_usages', $data); $this->inform_new_usage_id($newitemid); $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false); } /** * When process_question_usage creates the new usage, it calls this method * to let the activity link to the new usage. For example, the quiz uses * this method to set quiz_attempts.uniqueid to the new usage id. * @param integer $newusageid */ abstract protected function inform_new_usage_id($newusageid); /** * This method does the acutal work for process_question_attempt or * process_{nameprefix}_question_attempt. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_attempt_worker($data, $nameprefix) { global $DB; $data = (object)$data; $oldid = $data->id; $question = $this->get_mapping('question', $data->questionid); $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage'); $data->questionid = $question->newitemid; if (!property_exists($data, 'variant')) { $data->variant = 1; } $data->timemodified = $this->apply_date_offset($data->timemodified); if (!property_exists($data, 'maxfraction')) { $data->maxfraction = 1; } $newitemid = $DB->insert_record('question_attempts', $data); $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid); $this->qtypes[$newitemid] = $question->info->qtype; $this->newquestionids[$newitemid] = $data->questionid; } /** * This method does the acutal work for process_question_attempt_step or * process_{nameprefix}_question_attempt_step. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_attempt_step_worker($data, $nameprefix) { global $DB; $data = (object)$data; $oldid = $data->id; // Pull out the response data. $response = array(); if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) { foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) { $response[$variable['name']] = $variable['value']; } } unset($data->response); $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt'); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->userid = $this->get_mappingid('user', $data->userid); // Everything ready, insert and create mapping (needed by question_sessions) $newitemid = $DB->insert_record('question_attempt_steps', $data); $this->set_mapping('question_attempt_step', $oldid, $newitemid, true); // Now process the response data. $response = $this->questions_recode_response_data( $this->qtypes[$data->questionattemptid], $this->newquestionids[$data->questionattemptid], $data->sequencenumber, $response); foreach ($response as $name => $value) { $row = new stdClass(); $row->attemptstepid = $newitemid; $row->name = $name; $row->value = $value; $DB->insert_record('question_attempt_step_data', $row, false); } } /** * Recode the respones data for a particular step of an attempt at at particular question. * @param string $qtype the question type. * @param int $newquestionid the question id. * @param int $sequencenumber the sequence number. * @param array $response the response data to recode. */ public function questions_recode_response_data( $qtype, $newquestionid, $sequencenumber, array $response) { $qtyperestorer = $this->get_qtype_restorer($qtype); if ($qtyperestorer) { $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response); } return $response; } /** * Given a list of question->ids, separated by commas, returns the * recoded list, with all the restore question mappings applied. * Note: Used by quiz->questions and quiz_attempts->layout * Note: 0 = page break (unconverted) */ protected function questions_recode_layout($layout) { // Extracts question id from sequence if ($questionids = explode(',', $layout)) { foreach ($questionids as $id => $questionid) { if ($questionid) { // If it is zero then this is a pagebreak, don't translate $newquestionid = $this->get_mappingid('question', $questionid); $questionids[$id] = $newquestionid; } } } return implode(',', $questionids); } /** * Get the restore_qtype_plugin subclass for a specific question type. * @param string $qtype e.g. multichoice. * @return restore_qtype_plugin instance. */ protected function get_qtype_restorer($qtype) { // Build one static cache to store {@link restore_qtype_plugin} // while we are needing them, just to save zillions of instantiations // or using static stuff that will break our nice API static $qtypeplugins = array(); if (!isset($qtypeplugins[$qtype])) { $classname = 'restore_qtype_' . $qtype . '_plugin'; if (class_exists($classname)) { $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this); } else { $qtypeplugins[$qtype] = null; } } return $qtypeplugins[$qtype]; } protected function after_execute() { parent::after_execute(); // Restore any files belonging to responses. foreach (question_engine::get_all_response_file_areas() as $filearea) { $this->add_related_files('question', $filearea, 'question_attempt_step'); } } /** * Attach below $element (usually attempts) the needed restore_path_elements * to restore question attempt data from Moodle 2.0. * * When using this method, the parent element ($element) must be defined with * $grouped = true. Then, in that elements process method, you must call * {@link process_legacy_attempt_data()} with the groupded data. See, for * example, the usage of this method in {@link restore_quiz_activity_structure_step}. * @param restore_path_element $element the parent element. (E.g. a quiz attempt.) * @param array $paths the paths array that is being built to describe the * structure. */ protected function add_legacy_question_attempt_data($element, &$paths) { global $CFG; require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php'); // Check $element is restore_path_element if (!($element instanceof restore_path_element)) { throw new restore_step_exception('element_must_be_restore_path_element', $element); } // Check $paths is one array if (!is_array($paths)) { throw new restore_step_exception('paths_must_be_array', $paths); } $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state'); $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session'); } protected function get_attempt_upgrader() { if (empty($this->attemptupgrader)) { $this->attemptupgrader = new question_engine_attempt_upgrader(); $this->attemptupgrader->prepare_to_restore(); } return $this->attemptupgrader; } /** * Process the attempt data defined by {@link add_legacy_question_attempt_data()}. * @param object $data contains all the grouped attempt data to process. * @param pbject $quiz data about the activity the attempts belong to. Required * fields are (basically this only works for the quiz module): * oldquestions => list of question ids in this activity - using old ids. * preferredbehaviour => the behaviour to use for questionattempts. */ protected function process_legacy_quiz_attempt_data($data, $quiz) { global $DB; $upgrader = $this->get_attempt_upgrader(); $data = (object)$data; $layout = explode(',', $data->layout); $newlayout = $layout; // Convert each old question_session into a question_attempt. $qas = array(); foreach (explode(',', $quiz->oldquestions) as $questionid) { if ($questionid == 0) { continue; } $newquestionid = $this->get_mappingid('question', $questionid); if (!$newquestionid) { throw new restore_step_exception('questionattemptreferstomissingquestion', $questionid, $questionid); } $question = $upgrader->load_question($newquestionid, $quiz->id); foreach ($layout as $key => $qid) { if ($qid == $questionid) { $newlayout[$key] = $newquestionid; } } list($qsession, $qstates) = $this->find_question_session_and_states( $data, $questionid); if (empty($qsession) || empty($qstates)) { throw new restore_step_exception('questionattemptdatamissing', $questionid, $questionid); } list($qsession, $qstates) = $this->recode_legacy_response_data( $question, $qsession, $qstates); $data->layout = implode(',', $newlayout); $qas[$newquestionid] = $upgrader->convert_question_attempt( $quiz, $data, $question, $qsession, $qstates); } // Now create a new question_usage. $usage = new stdClass(); $usage->component = 'mod_quiz'; $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid()); $usage->preferredbehaviour = $quiz->preferredbehaviour; $usage->id = $DB->insert_record('question_usages', $usage); $this->inform_new_usage_id($usage->id); $data->uniqueid = $usage->id; $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas, $this->questions_recode_layout($quiz->oldquestions)); } protected function find_question_session_and_states($data, $questionid) { $qsession = null; foreach ($data->sessions['session'] as $session) { if ($session['questionid'] == $questionid) { $qsession = (object) $session; break; } } $qstates = array(); foreach ($data->states['state'] as $state) { if ($state['question'] == $questionid) { // It would be natural to use $state['seq_number'] as the array-key // here, but it seems that buggy behaviour in 2.0 and early can // mean that that is not unique, so we use id, which is guaranteed // to be unique. $qstates[$state['id']] = (object) $state; } } ksort($qstates); $qstates = array_values($qstates); return array($qsession, $qstates); } /** * Recode any ids in the response data * @param object $question the question data * @param object $qsession the question sessions. * @param array $qstates the question states. */ protected function recode_legacy_response_data($question, $qsession, $qstates) { $qsession->questionid = $question->id; foreach ($qstates as &$state) { $state->question = $question->id; $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype); } return array($qsession, $qstates); } /** * Recode the legacy answer field. * @param object $state the state to recode the answer of. * @param string $qtype the question type. */ public function restore_recode_legacy_answer($state, $qtype) { $restorer = $this->get_qtype_restorer($qtype); if ($restorer) { return $restorer->recode_legacy_state_answer($state); } else { return $state->answer; } } }
jrchamp/moodle
backup/moodle2/restore_stepslib.php
PHP
gpl-3.0
202,518
/* * 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 xmv.solutions.IT2JZ.Jira; /** * * @author David Koller XMV Solutions GmbH */ public class JiraTestcaseStep { /** * Name of Step (e.g. "Step 1") */ private String stepName; /** * Action to give in actual step (e.g. "Press red button") */ private String testData; /** * Expected result of action for current step (e.g. "Popup is shown saying 'Done!'") */ private String expectedResult; public String getStepName() { return stepName; } public void setStepName(String stepName) { this.stepName = stepName; } public String getTestData() { return testData; } public void setTestData(String testData) { this.testData = testData; } public String getExpectedResult() { return expectedResult; } public void setExpectedResult(String expectedResult) { this.expectedResult = expectedResult; } }
XMV-Solutions/ImportTestcases2JiraZephyr
src/main/java/xmv/solutions/IT2JZ/Jira/JiraTestcaseStep.java
Java
gpl-3.0
1,034
/* package de.elxala.langutil (c) Copyright 2006 Alejandro Xalabarder Aulet 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* //(o) WelcomeGastona_source_javaj_layout EVALAYOUT ======================================================================================== ================ documentation for WelcomeGastona.gast ================================= ======================================================================================== #gastonaDoc# <docType> javaj_layout <name> EVALAYOUT <groupInfo> <javaClass> de.elxala.Eva.layout.EvaLayout <importance> 10 <desc> //A fexible grid layout <help> // // Eva layout is the most powerful layout used by Javaj. The components are laid out in a grid // and it is possible to define very accurately which cells of the grid occupy each one, which // size has to have and if they are expandable or not. // // Syntax: // // <layout of NAME> // EVALAYOUT, marginX, marginY, gapX, gapY // // --grid-- , header col1, ... , header colN // header row1, cell 1 1 , ... , cell 1 N // ... , ... , ... , ... // header rowM, cell M 1 , ... , cell M N // // The first row starts with "EVALAYOUT" or simply "EVA", then optionally the following values // in pixels for the whole grid // // marginX : horizontal margins for both left and right sides // marginY : vertical margins for both top and bottom areas // gapX : horizontal space between columns // gapY : vertical space between rows // // The rest of rows defines a grid with arbitrary N columns and M rows, the minimum for both M // and N is 1. To define a grid M x N we will need M+1 rows and a maximum of N+1 columns, this // is because the header types given in rows and columns. These header values may be one of: // // header // value meaning // ------- -------- // A Adapt (default). The row or column will adapt its size to the bigest default // size of all components that start in this row or column. // X Expand. The row or column is expandable, when the the frame is resized all // expandable row or columns will share the remaining space equally. // a number A fix size in pixels for the row or column // // Note that the very first header ("--grid--") acctually does not correspond with a row or a // column of the grid and therefore it is ignored by EvaLayout. // // Finally the cells are used to place and expand the components. If we want the component to // ocupy just one cell then we place it in that cell. If we want the component to ocupy more // cells then we place the component on the left-top cell of the rectangle of cells to be // ocupped, we fill the rest of top cells with "-" to the right and the rest of left cells with // the symbol "+" to the bottom, the rest of cells (neither top or left cells) might be left in // blank. // // Example: // // let's say we want to lay-out the following form // // ---------------------------------------------- // | label1 | field -------> | button1 | // ---------------------------------------------- // | label2 | text -------> | button2 | // ------------| | |---------- // | | | button3 | // | V |---------- // | | // ------------------------ // // representing this as grid of cells can be done at least in these two ways // // // Adapt Adapt Expand Adapt Adapt Expand Adapt // ------------------------------------- ----------------------------- // Adapt | label1 | field | - | button1 | Adapt | label1 | field | button1 | // |---------|-------|-------|---------| |---------|-------|---------| // Adapt | label2 | text | - | button2 | Adapt | label2 | text | button2 | // |---------|------ |-------|---------| |---------|------ |---------| // Adapt | | + | | button3 | Adapt | | + | button3 | // |---------|------ |-------|---------| |---------|------ |---------| // Expand | | + | | | Expand | | + | | // ------------------------------------- ----------------------------- // // the implementation of the second one as Evalayout would be // // <layout of myFirstLayout> // // EVALAYOUT // // grid, A , X , A // A, label1 , field , button1 // A, label2 , text , button2 // A, , + , button3 // X, , + , // // NOTE: While columns and rows of type expandable or fixed size might be empty of components, // this does not make sense for columns and rows of type adaptable (A), since in this // case there is nothing to adapt. These columns or rows has to be avoided because // might produce undefined results. // <...> // NOTE: EvaLayout is also available for C++ development with Windows Api and MFC, // see as reference the article http://www.codeproject.com/KB/dialog/EvaLayout.aspx // <examples> gastSample eva layout example1 eva layout example2 eva layout example3 eva layout complet eva layout centering eva layout percenting <eva layout example1> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example layout EVALAYOUT" // // <layout of F> // // EVALAYOUT, 10, 10, 5, 5 // // grid, , X , // , lLabel1 , eField1 , bButton1 // , lLabel2 , xText1 , bButton2 // , , + , bButton3 // X , , + , <eva layout example2> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example 2 layout EVALAYOUT" // // <layout of F> // // EVA, 10, 10, 5, 5 // // --- , 75 , X , A , // , bButton , xMemo , - , // , bBoton , + , , // , bKnopf , + , , // X , , + , , // , eCamp , - , bBotó maco , <eva layout example3> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example 2 bis layout EVALAYOUT" // // <layout of F> // EVALAYOUT, 15, 15, 5, 5 // // , , X , // 50, bBoton1 , - , - // , bBoton4 , eField , bBoton2 // X , + , xText , + // 50, bBoton3 , - , + <eva layout complet> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example complex layout" // // <layout of F> // EVALAYOUT, 15, 15, 5, 5 // // ---, 80 , X , 110 // , lLabel1 , eEdit1 , - // , lLabel2 , cCombo , lLabel3 // , lLabel4 , xMemo , iLista // , bBoton1 , + , + // , bBoton2 , + , + // X , , + , + // , layOwner , - , + // , , , bBoton4 // // <layout of layOwner> // PANEL, Y, Owner Info // // LayFields // // <layout of LayFields> // EVALAYOUT, 5, 5, 5, 5 // // ---, , X // , lName , eName // , lPhone , ePhone // <eva layout centering> //#gastona# // // <PAINT LAYOUT> // //#javaj# // // <frames> // Fmain, Centering with EvaLayout demo // // <layout of Fmain> // EVA // // , X, A , X // X , // A , , bCentered // X , <eva layout percenting> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // Fmain, Percenting with EvaLayout demo, 300, 300 // // <layout of Fmain> // EVA, 10, 10, 7, 7 // // , X , X , X , X // X , b11 , b13 , - , - // X , b22 , - , b23 , - // X , + , , + , // X , b12 , - , + , // //#data# // // <b11> 25% x 25% // <b13> 75% horizontally 25% vertically // <b22> fifty-fifty // <b12> 50% x 25% y // <b23> half and 3/4 #**FIN_EVA# */ package de.elxala.Eva.layout; import java.util.Vector; import java.util.Hashtable; import java.util.Enumeration; // to traverse the HashTable ... import java.awt.*; import de.elxala.Eva.*; import de.elxala.langutil.*; import de.elxala.zServices.*; /** @author Alejandro Xalabarder @date 11.04.2006 22:32 Example: <pre> import java.awt.*; import javax.swing.*; import de.elxala.Eva.*; import de.elxala.Eva.layout.*; public class sampleEvaLayout { public static void main (String [] aa) { JFrame frame = new JFrame ("sampleEvaLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = frame.getContentPane (); Eva lay = new Eva(); // set margins lay.addLine (new EvaLine ("EvaLayout, 15, 15, 5, 5")); // set grid lay.addLine (new EvaLine ("RxC, , 100 , X ,")); lay.addLine (new EvaLine (" , lname , eName , ,")); lay.addLine (new EvaLine (" , lobserv, xObs , - ,")); lay.addLine (new EvaLine (" X, , + , ,")); pane.setLayout (new EvaLayout(lay)); pane.add ("lname", new JLabel("Name")); pane.add ("lobserv", new JLabel("Notes")); pane.add ("eName", new JTextField()); pane.add ("xObs", new JTextPane()); frame.pack(); frame.setSize (new Dimension (300, 200)); frame.show(); } } </pre> */ public class EvaLayout implements LayoutManager2 { private static logger log = new logger (null, "de.elxala.Eva.EvaLayout", null); //19.10.2010 20:31 // Note : Limits introduced in change (bildID) 11088 on 2010-09-20 01:47:25 // named "FIX problema en layout (LOW LEVEL BUG 2!)" // But today the problem (without limits) cannot be reproduced! (?) // Limits set as aproximation, these can be reviewed and changed // private static int MAX_SIZE_DX = 10000; private static int MAX_SIZE_DY = 10000; protected static final int HEADER_EXPAND = 10; protected static final int HEADER_ORIGINAL = 11; protected static final int HEADER_NUMERIC = 12; protected static final String EXPAND_HORIZONTAL = "-"; protected static final String EXPAND_VERTICAL = "+"; // variables for pre-calculated layout // private boolean isPrecalculated = false; protected int Hmargin; protected int Vmargin; protected int Hgap; protected int Vgap; private int mnCols = -1; // note : this is a cached value and might be call before precalculation! private int mnRows = -1; // note : this is a cached value and might be call before precalculation! private int fijoH = 0; private int fijoV = 0; public int [] HdimMin = new int [0]; public int [] HdimPref = new int [0]; // for preferred instead of minimum public int [] Hpos = new int [0]; public int [] VdimMin = new int [0]; public int [] VdimPref = new int [0]; // for preferred instead of minimum public int [] Vpos = new int [0]; private Eva lay = null; private Hashtable componentHTable = new Hashtable(); protected class widgetInfo { public widgetInfo (String nam, Component com) { name = nam; comp = com; } public String name; // name of the component in the layout array public Component comp; // component info public boolean isLaidOut; // if the component has been found in the layout array // and therefore if indxPos is a valid calculated field // place in the layout array mesured in array indices public int posCol0; // first column that the widget occupies public int posRow0; // first row public int posCol1; // last column public int posRow1; // last row } Vector columnsReparto = new Vector (); Vector rowsReparto = new Vector (); public EvaLayout() { this(new Eva()); } public EvaLayout(Eva layarray) { log.dbg (2, "EvaLayout", "create EvaLayout " + layarray.getName ()); lay = layarray; } /** Switches to another layout : note that the components used in this new layout has to exists (added to the layout using add method) */ public void switchLayout(Eva layarray) { log.dbg (2, "switchLayout", "switch new layout info " + layarray.getName ()); lay = layarray; invalidatePreCalc (); } private int headType (String str) { if (str.length () == 0 || str.equalsIgnoreCase ("a")) return HEADER_ORIGINAL; if (str.equalsIgnoreCase ("x")) return HEADER_EXPAND; return HEADER_NUMERIC; // it should } private void precalculateAll () { if (isPrecalculated) return; log.dbg (2, "precalculateAll", "layout " + lay.getName () + " perform precalculation."); Hmargin = Math.max (0, stdlib.atoi (lay.getValue (0,1))); Vmargin = Math.max (0, stdlib.atoi (lay.getValue (0,2))); Hgap = Math.max (0, stdlib.atoi (lay.getValue (0,3))); Vgap = Math.max (0, stdlib.atoi (lay.getValue (0,4))); log.dbg (4, "precalculateAll", nColumns() + " columns x " + nRows() + " rows"); log.dbg (4, "precalculateAll", "margins xm=" + Hmargin + ", ym=" + Vmargin + ", yg=" + Hgap + ", yg=" + Vgap); mnCols = -1; // reset cached number of cols mnRows = -1; // reset cached number of rows HdimMin = new int [nColumns()]; HdimPref = new int [nColumns()]; Hpos = new int [nColumns()]; VdimMin = new int [nRows()]; VdimPref = new int [nRows()]; Vpos = new int [nRows()]; columnsReparto = new Vector (); rowsReparto = new Vector (); // for all components ... Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); ((widgetInfo) componentHTable.get(key)).isLaidOut = false; } // compute Vdim (Note: it might be precalculated if needed) fijoV = Vmargin; for (int rr = 0; rr < nRows(); rr ++) { String heaRow = rowHeader(rr); int typ = headType(heaRow); int gap = (rr == 0) ? 0: Vgap; if (typ == HEADER_ORIGINAL) { // maximum-minimum of the row VdimPref[rr] = minHeightOfRow(rr, true); VdimMin[rr] = minHeightOfRow(rr, false); log.dbg (2, "precalculateAll", "Adaption... VdimPref[rr] = " + VdimPref[rr]); } else if (typ == HEADER_EXPAND) { rowsReparto.add (new int [] { rr }); // compute later log.dbg (2, "precalculateAll", "Expand... VdimPref[rr] = " + VdimPref[rr]); } else { // indicated size VdimPref[rr] = VdimMin[rr] = stdlib.atoi(heaRow); log.dbg (2, "precalculateAll", "Explicit... VdimPref[rr] = " + VdimPref[rr]); } Vpos[rr] = fijoV + gap; fijoV += VdimPref[rr]; fijoV += gap; } fijoV += Vmargin; log.dbg (2, "precalculateAll", "fijoV = " + fijoV + " Vmargin = " + Vmargin + " Vgap = " + Vgap); //DEBUG .... if (log.isDebugging (2)) { String vertical = "Vertical array (posY/prefHeight/minHeight)"; for (int rr = 0; rr < Vpos.length; rr++) vertical += " " + rr + ") " + Vpos[rr] + "/" + VdimPref[rr] + "/" + VdimMin[rr]; log.dbg (2, "precalculateAll", vertical); } // compute Hdim (Note: it might be precalculated if needed) fijoH = Hmargin; for (int cc = 0; cc < nColumns(); cc ++) { String heaCol = columnHeader(cc); int typ = headType(heaCol); int gap = (cc == 0) ? 0: Hgap; if (typ == HEADER_ORIGINAL) { // maximum-minimum of the column HdimPref[cc] = minWidthOfColumn(cc, true); HdimMin[cc] = minWidthOfColumn(cc, false); } else if (typ == HEADER_EXPAND) columnsReparto.add (new int [] { cc }); // compute later else HdimPref[cc] = HdimMin[cc] = stdlib.atoi(heaCol); // indicated size Hpos[cc] = fijoH + gap; fijoH += HdimPref[cc]; fijoH += gap; } fijoH += Hmargin; log.dbg (2, "precalculateAll", "fijoH = " + fijoH); //DEBUG .... if (log.isDebugging (2)) { String horizontal = "Horizontal array (posX/prefWidth/minWidth)"; for (int cc = 0; cc < Hpos.length; cc++) horizontal += " " + cc + ") " + Hpos[cc] + "/" + HdimPref[cc] + "/" + HdimMin[cc]; log.dbg (2, "precalculateAll", horizontal); } // finding all components in the layout array for (int cc = 0; cc < nColumns(); cc ++) { for (int rr = 0; rr < nRows(); rr ++) { String name = widgetAt(rr, cc); widgetInfo wid = theComponent (name); if (wid == null) continue; // set position x,y wid.posCol0 = cc; wid.posRow0 = rr; // set position x2,y2 int ava = cc; while (ava+1 < nColumns() && widgetAt(rr, ava+1).equals (EXPAND_HORIZONTAL)) ava ++; wid.posCol1 = ava; ava = rr; while (ava+1 < nRows() && widgetAt(ava+1, cc).equals (EXPAND_VERTICAL)) ava ++; wid.posRow1 = ava; wid.isLaidOut = true; //DEBUG .... if (log.isDebugging (2)) { log.dbg (2, "precalculateAll", wid.name + " leftTop (" + wid.posCol0 + ", " + wid.posRow0 + ") rightBottom (" + wid.posCol1 + ", " + wid.posRow1 + ")"); } } } isPrecalculated = true; } protected int nColumns () { // OLD // return Math.max(0, lay.cols(1) - 1); if (mnCols != -1) return mnCols; // has to be calculated, // the maximum n of cols of header or rows // for (int ii = 1; ii < lay.rows (); ii ++) if (mnCols < Math.max(0, lay.cols(ii) - 1)) mnCols = Math.max(0, lay.cols(ii) - 1); mnCols = Math.max(0, mnCols); return mnCols; } protected int nRows () { // OLD // return Math.max(0, lay.rows() - 2); if (mnRows != -1) return mnRows; mnRows = Math.max(0, lay.rows() - 2); return mnRows; } public Eva getEva () { return lay; } public String [] getWidgets () { java.util.Vector vecWidg = new java.util.Vector (); for (int rr = 0; rr < nRows(); rr ++) for (int cc = 0; cc < nColumns(); cc ++) { String name = widgetAt (rr, cc); if (name.length() > 0 && !name.equals(EXPAND_HORIZONTAL) && !name.equals(EXPAND_VERTICAL)) vecWidg.add (name); } // pasarlo a array String [] arrWidg = new String [vecWidg.size ()]; for (int ii = 0; ii < arrWidg.length; ii ++) arrWidg[ii] = (String) vecWidg.get (ii); return arrWidg; } /** * Adds the specified component with the specified name */ public void addLayoutComponent(String name, Component comp) { log.dbg (2, "addLayoutComponent", name + " compName (" + comp.getName () + ")"); componentHTable.put(name, new widgetInfo (name, comp)); isPrecalculated = false; } /** * Removes the specified component from the layout. * @param comp the component to be removed */ public void removeLayoutComponent(Component comp) { // componentHTable.remove(comp); } /** * Calculates the preferred size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out */ public Dimension preferredLayoutSize(Container parent) { ///*EXPERIMENT!!!*/invalidatePreCalc (); Dimension di = getLayoutSize(parent, true); log.dbg (2, "preferredLayoutSize", lay.getName() + " preferredLayoutSize (" + di.width + ", " + di.height + ")"); //(o) TODO_javaj_layingOut Problem: preferredLayoutSize //19.04.2009 19:50 Problem: preferredLayoutSize is called when pack and after that no more // layouts data dependent like slider (don't know if horizontal or vertical) have problems // Note: this is not just a problem of EvaLayout but of all layout managers //log.severe ("SEVERINIO!"); return di; } /** * Calculates the minimum size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out */ public Dimension minimumLayoutSize(Container parent) { Dimension di = getLayoutSize(parent, false); log.dbg (2, "minimumLayoutSize", lay.getName() + " minimumLayoutSize (" + di.width + ", " + di.height + ")"); return di; } /** *calculating layout size (minimum or preferred). */ protected Dimension getLayoutSize(Container parent, boolean isPreferred) { log.dbg (2, "getLayoutSize", lay.getName()); precalculateAll (); // In precalculateAll the methods minWidthOfColumn and minHeightOfRow // does not evaluate expandable components since these might use other columns. // But in order to calculate the minimum or preferred total size we need this information. // In these cases we have to calculate following : if the sum of the sizes of the // columns that the component occupies is less that the minimum/preferred size of // the component then we add the difference to the total width // We evaluate this ONLY for those components that could be expanded! // for example // // NO COMPONENT HAS TO COMPONENTS comp1 and comp3 // BE RECALCULED HAS TO BE RECALCULED // --------------------- ------------------------ // grid, 160 , A grid, 160 , X // A , comp1 , - A , comp1 , - // A , comp2 , comp3 X , comp2 , comp3 // int [] extraCol = new int [nColumns ()]; int [] extraRow = new int [nRows ()]; int [] Hdim = isPreferred ? HdimPref: HdimMin; int [] Vdim = isPreferred ? VdimPref: VdimMin; //System.err.println ("PARLANT DE " + lay.getName () + " !!!"); // for all components ... Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { boolean someExpan = false; String key = (String) enu.nextElement(); widgetInfo wi = (widgetInfo) componentHTable.get(key); if (! wi.isLaidOut) continue; Dimension csiz = (isPreferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); log.dbg (2, "getLayoutSize", wi.name + " dim (" + csiz.width + ", " + csiz.height + ")"); // some column expandable ? // someExpan = false; for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) if (headType(columnHeader(cc)) == HEADER_EXPAND) { someExpan = true; break; } if (someExpan) { // sum of all columns that this component occupy int sum = 0; for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) sum += (Hdim[cc] + extraCol[cc]); // distribute it in all columns to be salomonic int resto = csiz.width - sum; if (resto > 0) { if (wi.posCol0 == wi.posCol1) { // System.err.println ("Resto X " + resto + " de " + wi.name + " en la " + wi.posCol0 + " veniendo de csiz.width " + csiz.width + " y sum " + sum + " que repahartimos en " + (1 + wi.posCol1 - wi.posCol0) + " parates tenahamos una estra de " + extraCol[wi.posCol0]); } for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) extraCol[cc] = resto / (1 + wi.posCol1 - wi.posCol0); } } // some row expandable ? // someExpan = false; for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) if (headType(rowHeader(rr)) == HEADER_EXPAND) { someExpan = true; break; } if (someExpan) { // sum of all height (rows) that this component occupy int sum = 0; for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) sum += (Vdim[rr] + extraRow[rr]); // distribute it in all columns to be salomonic int resto = csiz.height - sum; if (resto > 0) { for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) extraRow[rr] = resto / (1 + wi.posRow1 - wi.posRow0); } } } int tot_width = 0; for (int cc = 0; cc < nColumns(); cc ++) { tot_width += (Hdim[cc] + extraCol[cc]); } int tot_height = 0; for (int rr = 0; rr < nRows(); rr ++) { tot_height += Vdim[rr] + extraRow[rr]; } Insets insets = (parent != null) ? parent.getInsets(): new Insets(0,0,0,0); tot_width += Hgap * (nColumns() - 1) + insets.left + insets.right + 2 * Hmargin; tot_height += Vgap * (nRows() - 1) + insets.top + insets.bottom + 2 * Vmargin; log.dbg (2, "getLayoutSize", "returning tot_width " + tot_width + ", tot_height " + tot_height); // System.out.println ("getLayoutSize pref=" + isPreferred + " nos sale (" + tot_width + ", " + tot_height + ")"); return new Dimension (tot_width, tot_height); } private String columnHeader(int ncol) { return lay.getValue(1, ncol + 1).toUpperCase (); } private String rowHeader(int nrow) { return lay.getValue(2 + nrow, 0).toUpperCase (); } private String widgetAt(int nrow, int ncol) { return lay.getValue (nrow + 2, ncol + 1); } private widgetInfo theComponent(String cellName) { if (cellName.length() == 0 || cellName.equals(EXPAND_HORIZONTAL) || cellName.equals(EXPAND_VERTICAL)) return null; widgetInfo wi = (widgetInfo) componentHTable.get(cellName); if (wi == null) log.severe ("theComponent", "Component " + cellName + " not found in the container laying out " + lay.getName () + "!"); return wi; } private int minWidthOfColumn (int ncol, boolean preferred) { // el componente ma's ancho de la columna int maxwidth = 0; for (int rr = 0; rr < nRows(); rr ++) { String name = widgetAt (rr, ncol); widgetInfo wi = theComponent (name); if (wi != null) { if (widgetAt (rr, ncol+1).equals(EXPAND_HORIZONTAL)) continue; // widget occupies more columns so do not compute it Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); maxwidth = Math.max (maxwidth, csiz.width); } } //19.09.2010 Workaround //in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail! return maxwidth > MAX_SIZE_DX ? MAX_SIZE_DX : maxwidth; } private int minHeightOfRow (int nrow, boolean preferred) { // el componente ma's alto de la columna int maxheight = 0; for (int cc = 0; cc < nColumns(); cc ++) { String name = widgetAt (nrow, cc); widgetInfo wi = theComponent (name); if (wi != null) { if (widgetAt (nrow+1, cc).equals(EXPAND_VERTICAL)) continue; // widget occupies more rows so do not compute it Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); maxheight = Math.max (maxheight, csiz.height); } } //19.09.2010 Workaround //in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail! return maxheight > MAX_SIZE_DY ? MAX_SIZE_DY : maxheight; } /** * Lays out the container in the specified container. * @param parent the component which needs to be laid out */ public void layoutContainer(Container parent) { //isPrecalculated = false; if (log.isDebugging(4)) log.dbg (4, "layoutContainer", lay.getName ()); precalculateAll (); synchronized (parent.getTreeLock()) { Insets insets = parent.getInsets(); //if (log.isDebugging(4)) // log.dbg (4, "layoutContainer", "insets left right =" + insets.left + ", " + insets.right + " top bottom " + insets.top + ", " + insets.bottom); // Total parent dimensions Dimension size = parent.getSize(); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "parent size =" + size.width + ", " + size.height); int repartH = size.width - (insets.left + insets.right) - fijoH; int repartV = size.height - (insets.top + insets.bottom) - fijoV; int [] HextraPos = new int [HdimPref.length]; int [] VextraPos = new int [VdimPref.length]; if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "repartH=" + repartH + " repartV=" + repartV); // repartir H if (columnsReparto.size() > 0) { repartH /= columnsReparto.size(); for (int ii = 0; ii < columnsReparto.size(); ii ++) { int indx = ((int []) columnsReparto.get (ii))[0]; HdimPref[indx] = repartH; for (int res = indx+1; res < nColumns(); res ++) HextraPos[res] += repartH; } } // repartir V if (rowsReparto.size() > 0) { repartV /= rowsReparto.size(); for (int ii = 0; ii < rowsReparto.size(); ii ++) { int indx = ((int []) rowsReparto.get (ii))[0]; VdimPref[indx] = repartV; for (int res = indx+1; res < nRows(); res ++) VextraPos[res] += repartV; } } // // for all components ... for (int ii = 0; ii < componentArray.size(); ii ++) // java.util.Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); widgetInfo wi = (widgetInfo) componentHTable.get(key); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "element [" + key + "]"); // System.out.println ("componente " + wi.name); if (! wi.isLaidOut) continue; // System.out.println (" indices " + wi.posCol0 + " (" + Hpos[wi.posCol0] + " extras " + HextraPos[wi.posCol0] + ")"); int x = Hpos[wi.posCol0] + HextraPos[wi.posCol0]; int y = Vpos[wi.posRow0] + VextraPos[wi.posRow0]; int dx = 0; int dy = 0; //if (log.isDebugging(4)) // log.dbg (4, "SIGUEY", "1) y = " + y + " Vpos[wi.posRow0] = " + Vpos[wi.posRow0] + " VextraPos[wi.posRow0] = " + VextraPos[wi.posRow0]); for (int mm = wi.posCol0; mm <= wi.posCol1; mm ++) { if (mm != wi.posCol0) dx += Hgap; dx += HdimPref[mm]; } for (int mm = wi.posRow0; mm <= wi.posRow1; mm ++) { if (mm != wi.posRow0) dy += Vgap; dy += VdimPref[mm]; } if (x < 0 || y < 0 || dx < 0 || dy < 0) { //Disable this warning because it happens very often when minimizing the window etc //log.warn ("layoutContainer", "component not laid out! [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")"); continue; } wi.comp.setBounds(x, y, dx, dy); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "vi.name [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")"); } } // end synchronized } // LayoutManager2 ///////////////////////////////////////////////////////// /** * This method make no sense in this layout, the constraints are not per component * but per column and rows. Since this method is called when adding components through * the method add(String, Component) we implement it as if constraints were the name */ public void addLayoutComponent(Component comp, Object constraints) { addLayoutComponent((String) constraints, comp); } /** * Returns the maximum size of this component. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Returns the alignment along the x axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentX(Container target) { return 0.5f; } /** * Returns the alignment along the y axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentY(Container target) { return 0.5f; } /** * Invalidates the layout, indicating that if the layout manager * has cached information it should be discarded. */ public void invalidateLayout(Container target) { invalidatePreCalc(); } public void invalidatePreCalc() { isPrecalculated = false; } }
wakeupthecat/gastona
pc/src/de/elxala/Eva/layout/EvaLayout.java
Java
gpl-3.0
36,814
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto 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. # Pycornetto 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/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <e.marsi@gmail.com>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h"
emsrc/pycornetto
bin/cornetto-client.py
Python
gpl-3.0
6,265
package tempconv // CToF converts a Celsius temperature to Fahrenheit func CToF(c Celsius) Fahrenheit { return Fahrenheit(c * 9 / 5 + 32) } // FToC converts s Fahrenheit temperature to Celsius func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
ptdecker/gobasics
src/ch02/tempconv/conv.go
GO
gpl-3.0
273
const { nativeImage } = require('electron') const { resolve } = require('path') exports.size16 = nativeImage.createFromPath(resolve(__dirname, '../icon16.png')) exports.size16.setTemplateImage(true)
Gerhut/Meibo
lib/icon.js
JavaScript
gpl-3.0
201
package yio.tro.antiyoy.menu.customizable_list; import com.badlogic.gdx.graphics.g2d.BitmapFont; import yio.tro.antiyoy.gameplay.diplomacy.DiplomaticEntity; import yio.tro.antiyoy.menu.render.AbstractRenderCustomListItem; import yio.tro.antiyoy.menu.render.MenuRender; import yio.tro.antiyoy.menu.scenes.Scenes; import yio.tro.antiyoy.menu.scenes.gameplay.choose_entity.IDipEntityReceiver; import yio.tro.antiyoy.stuff.Fonts; import yio.tro.antiyoy.stuff.GraphicsYio; public class SimpleDipEntityItem extends AbstractSingleLineItem{ public DiplomaticEntity diplomaticEntity; public int backgroundColor; @Override protected BitmapFont getTitleFont() { return Fonts.smallerMenuFont; } @Override protected double getHeight() { return 0.07f * GraphicsYio.height; } @Override protected void onClicked() { Scenes.sceneChooseDiplomaticEntity.onDiplomaticEntityChosen(diplomaticEntity); } public void setDiplomaticEntity(DiplomaticEntity diplomaticEntity) { this.diplomaticEntity = diplomaticEntity; backgroundColor = getGameController().colorsManager.getColorByFraction(diplomaticEntity.fraction); setTitle("" + diplomaticEntity.capitalName); } @Override public AbstractRenderCustomListItem getRender() { return MenuRender.renderSimpleDipEntityItem; } }
yiotro/Antiyoy
core/src/yio/tro/antiyoy/menu/customizable_list/SimpleDipEntityItem.java
Java
gpl-3.0
1,380
// ==++== // // Copyright (C) 2019 Matthias Fussenegger // // 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/>. // // ==--== namespace SimpleZIP_UI.Presentation.View.Model { /// <summary> /// Represents a list box item for the <see cref="MessageDigestPage"/>. /// </summary> public class MessageDigestModel { /// <summary> /// The name of the file whose hash value is to be displayed. /// </summary> public string FileName { get; } /// <summary> /// The physical location (full path) of the file. /// </summary> public string Location { get; } /// <summary> /// The calculated hash value of the file. /// </summary> public string HashValue { get; internal set; } /// <summary> /// Displays the location in the model if set to true. /// </summary> public BooleanModel IsDisplayLocation { get; set; } = false; /// <summary> /// Sets the color brush of the <see cref="FileName"/>. /// </summary> public SolidColorBrushModel FileNameColorBrush { get; set; } /// <summary> /// Constructs a new model for the ListBox in <see cref="MessageDigestPage"/>. /// </summary> /// <param name="fileName">The name of the file to be displayed.</param> /// <param name="location">The location of the file to be displayed.</param> /// <param name="hashValue">The hash value of the file to be displayed.</param> public MessageDigestModel(string fileName, string location, string hashValue) { FileName = fileName; Location = location; HashValue = hashValue; } } }
turbolocust/SimpleZIP
SimpleZIP_UI/Presentation/View/Model/MessageDigestModel.cs
C#
gpl-3.0
2,339
package standalone_tools; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Set; import framework.DataQuery; import framework.DiffComplexDetector; import framework.DiffComplexDetector.SPEnrichment; import framework.DiffSeedCombDetector; import framework.QuantDACOResultSet; import framework.Utilities; /** * CompleXChange cmd-tool * @author Thorsten Will */ public class CompleXChange { static String version_string = "CompleXChange 1.01"; private static String path_group1 = "[GROUP1-FOLDER]"; private static String path_group2 = "[GROUP2-FOLDER]"; private static Map<String, QuantDACOResultSet> group1; private static Map<String, QuantDACOResultSet> group2; private static String path_seed = "no seed file defined"; private static Set<String> seed = null; private static String output_folder; private static double FDR = 0.05; private static boolean parametric = false; private static boolean paired = false; private static boolean incorporate_supersets = false; private static double min_variant_fraction = 0.75; private static boolean human_readable = false; private static boolean also_seedcomb_calcs = false; private static boolean also_seed_enrich = false; private static boolean filter_allosome = false; private static int no_threads = Math.max(Runtime.getRuntime().availableProcessors() / 2, 1); // assuming HT/SMT systems /** * Reads all matching output pairs of JDACO results/major transcripts from a certain folder: * [folder]/[sample-string]_complexes.txt(.gz) and [folder]/[sample-string]_major-transcripts.txt(.gz) * @param folder * @return */ public static Map<String, QuantDACOResultSet> readQuantDACOComplexes(String folder) { Map<String, QuantDACOResultSet> data = new HashMap<>(); for (File f:Utilities.getAllSuffixMatchingFilesInSubfolders(folder, "_major-transcripts.txt")) { String gz = ""; if (f.getName().endsWith(".gz")) gz = ".gz"; String pre = f.getAbsolutePath().split("_major-transcripts")[0]; String sample = f.getName().split("_major-transcripts")[0]; QuantDACOResultSet qdr = new QuantDACOResultSet(pre + "_complexes.txt" + gz, seed, pre + "_major-transcripts.txt" + gz); data.put(sample, qdr); } return data; } /** * Prints the help message */ public static void printHelp() { System.out.println("usage: java -jar CompleXChange.jar ([OPTIONS]) [GROUP1-FOLDER] [GROUP2-FOLDER] [OUTPUT-FOLDER]"); System.out.println(); System.out.println("[OPTIONS] (optional) :"); System.out.println(" -fdr=[FDR] : false discovery rate (default: 0.05)"); System.out.println(" -mf=[MIN_VAR_FRACTION] : fraction of either group a complex must be part of to be considered in the analysis (default: 0.75)"); System.out.println(" -s=[SEED-FILE] : file listing proteins around which the complexes are centered, e.g. seed file used for JDACO complex predictions (default: none)"); System.out.println(" -t=[#threads] : number of threads to be used (default: #cores/2)"); System.out.println(" -nd : assume normal distribution when testing (default: no assumption, non-parametric tests applied)"); System.out.println(" -p : assume paired/dependent data (default: unpaired/independent tests applied)"); System.out.println(" -ss : also associate supersets in the analyses (default: no supersets)"); System.out.println(" -enr : determine seed proteins enriched in up/down-regulated complexes (as in GSEA)"); System.out.println(" -sc : additional analysis based on seed combinations rather than sole complexes (as in GSEA)"); System.out.println(" -hr : additionally output human readable files with gene names and rounded numbers (default: no output)"); System.out.println(" -f : filter complexes with allosome proteins (default: no filtering)"); System.out.println(); System.out.println("[GROUPx-FOLDER] :"); System.out.println(" Standard PPIXpress/JDACO-output is read from those folders. JDACO results and major transcripts are needed."); System.out.println(); System.out.println("[OUTPUT-FOLDER]"); System.out.println(" The outcome is written to this folder. If it does not exist, it is created."); System.out.println(); System.exit(0); } /** * Prints the version of the program */ public static void printVersion() { System.out.println(version_string); System.exit(0); } /** * Parse arguments * @param args */ public static void parseInput(String[] args) { for (String arg:args) { // help needed? if (arg.equals("-h") || arg.equals("-help")) printHelp(); // output version else if (arg.equals("-version")) printVersion(); // parse FDR else if (arg.startsWith("-fdr=")) FDR = Double.parseDouble(arg.split("=")[1]); // parse min_variant_fraction else if (arg.startsWith("-mf=")) min_variant_fraction = Double.parseDouble(arg.split("=")[1]); // add seed file else if (arg.startsWith("-s=")) { path_seed = arg.split("=")[1]; seed = Utilities.readEntryFile(path_seed); if (seed == null) System.exit(1); // error will be thrown by the utility-function if (seed.isEmpty()) { System.err.println("Seed file " + path_seed + " is empty."); System.exit(1); } } // parse #threads else if (arg.startsWith("-t=")) no_threads = Math.max(Integer.parseInt(arg.split("=")[1]), 1); // parametric? else if (arg.equals("-nd")) parametric = true; // paired? else if (arg.equals("-p")) paired = true; // supersets? else if (arg.equals("-ss")) incorporate_supersets = true; // seed combinations? else if (arg.equals("-sc")) also_seedcomb_calcs = true; // seed enrichment? else if (arg.equals("-enr")) also_seed_enrich = true; // output human readable files? else if (arg.equals("-hr")) human_readable = true; // filter allosome proteins? else if (arg.equals("-f")) filter_allosome = true; // read groupwise input else if (group1 == null) { path_group1 = arg; if (!path_group1.endsWith("/")) path_group1 += "/"; group1 = readQuantDACOComplexes(path_group1); } else if (group2 == null) { path_group2 = arg; if (!path_group2.endsWith("/")) path_group2 += "/"; group2 = readQuantDACOComplexes(path_group2); } // set output-folder else if (output_folder == null) { output_folder = arg; if (!output_folder.endsWith("/")) output_folder += "/"; } } // some final checks if (group1 == null || group1.isEmpty() || group2 == null || group2.isEmpty()) { if (group1 == null || group1.isEmpty()) System.err.println(path_group1 + " does not exist or contains no useable data."); if (group2 == null || group2.isEmpty()) System.err.println(path_group2 + " does not exist or contains no useable data."); System.exit(1); } if (group1.size() < 2 || group2.size() < 2) { if (group1.size() < 2) System.err.println(path_group1 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation."); if (group2.size() < 2) System.err.println(path_group2 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation."); System.exit(1); } if (output_folder == null) { System.err.println("Please add an output folder."); System.exit(1); } // check for invalid usage of seedcomb mode if (also_seedcomb_calcs && seed == null) { also_seedcomb_calcs = false; System.out.println("Analysis of seed combination variants in complexes requires a seed file, this additional analysis is skipped."); } if (also_seed_enrich && seed == null) { also_seed_enrich = false; System.out.println("Analysis of seed protein enrichment in complexes requires a seed file, this additional analysis is skipped."); } } public static void main(String[] args) { if (args.length == 1 && args[0].equals("-version")) printVersion(); if (args.length < 3) { printHelp(); } // parse cmd-line and set all parameters try { parseInput(args); } catch (Exception e) { System.out.println("Something went wrong while reading the command-line, please check your input!"); System.out.println(); printHelp(); } // preface if (group1.size() < 5 || group2.size() < 5) { System.out.println("Computations will run as intended, but be aware that at least five samples per group are recommended to gather meaningful results."); } System.out.println("Seed: " + path_seed); System.out.println("FDR: " + FDR); String test = "Wilcoxon rank sum test (unpaired, non-parametric)"; if (paired && parametric) test = "paired t-test (paired, parametric)"; else if (paired) test = "Wilcoxon signed-rank test (paired, non-parametric)"; else if (parametric) test = "Welch's unequal variances t-test (unpaired, parametric)"; System.out.println("Statistical test: " + test); System.out.println("Min. fraction: " + min_variant_fraction); System.out.println("Incorporate supersets: " + (incorporate_supersets ? "yes" : "no")); if (filter_allosome) { System.out.print("Filtering of complexes with allosome proteins enabled. Downloading data ... "); String db = DataQuery.getEnsemblOrganismDatabaseFromProteins(group1.values().iterator().next().getAbundantSeedProteins()); DataQuery.getAllosomeProteins(db); System.out.println("done."); } System.out.println(); // computations boolean output_to_write = false; System.out.println("Processing " + path_group1 + " (" + group1.keySet().size() + ") vs " + path_group2 + " (" + group2.keySet().size() + ") ..."); System.out.flush(); DiffComplexDetector dcd = new DiffComplexDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome); if (seed != null) System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() +" (" + dcd.getSignSortedVariants(false, false).size() + " seed combination variants) significant."); else System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() + " significant."); System.out.flush(); output_to_write = !dcd.getSignificanceSortedComplexes().isEmpty(); DiffSeedCombDetector dscd = null; if (also_seedcomb_calcs) { dscd = new DiffSeedCombDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome); System.out.println(dscd.getVariantsRawPValues().size() + " seed combinations tested, " + dscd.getSignificanceSortedVariants().size() + " significant."); if (!dscd.getSignificanceSortedVariants().isEmpty()) output_to_write = true; System.out.flush(); } SPEnrichment spe = null; if (seed == null && also_seed_enrich) { System.out.println("Please specify a seed protein file if seed protein enrichment should be determined."); System.out.flush(); } else if (seed != null && also_seed_enrich) { System.out.println("Calculating seed protein enrichment with 10000 permutations to approximate null distribution and only considering seed proteins participating in at least 10 complexes."); System.out.flush(); spe = dcd.calculateSPEnrichment(FDR, 10000, 10); if (!spe.getSignificanceSortedSeedProteins().isEmpty()) output_to_write = true; } /* * write file-output */ if (!output_to_write) { System.out.println("Since there is nothing to report, no output is written."); System.exit(0); } // check if output-folder exists, otherwise create it File f = new File(output_folder); if (!f.exists()) f.mkdir(); // write output files System.out.println("Writing results ..."); dcd.writeSignSortedComplexes(output_folder + "diff_complexes.txt", false); if (seed != null) { dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes.txt", false); if (also_seedcomb_calcs) dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations.txt", false); if (also_seed_enrich) spe.writeSignificantSeedProteins(output_folder + "enriched_seed_proteins.txt"); } if (human_readable) { System.out.println("Retrieving data on gene names ..."); System.out.flush(); System.out.println("Output human readable results ..."); dcd.writeSignSortedComplexes(output_folder + "diff_complexes_hr.txt", true); if (seed != null) { dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes_hr.txt", true); if (also_seedcomb_calcs) dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations_hr.txt", true); } } } }
edeltoaster/jdaco_dev
jdaco_dev/src/standalone_tools/CompleXChange.java
Java
gpl-3.0
12,876
// black-box testing package router_test import ( "testing" "github.com/kataras/iris" "github.com/kataras/iris/context" "github.com/kataras/iris/core/router" "github.com/kataras/iris/httptest" ) type testController struct { router.Controller } var writeMethod = func(c router.Controller) { c.Ctx.Writef(c.Ctx.Method()) } func (c *testController) Get() { writeMethod(c.Controller) } func (c *testController) Post() { writeMethod(c.Controller) } func (c *testController) Put() { writeMethod(c.Controller) } func (c *testController) Delete() { writeMethod(c.Controller) } func (c *testController) Connect() { writeMethod(c.Controller) } func (c *testController) Head() { writeMethod(c.Controller) } func (c *testController) Patch() { writeMethod(c.Controller) } func (c *testController) Options() { writeMethod(c.Controller) } func (c *testController) Trace() { writeMethod(c.Controller) } type ( testControllerAll struct{ router.Controller } testControllerAny struct{ router.Controller } // exactly same as All ) func (c *testControllerAll) All() { writeMethod(c.Controller) } func (c *testControllerAny) All() { writeMethod(c.Controller) } func TestControllerMethodFuncs(t *testing.T) { app := iris.New() app.Controller("/", new(testController)) app.Controller("/all", new(testControllerAll)) app.Controller("/any", new(testControllerAny)) e := httptest.New(t, app) for _, method := range router.AllMethods { e.Request(method, "/").Expect().Status(httptest.StatusOK). Body().Equal(method) e.Request(method, "/all").Expect().Status(httptest.StatusOK). Body().Equal(method) e.Request(method, "/any").Expect().Status(httptest.StatusOK). Body().Equal(method) } } type testControllerPersistence struct { router.Controller Data string `iris:"persistence"` } func (t *testControllerPersistence) Get() { t.Ctx.WriteString(t.Data) } func TestControllerPersistenceFields(t *testing.T) { data := "this remains the same for all requests" app := iris.New() app.Controller("/", &testControllerPersistence{Data: data}) e := httptest.New(t, app) e.GET("/").Expect().Status(httptest.StatusOK). Body().Equal(data) } type testControllerBeginAndEndRequestFunc struct { router.Controller Username string } // called before of every method (Get() or Post()). // // useful when more than one methods using the // same request values or context's function calls. func (t *testControllerBeginAndEndRequestFunc) BeginRequest(ctx context.Context) { t.Username = ctx.Params().Get("username") // or t.Params.Get("username") because the // t.Ctx == ctx and is being initialized before this "BeginRequest" } // called after every method (Get() or Post()). func (t *testControllerBeginAndEndRequestFunc) EndRequest(ctx context.Context) { ctx.Writef("done") // append "done" to the response } func (t *testControllerBeginAndEndRequestFunc) Get() { t.Ctx.Writef(t.Username) } func (t *testControllerBeginAndEndRequestFunc) Post() { t.Ctx.Writef(t.Username) } func TestControllerBeginAndEndRequestFunc(t *testing.T) { app := iris.New() app.Controller("/profile/{username}", new(testControllerBeginAndEndRequestFunc)) e := httptest.New(t, app) usernames := []string{ "kataras", "makis", "efi", "rg", "bill", "whoisyourdaddy", } doneResponse := "done" for _, username := range usernames { e.GET("/profile/" + username).Expect().Status(httptest.StatusOK). Body().Equal(username + doneResponse) e.POST("/profile/" + username).Expect().Status(httptest.StatusOK). Body().Equal(username + doneResponse) } }
EriconYu/stocksniper
src/vendor/github.com/kataras/iris/core/router/controller_test.go
GO
gpl-3.0
3,581
/* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2016 HydroloGIS (www.hydrologis.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.geopaparazzi.library.profiles.objects; import android.os.Parcel; import android.os.Parcelable; import eu.geopaparazzi.library.network.download.IDownloadable; /** * Created by hydrologis on 19/03/18. */ public class ProfileOtherfiles extends ARelativePathResource implements Parcelable, IDownloadable { public String url = ""; public String modifiedDate = ""; public long size = -1; private String destinationPath = ""; public ProfileOtherfiles() { } protected ProfileOtherfiles(Parcel in) { url = in.readString(); modifiedDate = in.readString(); size = in.readLong(); destinationPath = in.readString(); } public static final Creator<ProfileOtherfiles> CREATOR = new Creator<ProfileOtherfiles>() { @Override public ProfileOtherfiles createFromParcel(Parcel in) { return new ProfileOtherfiles(in); } @Override public ProfileOtherfiles[] newArray(int size) { return new ProfileOtherfiles[size]; } }; @Override public long getSize() { return size; } @Override public String getUrl() { return url; } @Override public String getDestinationPath() { return destinationPath; } @Override public void setDestinationPath(String path) { destinationPath = path; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(url); dest.writeString(modifiedDate); dest.writeLong(size); dest.writeString(destinationPath); } }
geopaparazzi/geopaparazzi
geopaparazzi_library/src/main/java/eu/geopaparazzi/library/profiles/objects/ProfileOtherfiles.java
Java
gpl-3.0
2,473
#from moderation import moderation #from .models import SuccessCase #moderation.register(SuccessCase)
djangobrasil/djangobrasil.org
src/djangobrasil/success_cases/moderator.py
Python
gpl-3.0
104
document.addEventListener("DOMContentLoaded", function(event) { if (/android|blackberry|iPhone|iPad|iPod|webOS/i.test(navigator.userAgent) === false) { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { el.parentNode.addEventListener('mouseenter', animateTypeText); el.parentNode.addEventListener('mouseleave', destroyTypeText); }); } else { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { removeClass(el, 'link-descr'); }); } }); var addClass = function(elem, add_class) { elem.setAttribute("class", elem.getAttribute("class") + ' ' + add_class); }; var removeClass = function(elem, rem_class) { var origClass = elem.getAttribute("class"); var remClassRegex = new Regexp("(\\s*)"+rem_class+"(\\s*)"); var classMatch = origClass.match(remClassRegex); var replaceString = ''; if (classMatch[1].length > 0 || classMatch[2].length > 0) { replaceString = ' '; } var newClass = origClass.replace(remClassRegex, replaceString); elem.setAttribute("class", newClass); }; var animateTypeText = function() { var elem = this; var typeArea = document.createElement("span"); typeArea.setAttribute("class", "link-subtext"); elem.insertBefore(typeArea, elem.querySelector("span:last-of-type")); setTimeout(addLetter(elem), 40); }; var addLetter = function(elem) { // if (elem.parentElement.querySelector(":hover") === elem) { var subtextSpan = elem.querySelector(".link-subtext"); var descrText = elem.querySelector(".link-descr").textContent; if (subtextSpan === null) { return; } var currentText = subtextSpan.textContent.slice(0,-1); var currentPos = currentText.length; subtextSpan.textContent = currentText + descrText.slice(currentPos, currentPos+1) + "\u258B"; if (currentText.length < descrText.length) { setTimeout(function(){addLetter(elem)}, 40); } // } }; var destroyTypeText = function() { var elem = this; elem.removeChild(elem.querySelector('.link-subtext')); };
thedanielgray/thedanielgray.github.io
js/gray.js
JavaScript
gpl-3.0
2,070
package de.turnierverwaltung.control.settingsdialog; import java.awt.Dialog; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.sql.SQLException; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import de.turnierverwaltung.control.ExceptionHandler; import de.turnierverwaltung.control.MainControl; import de.turnierverwaltung.control.Messages; import de.turnierverwaltung.control.PropertiesControl; import de.turnierverwaltung.control.ratingdialog.DWZListToSQLITEControl; import de.turnierverwaltung.control.ratingdialog.ELOListToSQLITEControl; import de.turnierverwaltung.control.sqlite.SaveTournamentControl; import de.turnierverwaltung.model.TournamentConstants; import de.turnierverwaltung.view.settingsdialog.SettingsView; import say.swing.JFontChooser; public class ActionListenerSettingsControl { private final MainControl mainControl; private final SettingsControl esControl; private JDialog dialog; public ActionListenerSettingsControl(final MainControl mainControl, final SettingsControl esControl) { super(); this.mainControl = mainControl; this.esControl = esControl; addPropertiesActionListener(); } public void addActionListeners() { esControl.getEigenschaftenView().getFontChooserButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final JFontChooser fontChooser = esControl.getEigenschaftenView().getFontChooser(); fontChooser.setSelectedFont(mainControl.getPropertiesControl().getFont()); final int result = fontChooser.showDialog(esControl.getEigenschaftenView()); if (result == JFontChooser.OK_OPTION) { final Font selectedFont = fontChooser.getSelectedFont(); MainControl.setUIFont(selectedFont); mainControl.getPropertiesControl().setFont(selectedFont); mainControl.getPropertiesControl().writeProperties(); } } }); esControl.getEigenschaftenView().getOkButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { mainControl.getPropertiesControl().writeSettingsDialogProperties(dialog.getBounds().x, dialog.getBounds().y, dialog.getBounds().width, dialog.getBounds().height); dialog.dispose(); final PropertiesControl ppC = mainControl.getPropertiesControl(); final SettingsView settingsView = esControl.getEigenschaftenView(); ppC.setTableComumnBlack(settingsView.getBlackTextField().getText()); ppC.setTableComumnWhite(settingsView.getWhiteTextField().getText()); ppC.setTableComumnMeeting(settingsView.getMeetingTextField().getText()); ppC.setTableComumnNewDWZ(settingsView.getNewDWZTextField().getText()); ppC.setTableComumnOldDWZ(settingsView.getOldDWZTextField().getText()); ppC.setTableComumnNewELO(settingsView.getNewELOTextField().getText()); ppC.setTableComumnOldELO(settingsView.getOldELOTextField().getText()); ppC.setTableComumnPlayer(settingsView.getPlayerTextField().getText()); ppC.setTableComumnPoints(settingsView.getPointsTextField().getText()); ppC.setTableComumnRanking(settingsView.getRankingTextField().getText()); ppC.setTableComumnResult(settingsView.getResultTextField().getText()); ppC.setTableComumnSonnebornBerger(settingsView.getSbbTextField().getText()); ppC.setTableComumnRound(settingsView.getRoundTextField().getText()); ppC.setSpielfrei(settingsView.getSpielfreiTextField().getText()); if (mainControl.getPlayerListControl() != null) { mainControl.getPlayerListControl().testPlayerListForDoubles(); } ppC.setCutForename(settingsView.getForenameLengthBox().getValue()); ppC.setCutSurname(settingsView.getSurnameLengthBox().getValue()); ppC.setWebserverPath(settingsView.getWebserverPathTextField().getText()); ppC.checkCrossTableColumnForDoubles(); ppC.checkMeetingTableColumnForDoubles(); ppC.setCSSTable(settingsView.getTableCSSTextField().getText()); ppC.writeProperties(); esControl.setTableColumns(); } }); esControl.getEigenschaftenView().getOpenVereineCSVButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // vereine.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("CSV file", "csv", "CSV"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToVereineCVS(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS()); } } }); esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final DWZListToSQLITEControl dwzL = new DWZListToSQLITEControl(mainControl); dwzL.convertDWZListToSQLITE(); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } }); esControl.getEigenschaftenView().getOpenPlayersCSVButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // spieler.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("CSV or SQLite file", "csv", "CSV", "sqlite", "SQLite"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToPlayersCSV(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); final String filename = file.getName(); final int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true); } } } } }); esControl.getEigenschaftenView().getConvertELOToSQLITEButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final ELOListToSQLITEControl eloL = new ELOListToSQLITEControl(mainControl); eloL.convertELOListToSQLITE(); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } }); esControl.getEigenschaftenView().getOpenPlayersELOButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // spieler.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("TXT or SQLite file", "txt", "TXT", "sqlite", "SQLite"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToPlayersELO(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); final String filename = file.getName(); final int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true); } } } } }); esControl.getEigenschaftenView().getOpenDefaultPathButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setMultiSelectionEnabled(false); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setDefaultPath(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenDefaultPathLabel(mainControl.getPropertiesControl().getDefaultPath()); } } }); esControl.getEigenschaftenView() .setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS()); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); esControl.getEigenschaftenView().getGermanLanguageCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { mainControl.getLanguagePropertiesControl().setLanguageToGerman(); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getEnglishLanguageCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { mainControl.getLanguagePropertiesControl().setLanguageToEnglish(); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getSpielerListeAuswahlBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int anzahlProTab = esControl.getEigenschaftenView().getSpielerListeAuswahlBox() .getSelectedIndex(); mainControl.getPropertiesControl().setSpielerProTab(anzahlProTab); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getTurnierListeAuswahlBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final int anzahlProTab = esControl.getEigenschaftenView().getTurnierListeAuswahlBox() .getSelectedIndex(); mainControl.getPropertiesControl().setTurniereProTab(anzahlProTab); mainControl.getPropertiesControl().writeProperties(); } }); String filename = mainControl.getPropertiesControl().getPathToPlayersELO(); int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true); } } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } filename = mainControl.getPropertiesControl().getPathToPlayersCSV(); positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true); } } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } esControl.getEigenschaftenView().getResetPropertiesButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int abfrage = beendenHinweis(); if (abfrage > 0) { if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) { if (mainControl.getChangedGames().isEmpty() == false) { final SaveTournamentControl saveTournament = new SaveTournamentControl(mainControl); try { saveTournament.saveChangedPartien(); } catch (final SQLException e1) { final ExceptionHandler eh = new ExceptionHandler(mainControl); eh.fileSQLError(e1.getMessage()); } } } } mainControl.getPropertiesControl().resetProperties(); mainControl.getPropertiesControl().writeProperties(); JOptionPane.showMessageDialog(null, Messages.getString("EigenschaftenControl.29"), Messages.getString("EigenschaftenControl.28"), JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }); } private void addPropertiesActionListener() { mainControl.getNaviView().getPropertiesButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { mainControl.getSettingsControl().setEigenschaftenView(new SettingsView()); final SettingsView eigenschaftenView = mainControl.getSettingsControl().getEigenschaftenView(); mainControl.getSettingsControl().setItemListenerControl( new ItemListenerSettingsControl(mainControl, mainControl.getSettingsControl())); mainControl.getSettingsControl().getItemListenerControl().addItemListeners(); if (dialog == null) { dialog = new JDialog(); } else { dialog.dispose(); dialog = new JDialog(); } // dialog.setAlwaysOnTop(true); dialog.getContentPane().add(eigenschaftenView); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setBounds(mainControl.getPropertiesControl().getSettingsDialogX(), mainControl.getPropertiesControl().getSettingsDialogY(), mainControl.getPropertiesControl().getSettingsDialogWidth(), mainControl.getPropertiesControl().getSettingsDialogHeight()); dialog.setEnabled(true); if (mainControl.getPropertiesControl() == null) { mainControl.setPropertiesControl(new PropertiesControl(mainControl)); } final PropertiesControl ppC = mainControl.getPropertiesControl(); ppC.readProperties(); eigenschaftenView.getCheckBoxHeaderFooter().setSelected(ppC.getOnlyTables()); eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ()); eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(ppC.getNoFolgeDWZ()); eigenschaftenView.getCheckBoxohneELO().setSelected(ppC.getNoELO()); eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(ppC.getNoFolgeELO()); eigenschaftenView.getSpielerListeAuswahlBox().setSelectedIndex(ppC.getSpielerProTab()); eigenschaftenView.getTurnierListeAuswahlBox().setSelectedIndex(ppC.getTurniereProTab()); eigenschaftenView.getForenameLengthBox().setValue(ppC.getCutForename()); eigenschaftenView.getSurnameLengthBox().setValue(ppC.getCutSurname()); eigenschaftenView.getWebserverPathTextField().setText(ppC.getWebserverPath()); // eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ()); eigenschaftenView.getCheckBoxhtmlToClipboard().setSelected(ppC.gethtmlToClipboard()); if (eigenschaftenView.getCheckBoxohneDWZ().isSelected() == true) { eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(true); eigenschaftenView.getCheckBoxohneFolgeDWZ().setEnabled(false); ppC.setNoFolgeDWZ(true); } if (eigenschaftenView.getCheckBoxohneELO().isSelected() == true) { eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(true); eigenschaftenView.getCheckBoxohneFolgeELO().setEnabled(false); ppC.setNoFolgeELO(true); } eigenschaftenView.getCheckBoxPDFLinks().setSelected(ppC.getPDFLinks()); eigenschaftenView.getWebserverPathTextField().setEnabled(ppC.getPDFLinks()); if (mainControl.getPropertiesControl().getLanguage().equals("german")) { //$NON-NLS-1$ eigenschaftenView.getGermanLanguageCheckBox().setSelected(true); eigenschaftenView.getEnglishLanguageCheckBox().setSelected(false); mainControl.getLanguagePropertiesControl().setLanguageToGerman(); } else if (mainControl.getPropertiesControl().getLanguage().equals("english")) { //$NON-NLS-1$ eigenschaftenView.getGermanLanguageCheckBox().setSelected(false); eigenschaftenView.getEnglishLanguageCheckBox().setSelected(true); mainControl.getLanguagePropertiesControl().setLanguageToEnglish(); } eigenschaftenView.setOpenDefaultPathLabel(ppC.getDefaultPath()); eigenschaftenView.getTableCSSTextField().setText(ppC.getCSSTable()); esControl.setTableColumns(); addActionListeners(); esControl.getItemListenerControl().addItemListeners(); dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); dialog.setVisible(true); } }); } private int beendenHinweis() { int abfrage = 0; if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) { if (mainControl.getChangedGames().isEmpty() == false) { final String hinweisText = Messages.getString("NaviController.21") //$NON-NLS-1$ + Messages.getString("NaviController.22") //$NON-NLS-1$ + Messages.getString("NaviController.33"); //$NON-NLS-1$ abfrage = 1; // Custom button text final Object[] options = { Messages.getString("NaviController.24"), //$NON-NLS-1$ Messages.getString("NaviController.25") }; //$NON-NLS-1$ abfrage = JOptionPane.showOptionDialog(mainControl, hinweisText, Messages.getString("NaviController.26"), //$NON-NLS-1$ JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); } } return abfrage; } }
mars7105/JKLubTV
src/de/turnierverwaltung/control/settingsdialog/ActionListenerSettingsControl.java
Java
gpl-3.0
18,976
namespace Ribbonizer.Ribbon { using System.Collections.Generic; using System.Linq; using Ribbonizer.Ribbon.DefinitionValidation; using Ribbonizer.Ribbon.Tabs; internal class RibbonInitializer : IRibbonInitializer { private readonly IEnumerable<IRibbonDefinitionValidator> definitionValidators; private readonly IRibbonTabViewCacheInitializer tabViewCacheInitializer; public RibbonInitializer(IEnumerable<IRibbonDefinitionValidator> definitionValidators, IRibbonTabViewCacheInitializer tabViewCacheInitializer) { this.definitionValidators = definitionValidators; this.tabViewCacheInitializer = tabViewCacheInitializer; } public void InitializeRibbonViewTree() { IEnumerable<IRibbonDefinitionViolation> violations = this.definitionValidators .SelectMany(x => x.Validate()) .ToList(); if (violations.Any()) { throw new RibbonDefinitionViolationException(violations); } this.tabViewCacheInitializer.InitializeCache(); } } }
BrunoJuchli/RibbonizerSample
Ribbonizer/Ribbon/RibbonInitializer.cs
C#
gpl-3.0
1,152
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015 Satpy developers # # This file is part of satpy. # # satpy 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. # # satpy 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 # satpy. If not, see <http://www.gnu.org/licenses/>. """Fetch avhrr calibration coefficients.""" import datetime as dt import os.path import sys import h5py import urllib2 BASE_URL = "http://www.star.nesdis.noaa.gov/smcd/spb/fwu/homepage/" + \ "AVHRR/Op_Cal_AVHRR/" URLS = { "Metop-B": {"ch1": BASE_URL + "Metop1_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "Metop1_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "Metop1_AVHRR_Libya_ch3a.txt"}, "Metop-A": {"ch1": BASE_URL + "Metop2_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "Metop2_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "Metop2_AVHRR_Libya_ch3a.txt"}, "NOAA-16": {"ch1": BASE_URL + "N16_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N16_AVHRR_Libya_ch2.txt"}, "NOAA-17": {"ch1": BASE_URL + "N17_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N17_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "N17_AVHRR_Libya_ch3a.txt"}, "NOAA-18": {"ch1": BASE_URL + "N18_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N18_AVHRR_Libya_ch2.txt"}, "NOAA-19": {"ch1": BASE_URL + "N19_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N19_AVHRR_Libya_ch2.txt"} } def get_page(url): """Retrieve the given page.""" return urllib2.urlopen(url).read() def get_coeffs(page): """Parse coefficients from the page.""" coeffs = {} coeffs['datetime'] = [] coeffs['slope1'] = [] coeffs['intercept1'] = [] coeffs['slope2'] = [] coeffs['intercept2'] = [] slope1_idx, intercept1_idx, slope2_idx, intercept2_idx = \ None, None, None, None date_idx = 0 for row in page.lower().split('\n'): row = row.split() if len(row) == 0: continue if row[0] == 'update': # Get the column indices from the header line slope1_idx = row.index('slope_lo') intercept1_idx = row.index('int_lo') slope2_idx = row.index('slope_hi') intercept2_idx = row.index('int_hi') continue if slope1_idx is None: continue # In some cases the fields are connected, skip those rows if max([slope1_idx, intercept1_idx, slope2_idx, intercept2_idx]) >= len(row): continue try: dat = dt.datetime.strptime(row[date_idx], "%m/%d/%Y") except ValueError: continue coeffs['datetime'].append([dat.year, dat.month, dat.day]) coeffs['slope1'].append(float(row[slope1_idx])) coeffs['intercept1'].append(float(row[intercept1_idx])) coeffs['slope2'].append(float(row[slope2_idx])) coeffs['intercept2'].append(float(row[intercept2_idx])) return coeffs def get_all_coeffs(): """Get all available calibration coefficients for the satellites.""" coeffs = {} for platform in URLS: if platform not in coeffs: coeffs[platform] = {} for chan in URLS[platform].keys(): url = URLS[platform][chan] print(url) page = get_page(url) coeffs[platform][chan] = get_coeffs(page) return coeffs def save_coeffs(coeffs, out_dir=''): """Save calibration coefficients to HDF5 files.""" for platform in coeffs.keys(): fname = os.path.join(out_dir, "%s_calibration_data.h5" % platform) fid = h5py.File(fname, 'w') for chan in coeffs[platform].keys(): fid.create_group(chan) fid[chan]['datetime'] = coeffs[platform][chan]['datetime'] fid[chan]['slope1'] = coeffs[platform][chan]['slope1'] fid[chan]['intercept1'] = coeffs[platform][chan]['intercept1'] fid[chan]['slope2'] = coeffs[platform][chan]['slope2'] fid[chan]['intercept2'] = coeffs[platform][chan]['intercept2'] fid.close() print("Calibration coefficients saved for %s" % platform) def main(): """Create calibration coefficient files for AVHRR.""" out_dir = sys.argv[1] coeffs = get_all_coeffs() save_coeffs(coeffs, out_dir=out_dir) if __name__ == "__main__": main()
pytroll/satpy
utils/fetch_avhrr_calcoeffs.py
Python
gpl-3.0
4,773
<?php /** * Belgian Scouting Web Platform * Copyright (C) 2014 Julien Dupuis * * This code is licensed under the GNU General Public License. * * This is free software, and you are welcome to redistribute it * under under the terms of the GNU General Public License. * * It is distributed without any warranty; without even the * implied warranty of merchantability or fitness for a particular * purpose. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ /** * This Eloquent class represents a privilege of a leader * * Columns: * - operation: A string representing which operation this privilege allows * - scope: 'S' if the privilege is limited to the leader's section, 'U' for unit if they can use this privilege on any section * - member_id: The leader affected by this privilege * * Note : predefined privileges are privileges that can be automatically applied to classes * of members : * A: Simple leader * R: Leader in charge / Section webmaster * S: Unit co-leader * U: Unit main leader */ class Privilege extends Eloquent { var $guarded = array('id', 'created_at', 'updated_at'); // Following are all the privileges with // - id: the string representing the privilege // - text: a textual description of the privilege // - section: true if this privilege can be applied to only a section, false if it is a global privilige // - predefined: in which predefined classes it will be applied public static $UPDATE_OWN_LISTING_ENTRY = array( 'id' => 'Update own listing entry', 'text' => 'Modifier ses données personnelles dans le listing', 'section' => false, 'predefined' => "ARSU" ); public static $EDIT_PAGES = array( 'id' => 'Edit pages', 'text' => 'Modifier les pages #delasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_SECTION_EMAIL_AND_SUBGROUP = array( 'id' => "Edit section e-mail address and subgroup name", 'text' => "Changer l'adresse e-mail #delasection", 'section' => true, 'predefined' => "RSU" ); public static $EDIT_CALENDAR = array( 'id' => "Edit calendar", 'text' => 'Modifier les entrées du calendrier #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_ATTENDANCE = array( 'id' => "Manage attendance", 'text' => 'Cocher les présences aux activités #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_EVENT_PAYMENTS = array( 'id' => "Manage event payments", 'text' => 'Cocher le paiement des membres pour les activités #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $EDIT_NEWS = array( 'id' => "Edit news", 'text' => 'Poster des nouvelles (actualités) pour #lasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_DOCUMENTS = array( 'id' => "Edit documents", 'text' => 'Modifier les documents #delasection', 'section' => true, 'predefined' => "RSU" ); public static $SEND_EMAILS = array( 'id' => "Send e-mails", 'text' => 'Envoyer des e-mails aux membres #delasection', 'section' => true, 'predefined' => "RSU" ); public static $POST_PHOTOS = array( 'id' => "Post photos", 'text' => 'Ajouter/supprimer des photos pour #lasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_ACCOUNTING = array( 'id' => "Manage accounting", 'text' => 'Gérer les comptes #delasection', 'section' => true, 'predefined' => "RSU" ); public static $SECTION_TRANSFER = array( 'id' => "Section transfer", 'text' => "Changer les scouts de section", 'section' => false, 'predefined' => "SU", ); public static $EDIT_LISTING_LIMITED = array( 'id' => "Edit listing limited", 'text' => 'Modifier les données non sensibles du listing #delasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_LISTING_ALL = array( 'id' => "Edit listing all", 'text' => 'Modifier les données sensibles du listing #delasection', 'section' => true, 'predefined' => "U" ); public static $VIEW_HEALTH_CARDS = array( 'id' => "View health cards", 'text' => 'Consulter les fiches santé #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $EDIT_LEADER_PRIVILEGES = array( 'id' => "Edit leader privileges", 'text' => 'Changer les privilèges des animateurs #delasection', 'section' => true, 'predefined' => "RSU" ); public static $UPDATE_PAYMENT_STATUS = array( 'id' => "Update payment status", 'text' => 'Modifier le statut de paiement', 'section' => false, 'predefined' => "SU" ); public static $MANAGE_ANNUAL_FEAST_REGISTRATION = array( 'id' => "Manage annual feast registration", 'text' => "Valider les inscriptions pour la fête d'unité", 'section' => false, 'predefined' => "SU" ); public static $MANAGE_SUGGESIONS = array( 'id' => "Manage suggestions", 'text' => "Répondre aux suggestions et les supprimer", 'section' => false, 'predefined' => "SU" ); public static $EDIT_GLOBAL_PARAMETERS = array( 'id' => "Edit global parameters", 'text' => "Changer les paramètres du site", 'section' => false, 'predefined' => "U" ); public static $EDIT_STYLE = array( 'id' => "Edit style", 'text' => "Modifier le style du site", 'section' => false, 'predefined' => "U" ); public static $MANAGE_SECTIONS = array( 'id' => "Manage sections", 'text' => "Créer, modifier et supprimer les sections", 'section' => false, 'predefined' => "U" ); public static $DELETE_USERS = array( 'id' => "Delete users", 'text' => "Supprimer des comptes d'utilisateurs", 'section' => false, 'predefined' => "U" ); public static $DELETE_GUEST_BOOK_ENTRIES = array( 'id' => "Delete guest book entries", 'text' => "Supprimer des entrées du livre d'or", 'section' => false, 'predefined' => "U" ); /** * Returns the list of privileges */ public static function getPrivilegeList() { return array( self::$UPDATE_OWN_LISTING_ENTRY, self::$EDIT_CALENDAR, self::$MANAGE_ATTENDANCE, self::$MANAGE_EVENT_PAYMENTS, self::$POST_PHOTOS, self::$VIEW_HEALTH_CARDS, self::$EDIT_PAGES, self::$EDIT_DOCUMENTS, self::$EDIT_NEWS, self::$SEND_EMAILS, self::$EDIT_SECTION_EMAIL_AND_SUBGROUP, self::$MANAGE_ACCOUNTING, self::$SECTION_TRANSFER, self::$EDIT_LISTING_LIMITED, self::$EDIT_LEADER_PRIVILEGES, self::$MANAGE_ANNUAL_FEAST_REGISTRATION, self::$MANAGE_SUGGESIONS, self::$UPDATE_PAYMENT_STATUS, self::$EDIT_LISTING_ALL, self::$EDIT_GLOBAL_PARAMETERS, self::$EDIT_STYLE, self::$MANAGE_SECTIONS, self::$DELETE_GUEST_BOOK_ENTRIES, self::$DELETE_USERS, ); } /** * Returns the list of privileges sorted in 4 categories * * @param boolean $forSection Whether this is for a section leader or a unit leader */ public static function getPrivilegeArrayByCategory($forSection = false) { // The four categories $basicPrivileges = array(); $leaderInChargePrivileges = array(); $unitTeamPrivileges = array(); $unitLeaderPrivileges = array(); // Sort privileges into categories foreach (self::getPrivilegeList() as $privilege) { if (strpos($privilege['predefined'], "A") !== false) { if ($forSection) { if ($privilege['section']) { $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'S'); $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } else { $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } else { if ($privilege['section']) $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); else $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } elseif (strpos($privilege['predefined'], "R") !== false) { if ($forSection) { if ($privilege['section']) { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'S'); $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } else { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } else { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } elseif (strpos($privilege['predefined'], "S") !== false) { $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } elseif (strpos($privilege['predefined'], "U") !== false) { $unitLeaderPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } // Return list of categories return array( "Gestion de base" => $basicPrivileges, "Gestion avancée" => $leaderInChargePrivileges, "Gestion de l'unité" => $unitTeamPrivileges, "Gestion avancée de l'unité" => $unitLeaderPrivileges, ); } /** * Sets and saves all the privileges from the base category to the given leader */ public static function addBasePrivilegesForLeader($leader) { foreach (self::getPrivilegeList() as $privilege) { if (strpos($privilege['predefined'], "A") !== false) { try { Privilege::create(array( 'operation' => $privilege['id'], 'scope' => $privilege['section'] ? 'S' : 'U', 'member_id' => $leader->id, )); } catch (Exception $e) { Log::error($e); } } } } /** * Sets ($state = true) or unsets ($state = false) and saves a privilege for a leader in a given scope */ public static function set($operation, $scope, $leaderId, $state) { // Find existing privilege $privilege = Privilege::where('operation', '=', $operation) ->where('scope', '=', $scope) ->where('member_id', '=', $leaderId) ->first(); if ($privilege && !$state) { // Privilege exists and should be removed $privilege->delete(); } elseif (!$privilege && $state) { // Privilege does not exist and should be created Privilege::create(array( 'operation' => $operation, 'scope' => $scope, 'member_id' => $leaderId, )); } } }
juldup/scouting-web-platform
app/models/Privilege.php
PHP
gpl-3.0
11,158
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2155'; $TAGCLEAR='A<?php[^}]{1,600}}}define([\'"]startTime[\'"],getTime());if(!function_exists([\'"]shellexec[\'"])){functions+shellexec($cmd){'; $TAGBASE64='QTw/cGhwW159XXsxLDYwMH19fWRlZmluZShbXCciXXN0YXJ0VGltZVtcJyJdLGdldFRpbWUoKSk7aWYoIWZ1bmN0aW9uX2V4aXN0cyhbXCciXXNoZWxsZXhlY1tcJyJdKSl7ZnVuY3Rpb25zK3NoZWxsZXhlYygkY21kKXs='; $TAGHEX='413c3f7068705b5e7d5d7b312c3630307d7d7d646566696e65285b5c27225d737461727454696d655b5c27225d2c67657454696d652829293b6966282166756e6374696f6e5f657869737473285b5c27225d7368656c6c657865635b5c27225d29297b66756e6374696f6e732b7368656c6c657865632824636d64297b'; $TAGHEXPHP=''; $TAGURI='A%3C%3Fphp%5B%5E%7D%5D%7B1%2C600%7D%7D%7Ddefine%28%5B%5C%27%22%5DstartTime%5B%5C%27%22%5D%2CgetTime%28%29%29%3Bif%28%21function_exists%28%5B%5C%27%22%5Dshellexec%5B%5C%27%22%5D%29%29%7Bfunctions%2Bshellexec%28%24cmd%29%7B'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='10/09/2019'; $LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2155 '; $ACTIVED='1'; $VSTATR='malware_signature';
libre/webexploitscan
wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-2155-malware_signature.php
PHP
gpl-3.0
1,524
#define TYPEDEPARGS 0, 1, 2, 3 #define SINGLEARGS #define REALARGS #define OCTFILENAME comp_ufilterbankheapint // change to filename #define OCTFILEHELP "This function calls the C-library\n\ phase=comp_ufilterbankheapint(s,tgrad,fgrad,cfreq,a,do_real,tol,phasetype)\n Yeah." #include "ltfat_oct_template_helper.h" static inline void fwd_ufilterbankheapint( const double s[], const double tgrad[], const double fgrad[], const double cfreq[], ltfat_int a, ltfat_int M, ltfat_int L, ltfat_int W, int do_real, double tol, int phasetype, double phase[]) { if (phasetype == 1) ltfat_ufilterbankheapint_d( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); else ltfat_ufilterbankheapint_relgrad_d( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); } static inline void fwd_ufilterbankheapint( const float s[], const float tgrad[], const float fgrad[], const float cfreq[], ltfat_int a, ltfat_int M, ltfat_int L, ltfat_int W, int do_real, float tol, int phasetype, float phase[]) { if (phasetype == 1) ltfat_ufilterbankheapint_s( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); else ltfat_ufilterbankheapint_relgrad_s( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); } template <class LTFAT_TYPE, class LTFAT_REAL, class LTFAT_COMPLEX> octave_value_list octFunction(const octave_value_list& args, int nargout) { // Input data MArray<LTFAT_REAL> s = ltfatOctArray<LTFAT_REAL>(args(0)); MArray<LTFAT_REAL> tgrad = ltfatOctArray<LTFAT_REAL>(args(1)); MArray<LTFAT_REAL> fgrad = ltfatOctArray<LTFAT_REAL>(args(2)); MArray<LTFAT_REAL> cfreq = ltfatOctArray<LTFAT_REAL>(args(3)); octave_idx_type a = args(4).int_value(); octave_idx_type do_real = args(5).int_value(); double tol = args(6).double_value(); octave_idx_type phasetype = args(7).int_value(); octave_idx_type M = s.columns(); octave_idx_type N = s.rows(); octave_idx_type W = 1; octave_idx_type L = (octave_idx_type)( N * a); // phasetype--; MArray<LTFAT_REAL> phase(dim_vector(N, M, W)); fwd_ufilterbankheapint( s.data(), tgrad.data(), fgrad.data(), cfreq.data(), a, M, L, W, do_real, tol, phasetype, phase.fortran_vec()); return octave_value(phase); }
ltfat/ltfat
oct/comp_ufilterbankheapint.cc
C++
gpl-3.0
2,458