content
stringlengths
10
4.9M
/** * Loads the FONTS into cache for quick lookup. This also tries to find all fonts automatically via their font file */ public static void init() { if (!initDone) { String[] fonts = GenericsUtil.getFields(); for (String fontsClassPath : fonts) { try { MfbTypeface typeface = (MfbTypeface) Class.forName(fontsClassPath).getDeclaredConstructor().newInstance(); validateFont(typeface); FONTS.put(typeface.getMappingPrefix(), typeface); logHelper.logDebug("Typeface = %{public}s", typeface.getAuthor()); } catch (ClassNotFoundException e) { logHelper.logDebug("%{public}s not found.", fontsClassPath); } catch (Exception e) { logHelper.logDebug("Can't init: %{public}s", fontsClassPath); } } logHelper.logDebug("Total font = %{public}d", FONTS.size()); initDone = true; } }
/* * File: typedefs.h * Author: <NAME> * * Description: Contains the required typedefs. */ #ifndef _TYPEDEFS #define _TYPEDEFS #include <stdio.h> #include <math.h> /* ----- CONSTANTS --------------------------------------------------------- */ #define Pi 3.141592653589793239 #define radiansPerDegree 0.017453292519943 #define MATRIX_SIZE 4 #define MAX_NUM_OBJS 50 #define SMALL_STEP 0.0001 #define MIRROR_AMOUNT 2 /* ----- TYPE DECLARATIONS ------------------------------------------------- */ /* ** this a record structure for storing colour info. */ typedef struct { float red, green, blue; } RGBColour; /* ** this a record structure that contains a 3D vector (x, y, z). ** ** Note - if w == 1 then it represents a point. ** if w == 0 then it represents a vector. */ typedef struct _Vector { float x, y, z, w; } Vector; /* ray is defined by a point and a direction */ typedef struct _Ray { Vector start; Vector direction; } RayDef; typedef struct _Matrix { float element[MATRIX_SIZE][MATRIX_SIZE]; } Matrix; typedef struct _LightSource { Vector position; RGBColour colour; } LightSourceDef; typedef struct { float t_value; float *object; Vector intersection; Vector normal; } intersection_data; /* See Fileio.c to see how to access the values in the array of objects */ typedef struct _ObjectsDef { RGBColour diffuse_colour; RGBColour specular_colour; float phong; /* the phong coefficient */ Matrix transform; Matrix inverse_t; Matrix inverse_transpose; } ObjectsDef; #endif /* _TYPEDEFS */
main = do n <- readLn::IO Int interview <- getLine let process [] = [] process ('o':'g':'o':str) = '*':process' str process (c:str) = c:process str process' [] = [] process' ('g':'o':str) = process' str process' str = process str putStr . concat . map trans $ process interview where trans '*' = "***" trans c = [c]
<reponame>gpeter12/amuse #include "amuse/SoundMacroState.hpp" #include <cmath> #include <cstring> #include "amuse/AudioGroup.hpp" #include "amuse/AudioGroupPool.hpp" #include "amuse/Common.hpp" #include "amuse/Engine.hpp" #include "amuse/Voice.hpp" using namespace std::literals; /* C++17 will error out if an offsetof cannot be computed, so ignore this warning */ #pragma GCC diagnostic ignored "-Winvalid-offsetof" /* Squelch Win32 macro pollution >.< */ #undef SendMessage #undef GetMessage namespace amuse { void SoundMacroState::Evaluator::addComponent(uint8_t midiCtrl, float scale, Combine combine, VarType varType) { m_comps.push_back({midiCtrl, scale, combine, varType}); } float SoundMacroState::Evaluator::evaluate(double time, const Voice& vox, const SoundMacroState& st) const { float value = 0.f; /* Iterate each component */ for (auto it = m_comps.cbegin(); it != m_comps.cend(); ++it) { const Component& comp = *it; float thisValue = 0.f; /* Load selected data */ if (comp.m_varType == VarType::Ctrl) { switch (comp.m_midiCtrl) { case 128: /* Pitchbend */ thisValue = (vox.getPitchWheel() * 0.5f + 0.5f) * 127.f; break; case 129: /* Aftertouch */ thisValue = vox.getAftertouch(); break; case 130: /* LFO1 */ if (vox.m_lfoPeriods[0]) thisValue = (std::sin(time / vox.m_lfoPeriods[0] * 2.f * M_PIF) * 0.5f + 0.5f) * 127.f; break; case 131: /* LFO2 */ if (vox.m_lfoPeriods[1]) thisValue = (std::sin(time / vox.m_lfoPeriods[1] * 2.f * M_PIF) * 0.5f + 0.5f) * 127.f; break; case 132: /* Surround panning */ thisValue = (vox.m_curSpan * 0.5f + 0.5f) * 127.f; break; case 133: /* Macro-starting key */ thisValue = st.m_initKey; break; case 134: /* Macro-starting velocity */ thisValue = st.m_initVel; break; case 135: /* Time since macro-start (ms) */ thisValue = std::clamp(float(st.m_execTime * 1000.f), 0.f, 16383.f); break; default: thisValue = vox.getCtrlValue(comp.m_midiCtrl); break; } } else if (comp.m_varType == VarType::Var) thisValue = st.m_variables[comp.m_midiCtrl & 0x1f]; /* Apply scale */ thisValue *= comp.m_scale; /* Combine */ if (it != m_comps.cbegin()) { switch (comp.m_combine) { case Combine::Add: value += thisValue; break; case Combine::Mult: value *= thisValue; break; default: value = thisValue; break; } } else value = thisValue; } return value; } void SoundMacroState::initialize(ObjectId id, const SoundMacro* macro, int step) { initialize(id, macro, step, 1000.f, 0, 0, 0); } void SoundMacroState::initialize(ObjectId id, const SoundMacro* macro, int step, double ticksPerSec, uint8_t midiKey, uint8_t midiVel, uint8_t midiMod) { m_ticksPerSec = ticksPerSec; m_initKey = midiKey; m_initVel = midiVel; m_initMod = midiMod; m_curVel = midiVel; m_curMod = midiMod; m_curPitch = midiKey * 100; m_pc.clear(); m_pc.emplace_back(id, macro, macro->assertPC(step)); m_inWait = false; m_execTime = 0.f; m_keyoff = false; m_sampleEnd = false; m_loopCountdown = -1; m_lastPlayMacroVid = -1; m_useAdsrControllers = false; m_portamentoMode = SoundMacro::CmdPortamento::PortState::MIDIControlled; m_portamentoTime = 0.5f; } template <class T, std::enable_if_t<!std::is_enum_v<T>, int> = 0> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType() { return SoundMacro::CmdIntrospection::Field::Type::Invalid; } template <class T, std::enable_if_t<std::is_enum_v<T>, int> = 0> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType() { static_assert(sizeof(T) == 1, "Enum must be an 8-bit type"); return SoundMacro::CmdIntrospection::Field::Type::Choice; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<bool>() { return SoundMacro::CmdIntrospection::Field::Type::Bool; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<atInt8>() { return SoundMacro::CmdIntrospection::Field::Type::Int8; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<atUint8>() { return SoundMacro::CmdIntrospection::Field::Type::UInt8; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<atInt16>() { return SoundMacro::CmdIntrospection::Field::Type::Int16; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<atUint16>() { return SoundMacro::CmdIntrospection::Field::Type::UInt16; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<atInt32>() { return SoundMacro::CmdIntrospection::Field::Type::Int32; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<atUint32>() { return SoundMacro::CmdIntrospection::Field::Type::UInt32; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<SoundMacroIdDNA<athena::Endian::Little>>() { return SoundMacro::CmdIntrospection::Field::Type::SoundMacroId; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<SoundMacroStepDNA<athena::Endian::Little>>() { return SoundMacro::CmdIntrospection::Field::Type::SoundMacroStep; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<TableIdDNA<athena::Endian::Little>>() { return SoundMacro::CmdIntrospection::Field::Type::TableId; } template <> constexpr SoundMacro::CmdIntrospection::Field::Type GetFieldType<SampleIdDNA<athena::Endian::Little>>() { return SoundMacro::CmdIntrospection::Field::Type::SampleId; } #define FIELD_HEAD(tp, var) GetFieldType<decltype(var)>(), offsetof(tp, var) const SoundMacro::CmdIntrospection SoundMacro::CmdEnd::Introspective = { CmdType::Structure, "End"sv, "End of the macro. This always appears at the end of a given SoundMacro."sv, }; bool SoundMacro::CmdEnd::Do(SoundMacroState& st, Voice& vox) const { st._setPC(-1); return true; } const SoundMacro::CmdIntrospection SoundMacro::CmdStop::Introspective = { CmdType::Structure, "Stop"sv, "Stops the macro at any point."sv, }; bool SoundMacro::CmdStop::Do(SoundMacroState& st, Voice& vox) const { st._setPC(-1); return true; } const SoundMacro::CmdIntrospection SoundMacro::CmdSplitKey::Introspective = { CmdType::Structure, "Split Key"sv, "Conditionally branches macro execution based on MIDI key."sv, {{{FIELD_HEAD(SoundMacro::CmdSplitKey, key), "Key"sv, 0, 127, 60}, {FIELD_HEAD(SoundMacro::CmdSplitKey, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSplitKey, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdSplitKey::Do(SoundMacroState& st, Voice& vox) const { if (st.m_initKey >= key) { /* Do Branch */ if (macro.id == std::get<0>(st.m_pc.back())) st._setPC(macroStep.step); else vox.loadMacroObject(macro.id, macroStep.step, st.m_ticksPerSec, st.m_initKey, st.m_initVel, st.m_initMod); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSplitVel::Introspective = { CmdType::Structure, "Split Velocity"sv, "Conditionally branches macro execution based on velocity."sv, {{{FIELD_HEAD(SoundMacro::CmdSplitVel, velocity), "Key"sv, 0, 127, 100}, {FIELD_HEAD(SoundMacro::CmdSplitVel, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSplitVel, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdSplitVel::Do(SoundMacroState& st, Voice& vox) const { if (st.m_curVel >= velocity) { /* Do Branch */ if (macro.id == std::get<0>(st.m_pc.back())) st._setPC(macroStep.step); else vox.loadMacroObject(macro.id, macroStep.step, st.m_ticksPerSec, st.m_initKey, st.m_initVel, st.m_initMod); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdWaitTicks::Introspective = { CmdType::Structure, "Wait Ticks"sv, "Suspend SoundMacro execution for specified length of time. Value of 65535 " "will wait indefinitely, relying on Key Off or Sample End to signal stop. " "Absolute mode waits relative to the start of the SoundMacro."sv, {{{FIELD_HEAD(SoundMacro::CmdWaitTicks, keyOff), "Key Off"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitTicks, random), "Random"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitTicks, sampleEnd), "Sample End"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitTicks, absolute), "Absolute"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitTicks, msSwitch), "Use Millisec"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitTicks, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 96}}}}; bool SoundMacro::CmdWaitTicks::Do(SoundMacroState& st, Voice& vox) const { /* Set wait state */ if (ticksOrMs != 65535) { float q = msSwitch ? 1000.f : st.m_ticksPerSec; float secTime = ticksOrMs / q; /* Randomize at the proper resolution */ if (random) secTime = std::fmod(vox.getEngine().nextRandom() / q, secTime); if (absolute) { if (secTime <= st.m_execTime) return false; st.m_waitCountdown = secTime - st.m_execTime; } else st.m_waitCountdown = secTime; st.m_indefiniteWait = false; } else st.m_indefiniteWait = true; st.m_inWait = true; st.m_keyoffWait = keyOff; st.m_sampleEndWait = sampleEnd; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdLoop::Introspective = { CmdType::Structure, "Loop"sv, "Branch to specified location in a loop for a specified number of Times. " "65535 will cause an endless loop, relying on Key Off or Sample End to signal stop."sv, {{{FIELD_HEAD(SoundMacro::CmdLoop, keyOff), "Key Off"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdLoop, random), "Random"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdLoop, sampleEnd), "Sample End"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdLoop, macroStep), "Macro Step"sv, 0, 65535, 0}, {FIELD_HEAD(SoundMacro::CmdLoop, times), "Times"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdLoop::Do(SoundMacroState& st, Voice& vox) const { if ((keyOff && st.m_keyoff) || (sampleEnd && st.m_sampleEnd)) { /* Break out of loop */ st.m_loopCountdown = -1; return false; } uint16_t useTimes = times; if (random) useTimes = vox.getEngine().nextRandom() % times; if (st.m_loopCountdown == -1 && useTimes != 65535) st.m_loopCountdown = useTimes; if (st.m_loopCountdown > 0) { /* Loop back to step */ --st.m_loopCountdown; st._setPC(macroStep.step); } else /* Break out of loop */ st.m_loopCountdown = -1; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdGoto::Introspective = { CmdType::Structure, "Goto"sv, "Unconditional branch to specified SoundMacro location."sv, {{{FIELD_HEAD(SoundMacro::CmdGoto, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdGoto, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdGoto::Do(SoundMacroState& st, Voice& vox) const { /* Do Branch */ if (macro.id == std::get<0>(st.m_pc.back())) st._setPC(macroStep.step); else vox.loadMacroObject(macro.id, macroStep.step, st.m_ticksPerSec, st.m_initKey, st.m_initVel, st.m_initMod); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdWaitMs::Introspective = { CmdType::Structure, "Wait Millisec"sv, "Suspend SoundMacro execution for specified length of time. Value of 65535 " "will wait indefinitely, relying on Key Off or Sample End to signal stop. " "Absolute mode waits relative to the start of the SoundMacro."sv, {{{FIELD_HEAD(SoundMacro::CmdWaitMs, keyOff), "Key Off"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitMs, random), "Random"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitMs, sampleEnd), "Sample End"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitMs, absolute), "Absolute"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdWaitMs, ms), "Millisec"sv, 0, 65535, 96}}}}; bool SoundMacro::CmdWaitMs::Do(SoundMacroState& st, Voice& vox) const { /* Set wait state */ if (ms != 65535) { float secTime = ms / 1000.f; /* Randomize at the proper resolution */ if (random) secTime = std::fmod(vox.getEngine().nextRandom() / 1000.f, secTime); if (absolute) { if (secTime <= st.m_execTime) return false; st.m_waitCountdown = secTime - st.m_execTime; } else st.m_waitCountdown = secTime; st.m_indefiniteWait = false; } else st.m_indefiniteWait = true; st.m_inWait = true; st.m_keyoffWait = keyOff; st.m_sampleEndWait = sampleEnd; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPlayMacro::Introspective = { CmdType::Structure, "Play Macro"sv, "Play a SoundMacro in parallel to this one. Add Note is added to the " "current SoundMacro note to evaluate the new note."sv, {{{FIELD_HEAD(SoundMacro::CmdPlayMacro, addNote), "Add Note"sv, -128, 127, 0}, {FIELD_HEAD(SoundMacro::CmdPlayMacro, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdPlayMacro, macroStep), "Macro Step"sv, 0, 65535, 0}, {FIELD_HEAD(SoundMacro::CmdPlayMacro, priority), "Priority"sv, 0, 127, 50}, {FIELD_HEAD(SoundMacro::CmdPlayMacro, maxVoices), "Max Voices"sv, 0, 255, 255}}}}; bool SoundMacro::CmdPlayMacro::Do(SoundMacroState& st, Voice& vox) const { ObjToken<Voice> sibVox = vox.startChildMacro(addNote, macro.id, macroStep.step); if (sibVox) st.m_lastPlayMacroVid = sibVox->vid(); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSendKeyOff::Introspective = { CmdType::Structure, "Send Key Off"sv, "Send Key Off to voice specified by VID stored in a variable or the last started voice."sv, {{{FIELD_HEAD(SoundMacro::CmdSendKeyOff, variable), "Variable"sv, 0, 31, 0}, {FIELD_HEAD(SoundMacro::CmdSendKeyOff, lastStarted), "Last Started"sv, 0, 1, 0}}}}; bool SoundMacro::CmdSendKeyOff::Do(SoundMacroState& st, Voice& vox) const { if (lastStarted) { if (st.m_lastPlayMacroVid != -1) { ObjToken<Voice> otherVox = vox.getEngine().findVoice(st.m_lastPlayMacroVid); if (otherVox) otherVox->keyOff(); } } else { ObjToken<Voice> otherVox = vox.getEngine().findVoice(st.m_variables[variable & 0x1f]); if (otherVox) otherVox->keyOff(); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSplitMod::Introspective = { CmdType::Structure, "Split Mod"sv, "Conditionally branch if mod wheel is greater than or equal to specified value."sv, {{{FIELD_HEAD(SoundMacro::CmdSplitMod, modValue), "Mod Value"sv, 0, 127, 64}, {FIELD_HEAD(SoundMacro::CmdSplitMod, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSplitMod, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdSplitMod::Do(SoundMacroState& st, Voice& vox) const { if (st.m_curMod >= modValue) { /* Do Branch */ if (macro.id == std::get<0>(st.m_pc.back())) st._setPC(macroStep.step); else vox.loadMacroObject(macro.id, macroStep.step, st.m_ticksPerSec, st.m_initKey, st.m_initVel, st.m_initMod); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPianoPan::Introspective = { CmdType::Control, "Piano Pan"sv, "Gives piano-like sounds a natural-sounding stereo spread. The current key delta " "from Center Key is scaled with Scale and biased with Center Pan to evaluate panning."sv, {{{FIELD_HEAD(SoundMacro::CmdPianoPan, scale), "Scale"sv, 0, 127, 127}, {FIELD_HEAD(SoundMacro::CmdPianoPan, centerKey), "Center Key"sv, 0, 127, 36}, {FIELD_HEAD(SoundMacro::CmdPianoPan, centerPan), "Center Pan"sv, 0, 127, 64}}}}; bool SoundMacro::CmdPianoPan::Do(SoundMacroState& st, Voice& vox) const { int32_t pan = int32_t(st.m_initKey - centerKey) * scale / 127 + centerPan; pan = std::max(-127, std::min(127, pan)); vox.setPan(pan / 127.f); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetAdsr::Introspective = { CmdType::Volume, "Set ADSR"sv, "Specify ADSR envelope using a pool object. DLS mode must match setting in ADSR."sv, {{{FIELD_HEAD(SoundMacro::CmdSetAdsr, table), "ADSR"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSetAdsr, dlsMode), "DLS Mode"sv, 0, 1, 0}}}}; bool SoundMacro::CmdSetAdsr::Do(SoundMacroState& st, Voice& vox) const { vox.setAdsr(table.id, dlsMode); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdScaleVolume::Introspective = { CmdType::Volume, "Scale Volume"sv, "Calculates volume by scaling and biasing velocity. " "The result may be passed through an optional Curve."sv, {{{FIELD_HEAD(SoundMacro::CmdScaleVolume, scale), "Scale"sv, 0, 127, 127}, {FIELD_HEAD(SoundMacro::CmdScaleVolume, add), "Add"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdScaleVolume, table), "Curve"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdScaleVolume, originalVol), "Original Vol"sv, 0, 1, 1}}}}; bool SoundMacro::CmdScaleVolume::Do(SoundMacroState& st, Voice& vox) const { int32_t eval = int32_t(originalVol ? st.m_initVel : st.m_curVel) * scale / 127 + add; eval = std::clamp(eval, 0, 127); if (table.id != 0) { const Curve* curveData = vox.getAudioGroup().getPool().tableAsCurves(table.id); if (curveData && curveData->data.size() >= 128) { vox.m_curVol = curveData->data[eval] / 127.f; return false; } } vox.m_curVol = eval / 127.f; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPanning::Introspective = { CmdType::Control, "Panning"sv, "Start pan-sweep from Pan Position offset by Width over specified time period."sv, {{{FIELD_HEAD(SoundMacro::CmdPanning, panPosition), "Pan Position"sv, 0, 127, 64}, {FIELD_HEAD(SoundMacro::CmdPanning, timeMs), "Time Millisec"sv, 0, 65535, 0}, {FIELD_HEAD(SoundMacro::CmdPanning, width), "Width"sv, -128, 127, 0}}}}; bool SoundMacro::CmdPanning::Do(SoundMacroState& st, Voice& vox) const { vox.startPanning(timeMs / 1000.0, panPosition, width); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdEnvelope::Introspective = { CmdType::Volume, "Envelope"sv, "Start a velocity envelope by fading the current velocity to the one " "evaluated by Scale and Add. The result is optionally transformed with a Curve object."sv, {{{FIELD_HEAD(SoundMacro::CmdEnvelope, scale), "Scale"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdEnvelope, add), "Add"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdEnvelope, table), "Curve"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdEnvelope, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdEnvelope, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 500}}}}; bool SoundMacro::CmdEnvelope::Do(SoundMacroState& st, Voice& vox) const { double q = msSwitch ? 1000.0 : st.m_ticksPerSec; double secTime = ticksOrMs / q; int32_t eval = int32_t(st.m_curVel) * scale / 127 + add; eval = std::clamp(eval, 0, 127); const Curve* curveData; if (table.id != 0) curveData = vox.getAudioGroup().getPool().tableAsCurves(table.id); else curveData = nullptr; vox.startEnvelope(secTime, eval, curveData); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdStartSample::Introspective = { CmdType::Sample, "Start Sample"sv, "Start a Sample playing on the voice. An Offset in samples may be applied. " "This offset may be scaled with the current velocity."sv, {{{FIELD_HEAD(SoundMacro::CmdStartSample, sample), "Sample"sv, 0, 65535, 0}, {FIELD_HEAD(SoundMacro::CmdStartSample, mode), "Velocity Scale"sv, 0, 2, 0, {"No Scale"sv, "Negative"sv, "Positive"sv}}, {FIELD_HEAD(SoundMacro::CmdStartSample, offset), "Offset"sv, 0, 0xffffff, 0}}}}; bool SoundMacro::CmdStartSample::Do(SoundMacroState& st, Voice& vox) const { uint32_t useOffset = offset; switch (mode) { case Mode::Negative: useOffset = offset * (127 - st.m_curVel) / 127; break; case Mode::Positive: useOffset = offset * st.m_curVel / 127; break; default: break; } vox.startSample(sample.id, useOffset); vox.setPitchKey(st.m_curPitch); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdStopSample::Introspective = { CmdType::Sample, "Stop Sample"sv, "Stops the sample playing on the voice."sv}; bool SoundMacro::CmdStopSample::Do(SoundMacroState& st, Voice& vox) const { vox.stopSample(); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdKeyOff::Introspective = {CmdType::Control, "Key Off"sv, "Sends a Key Off to the current voice."sv}; bool SoundMacro::CmdKeyOff::Do(SoundMacroState& st, Voice& vox) const { vox._macroKeyOff(); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSplitRnd::Introspective = { CmdType::Structure, "Split Rnd"sv, "Conditionally branch if a random value is greater than or equal to RND. " "A lower RND will cause a higher probability of branching."sv, {{{FIELD_HEAD(SoundMacro::CmdSplitRnd, rnd), "RND"sv, 0, 255, 128}, {FIELD_HEAD(SoundMacro::CmdSplitRnd, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSplitRnd, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdSplitRnd::Do(SoundMacroState& st, Voice& vox) const { if (rnd <= vox.getEngine().nextRandom() % 256) { /* Do branch */ if (macro.id == std::get<0>(st.m_pc.back())) st._setPC(macroStep.step); else vox.loadMacroObject(macro.id, macroStep.step, st.m_ticksPerSec, st.m_initKey, st.m_initVel, st.m_initMod); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdFadeIn::Introspective = { CmdType::Volume, "Fade In"sv, "Start a velocity envelope by fading from silence to the velocity " "evaluated by Scale and Add. The result is optionally transformed with a Curve object."sv, {{{FIELD_HEAD(SoundMacro::CmdFadeIn, scale), "Scale"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdFadeIn, add), "Add"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdFadeIn, table), "Curve"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdFadeIn, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdFadeIn, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 500}}}}; bool SoundMacro::CmdFadeIn::Do(SoundMacroState& st, Voice& vox) const { float q = msSwitch ? 1000.f : st.m_ticksPerSec; float secTime = ticksOrMs / q; int32_t eval = int32_t(st.m_curVel) * scale / 127 + add; eval = std::clamp(eval, 0, 127); const Curve* curveData; if (table.id != 0) curveData = vox.getAudioGroup().getPool().tableAsCurves(table.id); else curveData = nullptr; vox.startFadeIn(secTime, eval, curveData); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSpanning::Introspective = { CmdType::Control, "Spanning"sv, "Start span-sweep from Span Position offset by Width over specified time period."sv, {{{FIELD_HEAD(SoundMacro::CmdSpanning, spanPosition), "Span Position"sv, 0, 127, 64}, {FIELD_HEAD(SoundMacro::CmdSpanning, timeMs), "Time Millisec"sv, 0, 65535, 0}, {FIELD_HEAD(SoundMacro::CmdSpanning, width), "Width"sv, -128, 127, 0}}}}; bool SoundMacro::CmdSpanning::Do(SoundMacroState& st, Voice& vox) const { vox.startSpanning(timeMs / 1000.0, spanPosition, width); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetAdsrCtrl::Introspective = { CmdType::Volume, "Set ADSR Ctrl"sv, "Bind MIDI controls to ADSR parameters."sv, {{{FIELD_HEAD(SoundMacro::CmdSetAdsrCtrl, attack), "Attack Ctrl"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdSetAdsrCtrl, decay), "Decay Ctrl"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdSetAdsrCtrl, sustain), "Sustain Ctrl"sv, 0, 127, 0}, {FIELD_HEAD(SoundMacro::CmdSetAdsrCtrl, release), "Release Ctrl"sv, 0, 127, 0}}}}; bool SoundMacro::CmdSetAdsrCtrl::Do(SoundMacroState& st, Voice& vox) const { st.m_useAdsrControllers = true; st.m_midiAttack = attack; st.m_midiDecay = decay; st.m_midiSustain = sustain; st.m_midiRelease = release; /* Bootstrap ADSR defaults here */ if (!vox.getCtrlValue(st.m_midiSustain)) { vox.setCtrlValue(st.m_midiAttack, 10); vox.setCtrlValue(st.m_midiSustain, 127); vox.setCtrlValue(st.m_midiRelease, 10); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdRndNote::Introspective = { CmdType::Pitch, "Random Note"sv, "Sets random pitch between Note Lo and Note Hi, biased by Detune in cents. " "If Free is set, the note will not snap to key steps."sv, {{{FIELD_HEAD(SoundMacro::CmdRndNote, noteLo), "Note Lo"sv, -127, 127, 48}, {FIELD_HEAD(SoundMacro::CmdRndNote, detune), "Detune"sv, 0, 99, 0}, {FIELD_HEAD(SoundMacro::CmdRndNote, noteHi), "Note Hi"sv, -127, 127, 72}, {FIELD_HEAD(SoundMacro::CmdRndNote, fixedFree), "Free"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdRndNote, absRel), "Absolute"sv, 0, 1, 0}}}}; bool SoundMacro::CmdRndNote::Do(SoundMacroState& st, Voice& vox) const { int32_t useNoteLo = noteLo; int32_t useNoteHi = noteHi; if (absRel) { useNoteLo = st.m_initKey - noteLo; useNoteHi = noteLo + noteHi; } useNoteLo *= 100; useNoteHi *= 100; if (useNoteHi == useNoteLo) st.m_curPitch = useNoteHi; else st.m_curPitch = (vox.getEngine().nextRandom() % (useNoteHi - useNoteLo)) + useNoteLo; if (!fixedFree) st.m_curPitch = st.m_curPitch / 100 * 100 + detune; vox.setPitchKey(st.m_curPitch); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAddNote::Introspective = { CmdType::Pitch, "Add Note"sv, "Sets new pitch by adding Add, biased by Detune in cents. " "The time parameters behave like a WAIT command when non-zero."sv, {{{FIELD_HEAD(SoundMacro::CmdAddNote, add), "Add"sv, -128, 127, 0}, {FIELD_HEAD(SoundMacro::CmdAddNote, detune), "Detune"sv, -99, 99, 0}, {FIELD_HEAD(SoundMacro::CmdAddNote, originalKey), "Original Key"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdAddNote, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdAddNote, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdAddNote::Do(SoundMacroState& st, Voice& vox) const { st.m_curPitch += add * 100 + detune; /* Set wait state */ if (msSwitch) { float q = msSwitch ? 1000.f : st.m_ticksPerSec; float secTime = ticksOrMs / q; st.m_waitCountdown = secTime; st.m_inWait = true; } vox.setPitchKey(st.m_curPitch); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetNote::Introspective = { CmdType::Pitch, "Set Note"sv, "Sets new pitch to Key, biased by Detune in cents. " "The time parameters behave like a WAIT command when non-zero."sv, {{{FIELD_HEAD(SoundMacro::CmdSetNote, key), "Key"sv, 0, 127, 60}, {FIELD_HEAD(SoundMacro::CmdSetNote, detune), "Detune"sv, -99, 99, 0}, {FIELD_HEAD(SoundMacro::CmdSetNote, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdSetNote, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdSetNote::Do(SoundMacroState& st, Voice& vox) const { st.m_curPitch = key * 100 + detune; /* Set wait state */ if (ticksOrMs) { float q = msSwitch ? 1000.f : st.m_ticksPerSec; float secTime = ticksOrMs / q; st.m_waitCountdown = secTime; st.m_inWait = true; } vox.setPitchKey(st.m_curPitch); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdLastNote::Introspective = { CmdType::Pitch, "Last Note"sv, "Sets new pitch by adding Add to last played MIDI note, biased by Detune in cents. " "The time parameters behave like a WAIT command when non-zero."sv, {{{FIELD_HEAD(SoundMacro::CmdLastNote, add), "Key"sv, -128, 127, 0}, {FIELD_HEAD(SoundMacro::CmdLastNote, detune), "Detune"sv, -99, 99, 0}, {FIELD_HEAD(SoundMacro::CmdLastNote, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdLastNote, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdLastNote::Do(SoundMacroState& st, Voice& vox) const { st.m_curPitch = (add + vox.getLastNote()) * 100 + detune; /* Set wait state */ if (msSwitch) { float q = msSwitch ? 1000.f : st.m_ticksPerSec; float secTime = ticksOrMs / q; st.m_waitCountdown = secTime; st.m_inWait = true; } vox.setPitchKey(st.m_curPitch); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPortamento::Introspective = { CmdType::Setup, "Portamento"sv, "Setup portamento mode for this voice."sv, {{{FIELD_HEAD(SoundMacro::CmdPortamento, portState), "Port. State"sv, 0, 2, 1, {"Enable"sv, "Disable"sv, "MIDI Controlled"sv}}, {FIELD_HEAD(SoundMacro::CmdPortamento, portType), "Port. Type"sv, 0, 1, 0, {"Last Pressed"sv, "Always"sv}}, {FIELD_HEAD(SoundMacro::CmdPortamento, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdPortamento, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdPortamento::Do(SoundMacroState& st, Voice& vox) const { st.m_portamentoMode = portState; st.m_portamentoType = portType; float q = msSwitch ? 1000.f : st.m_ticksPerSec; st.m_portamentoTime = ticksOrMs / q; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdVibrato::Introspective = { CmdType::Pitch, "Vibrato"sv, "Setup vibrato mode for this voice. Voice pitch will be " "modulated using the Level magnitude or the modwheel."sv, {{{FIELD_HEAD(SoundMacro::CmdVibrato, levelNote), "Level Note"sv, -127, 127, 0}, {FIELD_HEAD(SoundMacro::CmdVibrato, levelFine), "Level Fine"sv, -99, 99, 15}, {FIELD_HEAD(SoundMacro::CmdVibrato, modwheelFlag), "Use Modwheel"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdVibrato, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdVibrato, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 250}}}}; bool SoundMacro::CmdVibrato::Do(SoundMacroState& st, Voice& vox) const { float q = msSwitch ? 1000.f : st.m_ticksPerSec; vox.setVibrato(levelNote * 100 + levelFine, modwheelFlag, ticksOrMs / q); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPitchSweep1::Introspective = { CmdType::Pitch, "Pitch Sweep 1"sv, "Setup pitch sweep 1 for this voice. Voice pitch will accumulate Add for Times frames. " "If the time values are non-zero, this command also functions as a WAIT."sv, {{{FIELD_HEAD(SoundMacro::CmdPitchSweep1, times), "Times"sv, 0, 127, 100}, {FIELD_HEAD(SoundMacro::CmdPitchSweep1, add), "Add"sv, -32768, 32767, 100}, {FIELD_HEAD(SoundMacro::CmdPitchSweep1, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdPitchSweep1, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 1000}}}}; bool SoundMacro::CmdPitchSweep1::Do(SoundMacroState& st, Voice& vox) const { /* Set wait state */ if (msSwitch) { float q = msSwitch ? 1000.f : st.m_ticksPerSec; float secTime = ticksOrMs / q; st.m_waitCountdown = secTime; st.m_inWait = true; } vox.setPitchSweep1(times, add); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPitchSweep2::Introspective = { CmdType::Pitch, "Pitch Sweep 2"sv, "Setup pitch sweep 2 for this voice. Voice pitch will accumulate Add for Times frames. " "If the time values are non-zero, this command also functions as a WAIT."sv, {{{FIELD_HEAD(SoundMacro::CmdPitchSweep2, times), "Times"sv, 0, 127, 100}, {FIELD_HEAD(SoundMacro::CmdPitchSweep2, add), "Add"sv, -32768, 32767, 100}, {FIELD_HEAD(SoundMacro::CmdPitchSweep2, msSwitch), "Use Millisec"sv, 0, 1, 1}, {FIELD_HEAD(SoundMacro::CmdPitchSweep2, ticksOrMs), "Ticks/Millisec"sv, 0, 65535, 1000}}}}; bool SoundMacro::CmdPitchSweep2::Do(SoundMacroState& st, Voice& vox) const { /* Set wait state */ if (msSwitch) { float q = msSwitch ? 1000.f : st.m_ticksPerSec; float secTime = ticksOrMs / q; st.m_waitCountdown = secTime; st.m_inWait = true; } vox.setPitchSweep2(times, add); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetPitch::Introspective = { CmdType::Pitch, "Set Pitch"sv, "Set the playback sample rate directly."sv, {{{FIELD_HEAD(SoundMacro::CmdSetPitch, hz.val), "Hz"sv, 0, 0xffffff, 22050}, {FIELD_HEAD(SoundMacro::CmdSetPitch, fine), "Level Fine"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdSetPitch::Do(SoundMacroState& st, Voice& vox) const { vox.setPitchFrequency(hz, fine); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetPitchAdsr::Introspective = { CmdType::Pitch, "Set Pitch ADSR"sv, "Define the pitch ADSR from a DLS ADSR pool object. The pitch range is " "specified using Note and Cents parameters."sv, {{{FIELD_HEAD(SoundMacro::CmdSetPitchAdsr, table), "ADSR"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSetPitchAdsr, keys), "Note range"sv, -128, 127, 0}, {FIELD_HEAD(SoundMacro::CmdSetPitchAdsr, cents), "Cents range"sv, -99, 99, 0}}}}; bool SoundMacro::CmdSetPitchAdsr::Do(SoundMacroState& st, Voice& vox) const { vox.setPitchAdsr(table.id, keys * 100 + cents); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdScaleVolumeDLS::Introspective = { CmdType::Volume, "Scale Volume DLS"sv, "Sets new volume by scaling the velocity. A value of 4096 == 100%."sv, {{{FIELD_HEAD(SoundMacro::CmdScaleVolumeDLS, scale), "Scale"sv, 0, 16383, 4096}, {FIELD_HEAD(SoundMacro::CmdScaleVolumeDLS, originalVol), "Original Vol"sv, 0, 1, 1}}}}; bool SoundMacro::CmdScaleVolumeDLS::Do(SoundMacroState& st, Voice& vox) const { vox.m_curVol = int32_t(originalVol ? st.m_initVel : st.m_curVel) * scale / 4096.f / 127.f; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdMod2Vibrange::Introspective = { CmdType::Pitch, "Mod 2 Vibrange"sv, "Values used to scale the modwheel control for vibrato."sv, {{{FIELD_HEAD(SoundMacro::CmdMod2Vibrange, keys), "Key range"sv, 0, 16383, 4096}, {FIELD_HEAD(SoundMacro::CmdMod2Vibrange, cents), "Cent range"sv, 0, 1, 1}}}}; bool SoundMacro::CmdMod2Vibrange::Do(SoundMacroState& st, Voice& vox) const { vox.setMod2VibratoRange(keys * 100 + cents); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetupTremolo::Introspective = { CmdType::Special, "Setup Tremolo"sv, "Setup tremolo effect. Must be combined with Tremolo Select to connect " "with a configured LFO. A value of 4096 == 100%."sv, {{{FIELD_HEAD(SoundMacro::CmdSetupTremolo, scale), "Scale"sv, 0, 16383, 8192}, {FIELD_HEAD(SoundMacro::CmdSetupTremolo, modwAddScale), "Modw. add scale"sv, 0, 16383, 0}}}}; bool SoundMacro::CmdSetupTremolo::Do(SoundMacroState& st, Voice& vox) const { vox.setTremolo(scale / 4096.f, scale / 4096.f); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdReturn::Introspective = { CmdType::Structure, "Return"sv, "Branch to after last Go Subroutine command and pop call stack."sv}; bool SoundMacro::CmdReturn::Do(SoundMacroState& st, Voice& vox) const { if (st.m_pc.size() > 1) { st.m_pc.pop_back(); vox._setObjectId(std::get<0>(st.m_pc.back())); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdGoSub::Introspective = { CmdType::Structure, "Go Subroutine"sv, "Push location onto call stack and branch to specified location."sv, {{{FIELD_HEAD(SoundMacro::CmdSplitRnd, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSplitRnd, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdGoSub::Do(SoundMacroState& st, Voice& vox) const { if (macro.id == std::get<0>(st.m_pc.back())) st.m_pc.emplace_back(std::get<0>(st.m_pc.back()), std::get<1>(st.m_pc.back()), std::get<1>(st.m_pc.back())->assertPC(macroStep.step)); else vox.loadMacroObject(macro.id, macroStep.step, st.m_ticksPerSec, st.m_initKey, st.m_initVel, st.m_initMod, true); vox._setObjectId(std::get<0>(st.m_pc.back())); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdTrapEvent::Introspective = { CmdType::Structure, "Trap Event"sv, "Register event-based branch to a specified location."sv, {{{FIELD_HEAD(SoundMacro::CmdTrapEvent, event), "Event"sv, 0, 2, 0, {"Key Off"sv, "Sample End"sv, "Message Recv"sv}}, {FIELD_HEAD(SoundMacro::CmdTrapEvent, macro), "Macro"sv, 0, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdTrapEvent, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdTrapEvent::Do(SoundMacroState& st, Voice& vox) const { switch (event) { case EventType::KeyOff: vox.m_keyoffTrap.macroId = macro.id; vox.m_keyoffTrap.macroStep = macroStep.step; break; case EventType::SampleEnd: vox.m_sampleEndTrap.macroId = macro.id; vox.m_sampleEndTrap.macroStep = macroStep.step; break; case EventType::MessageRecv: vox.m_messageTrap.macroId = macro.id; vox.m_messageTrap.macroStep = macroStep.step; break; default: break; } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdUntrapEvent::Introspective = { CmdType::Structure, "Untrap Event"sv, "Unregister event-based branch."sv, {{{FIELD_HEAD(SoundMacro::CmdUntrapEvent, event), "Event"sv, 0, 2, 0, {"Key Off"sv, "Sample End"sv, "Message Recv"sv}}}}}; bool SoundMacro::CmdUntrapEvent::Do(SoundMacroState& st, Voice& vox) const { switch (event) { case CmdTrapEvent::EventType::KeyOff: vox.m_keyoffTrap.macroId = 0xffff; vox.m_keyoffTrap.macroStep = 0xffff; break; case CmdTrapEvent::EventType::SampleEnd: vox.m_sampleEndTrap.macroId = 0xffff; vox.m_sampleEndTrap.macroStep = 0xffff; break; case CmdTrapEvent::EventType::MessageRecv: vox.m_messageTrap.macroId = 0xffff; vox.m_messageTrap.macroStep = 0xffff; break; default: break; } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSendMessage::Introspective = { CmdType::Special, "Send Message"sv, "Send message to SoundMacro or Voice referenced in a variable. " "The message value is retrieved from a variable."sv, {{{FIELD_HEAD(SoundMacro::CmdSendMessage, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdSendMessage, macro), "Macro"sv, 1, 65535, 65535}, {FIELD_HEAD(SoundMacro::CmdSendMessage, voiceVar), "Voice Var"sv, 0, 31, 0}, {FIELD_HEAD(SoundMacro::CmdSendMessage, valueVar), "Value Var"sv, 0, 31, 0}}}}; bool SoundMacro::CmdSendMessage::Do(SoundMacroState& st, Voice& vox) const { if (isVar) { ObjToken<Voice> findVox = vox.getEngine().findVoice(st.m_variables[voiceVar & 0x1f]); if (findVox) findVox->message(st.m_variables[valueVar & 0x1f]); } else vox.getEngine().sendMacroMessage(macro.id, st.m_variables[valueVar & 0x1f]); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdGetMessage::Introspective = { CmdType::Special, "Get Message"sv, "Get voice's latest received message and store its value in Variable."sv, {{{FIELD_HEAD(SoundMacro::CmdGetMessage, variable), "Variable"sv, 0, 31, 0}}}}; bool SoundMacro::CmdGetMessage::Do(SoundMacroState& st, Voice& vox) const { st.m_variables[variable & 0x1f] = vox.m_latestMessage; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdGetVid::Introspective = { CmdType::Special, "Get VID"sv, "Get ID of current voice or last voice started by Play Macro command and store in Variable."sv, {{{FIELD_HEAD(SoundMacro::CmdGetVid, variable), "Variable"sv, 0, 31, 0}, {FIELD_HEAD(SoundMacro::CmdGetVid, playMacro), "Play Macro"sv, 0, 1, 1}}}}; bool SoundMacro::CmdGetVid::Do(SoundMacroState& st, Voice& vox) const { st.m_variables[variable & 0x1f] = playMacro ? st.m_lastPlayMacroVid : vox.vid(); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAddAgeCount::Introspective = { CmdType::Special, "Add Age Count"sv, "Adds a value to the current voice's age counter."sv, {{{FIELD_HEAD(SoundMacro::CmdAddAgeCount, add), "Add"sv, -32768, 32767, -30000}}}}; bool SoundMacro::CmdAddAgeCount::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetAgeCount::Introspective = { CmdType::Special, "Set Age Count"sv, "Set a value into the current voice's age counter."sv, {{{FIELD_HEAD(SoundMacro::CmdSetAgeCount, counter), "Counter"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdSetAgeCount::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSendFlag::Introspective = { CmdType::Special, "Send Flag"sv, "Send a flag value to the host application."sv, {{{FIELD_HEAD(SoundMacro::CmdSendFlag, flagId), "Flag ID"sv, 0, 15, 0}, {FIELD_HEAD(SoundMacro::CmdSendFlag, value), "Value"sv, 0, 255, 255}}}}; bool SoundMacro::CmdSendFlag::Do(SoundMacroState& st, Voice& vox) const { /* TODO: figure out a good API */ return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPitchWheelR::Introspective = { CmdType::Setup, "Pitch Wheel Range"sv, "Specifies the number of note steps for the range of the pitch wheel."sv, {{{FIELD_HEAD(SoundMacro::CmdPitchWheelR, rangeUp), "Range Up"sv, 0, 127, 2}, {FIELD_HEAD(SoundMacro::CmdPitchWheelR, rangeDown), "Range Down"sv, 0, 127, 2}}}}; bool SoundMacro::CmdPitchWheelR::Do(SoundMacroState& st, Voice& vox) const { vox.setPitchWheelRange(rangeUp, rangeDown); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetPriority::Introspective = { CmdType::Special, "Set Priority"sv, "Sets the priority of the current voice."sv, {{{FIELD_HEAD(SoundMacro::CmdSetPriority, prio), "Priority"sv, 0, 254, 50}}}}; bool SoundMacro::CmdSetPriority::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAddPriority::Introspective = { CmdType::Special, "Add Priority"sv, "Adds to the priority of the current voice."sv, {{{FIELD_HEAD(SoundMacro::CmdAddPriority, prio), "Priority"sv, -255, 255, 1}}}}; bool SoundMacro::CmdAddPriority::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAgeCntSpeed::Introspective = { CmdType::Special, "Age Count Speed"sv, "Sets the speed the current voice's age counter is decremented."sv, {{{FIELD_HEAD(SoundMacro::CmdAgeCntSpeed, time), "Millisec"sv, 0, 16777215, 1080000}}}}; bool SoundMacro::CmdAgeCntSpeed::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAgeCntVel::Introspective = { CmdType::Special, "Age Count Velocity"sv, "Sets the current voice's age counter by scaling the velocity."sv, {{{FIELD_HEAD(SoundMacro::CmdAgeCntVel, ageBase), "Base"sv, 0, 65535, 60000}, {FIELD_HEAD(SoundMacro::CmdAgeCntVel, ageScale), "Scale"sv, 0, 65535, 127}}}}; bool SoundMacro::CmdAgeCntVel::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdVolSelect::Introspective = { CmdType::Setup, "Volume Select"sv, "Appends an evaluator component for computing the voice's volume."sv, {{{FIELD_HEAD(SoundMacro::CmdVolSelect, midiControl), "MIDI Control"sv, 0, 132, 7}, {FIELD_HEAD(SoundMacro::CmdVolSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdVolSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdVolSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdVolSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdVolSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_volumeSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPanSelect::Introspective = { CmdType::Setup, "Pan Select"sv, "Appends an evaluator component for computing the voice's pan."sv, {{{FIELD_HEAD(SoundMacro::CmdPanSelect, midiControl), "MIDI Control"sv, 0, 132, 10}, {FIELD_HEAD(SoundMacro::CmdPanSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdPanSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdPanSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdPanSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdPanSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_panSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPitchWheelSelect::Introspective = { CmdType::Setup, "Pitch Wheel Select"sv, "Appends an evaluator component for computing the voice's pitch wheel."sv, {{{FIELD_HEAD(SoundMacro::CmdPitchWheelSelect, midiControl), "MIDI Control"sv, 0, 132, 128}, {FIELD_HEAD(SoundMacro::CmdPitchWheelSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdPitchWheelSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdPitchWheelSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdPitchWheelSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdPitchWheelSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_pitchWheelSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdModWheelSelect::Introspective = { CmdType::Setup, "Mod Wheel Select"sv, "Appends an evaluator component for computing the voice's mod wheel."sv, {{{FIELD_HEAD(SoundMacro::CmdModWheelSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdModWheelSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdModWheelSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdModWheelSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdModWheelSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdModWheelSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_modWheelSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPedalSelect::Introspective = { CmdType::Setup, "Pedal Select"sv, "Appends an evaluator component for computing the voice's pedal."sv, {{{FIELD_HEAD(SoundMacro::CmdPedalSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdPedalSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdPedalSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdPedalSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdPedalSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdPedalSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_pedalSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPortamentoSelect::Introspective = { CmdType::Setup, "Portamento Select"sv, "Appends an evaluator component for computing the voice's portamento."sv, {{{FIELD_HEAD(SoundMacro::CmdPortamentoSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdPortamentoSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdPortamentoSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdPortamentoSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdPortamentoSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdPortamentoSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_portamentoSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdReverbSelect::Introspective = { CmdType::Setup, "Reverb Select"sv, "Appends an evaluator component for computing the voice's reverb."sv, {{{FIELD_HEAD(SoundMacro::CmdReverbSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdReverbSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdReverbSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdReverbSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdReverbSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdReverbSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_reverbSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSpanSelect::Introspective = { CmdType::Setup, "Span Select"sv, "Appends an evaluator component for computing the voice's span."sv, {{{FIELD_HEAD(SoundMacro::CmdSpanSelect, midiControl), "MIDI Control"sv, 0, 132, 19}, {FIELD_HEAD(SoundMacro::CmdSpanSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdSpanSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdSpanSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdSpanSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdSpanSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_spanSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdDopplerSelect::Introspective = { CmdType::Setup, "Doppler Select"sv, "Appends an evaluator component for computing the voice's doppler."sv, {{{FIELD_HEAD(SoundMacro::CmdDopplerSelect, midiControl), "MIDI Control"sv, 0, 132, 132}, {FIELD_HEAD(SoundMacro::CmdDopplerSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdDopplerSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdDopplerSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdDopplerSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdDopplerSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_dopplerSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdTremoloSelect::Introspective = { CmdType::Setup, "Tremolo Select"sv, "Appends an evaluator component for computing the voice's tremolo."sv, {{{FIELD_HEAD(SoundMacro::CmdTremoloSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdTremoloSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdTremoloSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdTremoloSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdTremoloSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdTremoloSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_tremoloSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPreASelect::Introspective = { CmdType::Setup, "PreA Select"sv, "Appends an evaluator component for computing the voice's pre-AUXA."sv, {{{FIELD_HEAD(SoundMacro::CmdPreASelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdPreASelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdPreASelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdPreASelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdPreASelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdPreASelect::Do(SoundMacroState& st, Voice& vox) const { st.m_preAuxASel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPreBSelect::Introspective = { CmdType::Setup, "PreB Select"sv, "Appends an evaluator component for computing the voice's pre-AUXB."sv, {{{FIELD_HEAD(SoundMacro::CmdPreBSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdPreBSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdPreBSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdPreBSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdPreBSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdPreBSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_preAuxBSel.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdPostBSelect::Introspective = { CmdType::Setup, "PostB Select"sv, "Appends an evaluator component for computing the voice's post-AUXB."sv, {{{FIELD_HEAD(SoundMacro::CmdPostBSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdPostBSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdPostBSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdPostBSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdPostBSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}}}}; bool SoundMacro::CmdPostBSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_postAuxB.addComponent(midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAuxAFXSelect::Introspective = { CmdType::Setup, "AuxA FX Select"sv, "Appends an evaluator component for computing the AUXA Parameter."sv, {{{FIELD_HEAD(SoundMacro::CmdAuxAFXSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdAuxAFXSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdAuxAFXSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdAuxAFXSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdAuxAFXSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}, {FIELD_HEAD(SoundMacro::CmdAuxAFXSelect, paramIndex), "Param Index"sv, 0, 2, 0}}}}; bool SoundMacro::CmdAuxAFXSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_auxAFxSel[std::min(paramIndex, atUint8(3))].addComponent( midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAuxBFXSelect::Introspective = { CmdType::Setup, "AuxB FX Select"sv, "Appends an evaluator component for computing the AUXB Parameter."sv, {{{FIELD_HEAD(SoundMacro::CmdAuxBFXSelect, midiControl), "MIDI Control"sv, 0, 132, 1}, {FIELD_HEAD(SoundMacro::CmdAuxBFXSelect, scalingPercentage), "Scale Percentage"sv, -10000, 10000, 100}, {FIELD_HEAD(SoundMacro::CmdAuxBFXSelect, combine), "Combine Mode"sv, 0, 2, 0, {"Set"sv, "Add"sv, "Mult"sv}}, {FIELD_HEAD(SoundMacro::CmdAuxBFXSelect, isVar), "Is Var"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdAuxBFXSelect, fineScaling), "Fine Scaling"sv, -100, 100, 0}, {FIELD_HEAD(SoundMacro::CmdAuxBFXSelect, paramIndex), "Param Index"sv, 0, 2, 0}}}}; bool SoundMacro::CmdAuxBFXSelect::Do(SoundMacroState& st, Voice& vox) const { st.m_auxBFxSel[std::min(paramIndex, atUint8(3))].addComponent( midiControl, (scalingPercentage + fineScaling / 100.f) / 100.f, SoundMacroState::Evaluator::Combine(combine), SoundMacroState::Evaluator::VarType(isVar)); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetupLFO::Introspective = { CmdType::Setup, "Setup LFO"sv, "Configures voice's LFO period in milliseconds."sv, {{{FIELD_HEAD(SoundMacro::CmdSetupLFO, lfoNumber), "LFO Number"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdSetupLFO, periodInMs), "Period"sv, -10000, 10000, 100}}}}; bool SoundMacro::CmdSetupLFO::Do(SoundMacroState& st, Voice& vox) const { if (lfoNumber == 0) vox.setLFO1Period(periodInMs / 1000.f); else if (lfoNumber == 1) vox.setLFO2Period(periodInMs / 1000.f); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdModeSelect::Introspective = { CmdType::Setup, "Mode Select"sv, "Sets operating modes for current voice."sv, {{{FIELD_HEAD(SoundMacro::CmdModeSelect, dlsVol), "DLS Vol"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdModeSelect, itd), "ITD"sv, 0, 1, 0}}}}; bool SoundMacro::CmdModeSelect::Do(SoundMacroState& st, Voice& vox) const { vox.m_dlsVol = dlsVol; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetKeygroup::Introspective = { CmdType::Setup, "Set Keygroup"sv, "Selects keygroup for current voice."sv, {{{FIELD_HEAD(SoundMacro::CmdSetKeygroup, group), "Group"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdSetKeygroup, killNow), "Kill now"sv, 0, 1, 0}}}}; bool SoundMacro::CmdSetKeygroup::Do(SoundMacroState& st, Voice& vox) const { vox.setKeygroup(0); if (group) { vox.getEngine().killKeygroup(group, killNow); vox.setKeygroup(group); } return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSRCmodeSelect::Introspective = { CmdType::Setup, "SRC Mode Select"sv, "Sets operating modes for sample rate converter."sv, {{{FIELD_HEAD(SoundMacro::CmdSRCmodeSelect, srcType), "SRC Type"sv, 0, 2, 0}, {FIELD_HEAD(SoundMacro::CmdSRCmodeSelect, type0SrcFilter), "Type 0 SRC Filter"sv, 0, 2, 1}}}}; bool SoundMacro::CmdSRCmodeSelect::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdWiiUnknown::Introspective = { CmdType::Setup, "Wii Unknown"sv, "????"sv, {{{FIELD_HEAD(SoundMacro::CmdWiiUnknown, flag), "?"sv, 0, 1, 0}}}}; bool SoundMacro::CmdWiiUnknown::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdWiiUnknown2::Introspective = { CmdType::Setup, "Wii Unknown 2"sv, "????"sv, {{{FIELD_HEAD(SoundMacro::CmdWiiUnknown2, flag), "?"sv, 0, 1, 0}}}}; bool SoundMacro::CmdWiiUnknown2::Do(SoundMacroState& st, Voice& vox) const { return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAddVars::Introspective = { CmdType::Special, "Add Vars"sv, "A = B + C"sv, {{{FIELD_HEAD(SoundMacro::CmdAddVars, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdAddVars, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdAddVars, varCtrlB), "Use Ctrl B"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdAddVars, b), "B"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdAddVars, varCtrlC), "Use Ctrl C"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdAddVars, c), "C"sv, 0, 255, 0}}}}; bool SoundMacro::CmdAddVars::Do(SoundMacroState& st, Voice& vox) const { int32_t useB, useC; if (varCtrlB) useB = vox.getCtrlValue(b); else useB = st.m_variables[b & 0x1f]; if (varCtrlC) useC = vox.getCtrlValue(c); else useC = st.m_variables[c & 0x1f]; if (varCtrlA) vox.setCtrlValue(a, useB + useC); else st.m_variables[a & 0x1f] = useB + useC; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSubVars::Introspective = { CmdType::Special, "Sub Vars"sv, "A = B - C"sv, {{{FIELD_HEAD(SoundMacro::CmdSubVars, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdSubVars, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdSubVars, varCtrlB), "Use Ctrl B"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdSubVars, b), "B"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdSubVars, varCtrlC), "Use Ctrl C"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdSubVars, c), "C"sv, 0, 255, 0}}}}; bool SoundMacro::CmdSubVars::Do(SoundMacroState& st, Voice& vox) const { int32_t useB, useC; if (varCtrlB) useB = vox.getCtrlValue(b); else useB = st.m_variables[b & 0x1f]; if (varCtrlC) useC = vox.getCtrlValue(c); else useC = st.m_variables[c & 0x1f]; if (varCtrlA) vox.setCtrlValue(a, useB - useC); else st.m_variables[a & 0x1f] = useB - useC; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdMulVars::Introspective = { CmdType::Special, "Mul Vars"sv, "A = B * C"sv, {{{FIELD_HEAD(SoundMacro::CmdMulVars, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdMulVars, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdMulVars, varCtrlB), "Use Ctrl B"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdMulVars, b), "B"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdMulVars, varCtrlC), "Use Ctrl C"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdMulVars, c), "C"sv, 0, 255, 0}}}}; bool SoundMacro::CmdMulVars::Do(SoundMacroState& st, Voice& vox) const { int32_t useB, useC; if (varCtrlB) useB = vox.getCtrlValue(b); else useB = st.m_variables[b & 0x1f]; if (varCtrlC) useC = vox.getCtrlValue(c); else useC = st.m_variables[c & 0x1f]; if (varCtrlA) vox.setCtrlValue(a, useB * useC); else st.m_variables[a & 0x1f] = useB * useC; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdDivVars::Introspective = { CmdType::Special, "Div Vars"sv, "A = B / C"sv, {{{FIELD_HEAD(SoundMacro::CmdDivVars, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdDivVars, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdDivVars, varCtrlB), "Use Ctrl B"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdDivVars, b), "B"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdDivVars, varCtrlC), "Use Ctrl C"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdDivVars, c), "C"sv, 0, 255, 0}}}}; bool SoundMacro::CmdDivVars::Do(SoundMacroState& st, Voice& vox) const { int32_t useB, useC; if (varCtrlB) useB = vox.getCtrlValue(b); else useB = st.m_variables[b & 0x1f]; if (varCtrlC) useC = vox.getCtrlValue(c); else useC = st.m_variables[c & 0x1f]; if (varCtrlA) vox.setCtrlValue(a, useB / useC); else st.m_variables[a & 0x1f] = useB / useC; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdAddIVars::Introspective = { CmdType::Special, "Add Imm Vars"sv, "A = B + Immediate"sv, {{{FIELD_HEAD(SoundMacro::CmdAddIVars, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdAddIVars, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdAddIVars, varCtrlB), "Use Ctrl B"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdAddIVars, b), "B"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdAddIVars, imm), "Immediate"sv, -32768, 32767, 0}}}}; bool SoundMacro::CmdAddIVars::Do(SoundMacroState& st, Voice& vox) const { int32_t useB; if (varCtrlB) useB = vox.getCtrlValue(b); else useB = st.m_variables[b & 0x1f]; if (varCtrlA) vox.setCtrlValue(a, useB + imm); else st.m_variables[a & 0x1f] = useB + imm; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdSetVar::Introspective = { CmdType::Special, "Set Var"sv, "A = Immediate"sv, {{{FIELD_HEAD(SoundMacro::CmdSetVar, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdSetVar, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdSetVar, imm), "Immediate"sv, -32768, 32767, 0}}}}; bool SoundMacro::CmdSetVar::Do(SoundMacroState& st, Voice& vox) const { if (varCtrlA) vox.setCtrlValue(a, imm); else st.m_variables[a & 0x1f] = imm; return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdIfEqual::Introspective = { CmdType::Structure, "If Equal"sv, "Branches to specified step if A == B."sv, {{{FIELD_HEAD(SoundMacro::CmdIfEqual, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdIfEqual, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdIfEqual, varCtrlB), "Use Ctrl B"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdIfEqual, b), "B"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdIfEqual, notEq), "Not"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdIfEqual, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdIfEqual::Do(SoundMacroState& st, Voice& vox) const { int32_t useA, useB; if (varCtrlA) useA = vox.getCtrlValue(a); else useA = st.m_variables[a & 0x1f]; if (varCtrlB) useB = vox.getCtrlValue(b); else useB = st.m_variables[b & 0x1f]; if ((useA == useB) ^ notEq) st._setPC(macroStep.step); return false; } const SoundMacro::CmdIntrospection SoundMacro::CmdIfLess::Introspective = { CmdType::Structure, "If Less"sv, "Branches to specified step if A < B."sv, {{{FIELD_HEAD(SoundMacro::CmdIfLess, varCtrlA), "Use Ctrl A"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdIfLess, a), "A"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdIfLess, varCtrlB), "Use Ctrl B"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdIfLess, b), "B"sv, 0, 255, 0}, {FIELD_HEAD(SoundMacro::CmdIfLess, notLt), "Not"sv, 0, 1, 0}, {FIELD_HEAD(SoundMacro::CmdIfLess, macroStep), "Macro Step"sv, 0, 65535, 0}}}}; bool SoundMacro::CmdIfLess::Do(SoundMacroState& st, Voice& vox) const { int32_t useA, useB; if (varCtrlA) useA = vox.getCtrlValue(a); else useA = st.m_variables[a & 0x1f]; if (varCtrlB) useB = vox.getCtrlValue(b); else useB = st.m_variables[b & 0x1f]; if ((useA < useB) ^ notLt) st._setPC(macroStep.step); return false; } bool SoundMacroState::advance(Voice& vox, double dt) { /* Nothing if uninitialized or finished */ if (m_pc.empty() || std::get<1>(m_pc.back()) == nullptr || std::get<2>(m_pc.back()) == -1) return true; /* Loop through as many commands as we can for this time period */ while (true) { /* Advance wait timer if active, returning if waiting */ if (m_inWait) { if (m_keyoffWait && m_keyoff) m_inWait = false; else if (m_sampleEndWait && m_sampleEnd) m_inWait = false; else if (!m_indefiniteWait) { m_waitCountdown -= dt; if (m_waitCountdown < 0.f) m_inWait = false; } if (m_inWait) { m_execTime += dt; return false; } } /* Load next command based on counter */ const SoundMacro::ICmd& cmd = std::get<1>(m_pc.back())->getCmd(std::get<2>(m_pc.back())++); /* Perform function of command */ if (cmd.Do(*this, vox)) return true; } m_execTime += dt; return false; } void SoundMacroState::keyoffNotify(Voice& vox) { m_keyoff = true; } void SoundMacroState::sampleEndNotify(Voice& vox) { m_sampleEnd = true; } } // namespace amuse
// AAAA returns AAAA records from Backend or an error. func AAAA(b ServiceBackend, zone string, state request.Request, previousRecords []dns.RR, opt Options) (records []dns.RR, err error) { services, err := checkForApex(b, zone, state, opt) if err != nil { return nil, err } dup := make(map[string]bool) for _, serv := range services { what, ip := serv.HostType() switch what { case dns.TypeCNAME: if Name(state.Name()).Matches(dns.Fqdn(serv.Host)) { continue } newRecord := serv.NewCNAME(state.QName(), serv.Host) if len(previousRecords) > 7 { continue } if dnsutil.DuplicateCNAME(newRecord, previousRecords) { continue } state1 := state.NewWithQuestion(serv.Host, state.QType()) nextRecords, err := AAAA(b, zone, state1, append(previousRecords, newRecord), opt) if err == nil { if len(nextRecords) > 0 { records = append(records, newRecord) records = append(records, nextRecords...) } continue } target := newRecord.Target m1, e1 := b.Lookup(state, target, state.QType()) if e1 != nil { continue } records = append(records, newRecord) records = append(records, m1.Answer...) continue case dns.TypeA: case dns.TypeAAAA: if _, ok := dup[serv.Host]; !ok { dup[serv.Host] = true records = append(records, serv.NewAAAA(state.QName(), ip)) } } } return records, nil }
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int K = sc.nextInt(); long[] V = new long[N]; for (int i=0; i<N; i++){ V[i] = sc.nextInt(); } sc.close(); // l + r - d long ans = Long.MIN_VALUE; for(int l=0; l<=K; l++){ for (int r=0; r<=K-l; r++){ if (l+r > N) break; ArrayList<Long> s = new ArrayList<>(); int d = K - l - r; long now =0; for (int i=0; i<=l-1; i++){ now += V[i]; s.add(V[i]); } for (int i=N-r; i<N; i++){ now += V[i]; s.add(V[i]); } Collections.sort(s); for (int i=0; i<d; i++){ if (i >= s.size()) break; long tmp = s.get(i); if (tmp > 0) break; now -= tmp; } ans = Math.max(ans, now); } } System.out.println(ans); } }
// Range returns all Pythagorean triplets with sides in a given range min-max func Range(min int, max int) (result []Triplet) { for i := min; i < max; i++ { for j := max; i > min; i-- { sum := math.Sqrt(float64(i * i + j * j)) if sum == float64(int64(sum)) { result = append(result, Triplet{i, j, int(sum)}) } } } return }
// Start runs a golang http server with the given routes. // Returns // * a reference to the HTTP server (so that we can gracefully shut it down) // a channel that will contain the error result of the ListenAndServe call func (s *Server) Start() (*http.Server, chan error) { s.registry.MustRegister(s.processDuration) s.registry.MustRegister(s.processCurrent) s.registry.MustRegister(s.errCounter) s.registry.MustRegister(s.sigCounter) s.registry.MustRegister(s.skipCounter) err := s.initMetrics() if err != nil { panic(err) } mux := http.NewServeMux() srv := &http.Server{Addr: s.config.ListenAddr, Handler: mux} mux.HandleFunc("/", s.handleWebhook) mux.HandleFunc("/_health", handleHealth) mux.Handle("/metrics", promhttp.HandlerFor(s.registry, promhttp.HandlerOpts{ ErrorLog: log.New(os.Stderr, "", log.LstdFlags), Registry: s.registry, })) var httpSrvResult = make(chan error, 1) go func() { defer close(httpSrvResult) commands := make([]string, len(s.config.Commands)) for i, e := range s.config.Commands { commands[i] = e.String() } log.Println("Listening on", s.config.ListenAddr, "with commands", strings.Join(commands, ", ")) if (s.config.TLSCrt != "") && (s.config.TLSKey != "") { if s.config.Verbose { log.Println("HTTPS on") } httpSrvResult <- srv.ListenAndServeTLS(s.config.TLSCrt, s.config.TLSKey) } else { if s.config.Verbose { log.Println("HTTPS off") } httpSrvResult <- srv.ListenAndServe() } }() return srv, httpSrvResult }
def handler_imgur_image(self, url, info, channel): if not self.registryValue("imgur.enabled", channel=channel): return self.handler_default(url, channel) client_id = self.registryValue("imgur.clientID") if not client_id: log.error("SpiffyTitles: imgur client ID not set") return self.handler_default(url, channel) title = None if "." in info.path: path = info.path.lstrip("/") image_id = path.split(".")[0] else: image_id = info.path.lstrip("/") if not self.is_valid_imgur_id(image_id): log.error("SpiffyTitles: Invalid imgur image ID") return self.handler_default(url, channel) log.debug("SpiffyTitles: found image id %s" % (image_id)) headers = {"Authorization": "Client-ID {0}".format(client_id)} api_url = "https://api.imgur.com/3/image/{0}".format(image_id) try: request = requests.get( api_url, headers=headers, timeout=self.timeout, proxies=self.proxies ) request.raise_for_status() except ( requests.exceptions.RequestException, requests.exceptions.HTTPError, ) as e: log.error("SpiffyTitles: Imgur Error: {0}".format(e)) return self.handler_default(url, channel) image = None try: image = json.loads(request.content.decode()) image = image.get("data") except: log.error("SpiffyTitles: Error reading imgur JSON response") image = None if image: channel_template = self.registryValue( "imgur.imageTemplate", channel=channel ) imgur_template = Template(channel_template) readable_file_size = self.get_readable_file_size(image["size"]) compiled_template = imgur_template.render( { "title": image.get("title"), "type": image.get("type"), "nsfw": image.get("nsfw"), "width": image.get("width"), "height": image.get("height"), "view_count": "{:,}".format(image["views"]), "file_size": readable_file_size, "section": image.get("section"), } ) title = compiled_template else: log.error("SpiffyTitles: imgur API returned unexpected results!") if title: return title else: return self.handler_default(url, channel)
Diagnosing von Willebrand disease: a short history of laboratory milestones and innovations, plus current status, challenges, and solutions. von Willebrand disease (VWD) is a disorder characterized by deficiency of, or defects in, von Willebrand factor (VWF). VWD was originally identified by Erik Adolf von Willebrand, who in early 1924 investigated a large family suffering from a bleeding disorder that seemed to differ from hemophilia. Erik von Willebrand undertook some initial laboratory investigations to conclude the involvement of a plasma factor, the lack of which prolonged the bleeding time, but failed to impair coagulation times and clot retraction. By the end of the 1960s, VWD was accepted as a combined deficiency of factor VIII (FVIII) and another plasma factor responsible for normal platelet adhesion. Just how these two functions were related to each other was less clear and the diagnostic tests available at the time were poorly reproducible, cumbersome, and unreliable; thus, VWD was poorly delineated from other coagulation and platelet disorders. The early 1970s saw a revolution in diagnostics when ristocetin was identified to induce platelet aggregation, and this formed the basis of the first consistent and reliable VWF "activity" test, permitting quantification of the platelet adhesive function missing in VWD. Concurrently, immunoprecipitating techniques specific for VWF were defined, and the application of such technologies permitted a clearer understanding of both VWF and VWD heterogeneity. Continued exploration of the structure and function of VWF contributed greatly to the understanding of platelet physiology, ligand receptor interaction and pathways of cellular interaction and activation. Recently, additional assays evaluating other functions of VWF, including collagen binding, platelet glycoprotein Ib binding, and FVIII binding, have improved the diagnosis of VWD. The purpose of this narrative review is to explore the history of phenotypic VWD diagnostics, with a focus on laboratory milestones from the past as well highlighting recent and ongoing innovations, and ongoing challenges and possible solutions.
<gh_stars>1-10 #ifndef SRC_PAYLOAD_PROCESSOR_UPLINKS_QUERY_EXCEPTIONS_UPLINK_H_ #define SRC_PAYLOAD_PROCESSOR_UPLINKS_QUERY_EXCEPTIONS_UPLINK_H_ #include <src/payload_processor/uplinks/uplink.h> class QueryExceptionsUplink : public Uplink { public: explicit QueryExceptionsUplink(byte* payload); bool ExecuteUplink(); private: // TODO(dingbenjamin): Make a Nanopb for this const uint8_t error_id; static constexpr uint8_t kQueryExceptionsUplinkArgumentLength = sizeof(uint8_t); }; #endif // SRC_PAYLOAD_PROCESSOR_SRC_PAYLOAD_PROCESSOR_UPLINKS_QUERY_EXCEPTIONS_UPLINK_H_
export * from './lib/ng2-throttle-click.module';
The Evacuation of the Noncombatant Population in the 1948 War: Three Kibbutzim as a Case Study During the 1948 Israeli War of Independence thousands of Jewish civilians, mainly women and children, became refugees when the fighting came dangerously near to their homes in the towns and agricultural settlements (moshavot, moshavim and kibbutzim). While the Jewish victory in the war turned the refugee phenomenon among the Palestinians into an ongoing tragedy, the Jewish refugee phenomenon proved temporary, lasting on average only several months, and has almost been forgotten by the Israeli collective memory. This article examines this episode in the history of the 1948 war from the viewpoint of the evacuees in three kibbutzim, and proposes a number of possible directions for research: the organizational, personal-psychological and ideological aspects of the evacuation, along with the role of national myths and symbols.
/** * __lpfc_sli_issue_iocb - Wrapper func of lockless version for issuing iocb * * This routine wraps the actual lockless version for issusing IOCB function * pointer from the lpfc_hba struct. * * Return codes: * IOCB_ERROR - Error * IOCB_SUCCESS - Success * IOCB_BUSY - Busy **/ int __lpfc_sli_issue_iocb(struct lpfc_hba *phba, uint32_t ring_number, struct lpfc_iocbq *piocb, uint32_t flag) { return phba->__lpfc_sli_issue_iocb(phba, ring_number, piocb, flag); }
// Simple Class to iterate over the modules on the PEB to add extra modularity class ModuleIterator { private: const WinDecls::LDR_DATA_TABLE_ENTRY_T* modulePtr; const WinDecls::PEB_LDR_DATA_T* Ldr; const char* base; public: ModuleIterator(const WinDecls::LDR_DATA_TABLE_ENTRY_T* _modptr, const WinDecls::PEB_LDR_DATA_T* _ldr); void next(); const char* get_base() const; const WinDecls::LDR_DATA_TABLE_ENTRY_T* get_modPtr() const; const wchar_t* get_modName() const; void reset(); }
<filename>Projeto Estoque/Projeto LabED/controle.h #ifndef CONTROLE_H_INCLUDED #define CONTROLE_H_INCLUDED void apresentacao(char* mensagem); void msgm_desp(char* mensagem); void limpa_tela(void); void limpa_buffer(void); void apresenta_menu(int n_itens, int menor_opcao, ...); int le_opcao(int menor_valor, int maior_valor); char* le_string(void); #endif // CONTROLE_H_INCLUDED
#include <iostream> using namespace std; int main() { string nombre; short int edad; short int altura; float peso; cout << "Por favor, introduce el nombre: "; cin >> nombre; cout << "Por favor, introduce la edad de " << nombre << ": "; cin >> edad; if(edad <= 0){ cout << "La edad debe ser mayor que 0" << endl; return 1; } if (edad>=115){ cout<<"Inroduzca un valor menor a 115 años"; return 1; } cout << "Por favor, introduce la altura en cm de " << nombre << ": "; cin >> altura; if(altura <= 0){ cout << "La altura debe ser mayor que 0" << endl; return 1; } cout<< "Por favor, introduce el peso en kg de "<<nombre << ": "; cin >> peso; if(peso >=200); { cout <<"El peso debe ser menor de 200 Kg "<<nombre<<endl; return 1; } }
<gh_stars>1000+ #pragma once #include <mbgl/map/map.hpp> #include <mbgl/map/map_impl.hpp> namespace mbgl { class FileSource; // Non-public version of mbgl::Map that accepts a file source as parameter. class MapAdapter : public Map { public: explicit MapAdapter(RendererFrontend& frontend, MapObserver& observer, std::shared_ptr<FileSource> fileSource, const MapOptions& options) : Map(std::make_unique<Map::Impl>(frontend, observer, std::move(fileSource), options)) {} }; } // namespace mbgl
<filename>src/App/app.tsx import React, { Component } from "react"; import "./app.scss"; import { Routes } from "../routes"; import Navigation from "../Components/Navigation/navigation"; interface AppState { showMenu: boolean; } export class App extends Component<{}, AppState> { readonly state = { showMenu: false, }; constructor(props: any) { super(props); this._updatePredicate = this._updatePredicate.bind(this); } componentDidMount() { this._updatePredicate(); window.addEventListener("resize", this._updatePredicate); } _updatePredicate() { let vh = window.innerHeight / 100; document.documentElement.style.setProperty("--vh", `${vh}px`); } _handleMenuClick = () => { this.setState({ showMenu: !this.state.showMenu }); }; render() { return ( <div className="container"> <Navigation showMenu={this.state.showMenu} closeEvent={this._handleMenuClick} /> <Routes hamburgerClicked={this._handleMenuClick} /> </div> ); } }
#ifndef XT_PULSE_SHARED_HPP #define XT_PULSE_SHARED_HPP #if XT_ENABLE_PULSE #include <xt/private/Device.hpp> #include <xt/private/Stream.hpp> #include <xt/private/Service.hpp> #include <xt/blocking/Device.hpp> #include <xt/blocking/Stream.hpp> #include <xt/private/DeviceList.hpp> #include <xt/backend/pulse/Private.hpp> #include <pulse/simple.h> #include <pulse/pulseaudio.h> #include <cstdint> #include <vector> struct PulseService final: public XtService { XT_IMPLEMENT_SERVICE(Pulse); }; struct PulseDevice final: public XtBlockingDevice { bool const _output; XT_IMPLEMENT_DEVICE(); XT_IMPLEMENT_DEVICE_BLOCKING(); XT_IMPLEMENT_DEVICE_BASE(Pulse); PulseDevice(bool output); }; struct PulseStream final: public XtBlockingStream { bool _output; XtPaSimple _pa; int32_t _frames; std::vector<uint8_t> _audio; PulseStream() = default; XT_IMPLEMENT_STREAM_BASE(); XT_IMPLEMENT_BLOCKING_STREAM(); XT_IMPLEMENT_STREAM_BASE_SYSTEM(Pulse); }; struct PulseDeviceList final: public XtDeviceList { bool const _input; bool const _output; XT_IMPLEMENT_DEVICE_LIST(Pulse); PulseDeviceList(bool input, bool output); }; #endif // XT_ENABLE_PULSE #endif // XT_PULSE_SHARED_HPP
In this image provided by IntelCenter, Sgt. Bowe Bergdahl is seen while in captivity. (AFP/Getty Images) Bowe Bergdahl, the Army sergeant now facing charges of desertion and misbehaving before the enemy, has remained outside the public spotlight since he was recovered in a prisoner swap and returned to U.S. custody last spring. He has not spoken to reporters and has never detailed the conditions of his five-year captivity. On Wednesday, shortly after the Army announced its decision in the 28-year-old soldier’s case, Bergdahl’s lawyer released a statement that his client sent the commanding general overseeing the investigation into his disappearance. In it, the soldier describes the conditions of his captivity as brutal, saying he endured beatings, severe hunger and threats of execution. He also describes his failed attempts to escape. “I was kept in constant isolation during the entire 5 years, with little to no understanding of time, through constant periods of constant darkness, periods of constant light, and periods of completely random flickering of light,” he wrote at one point. He added that he had “absolutely no understanding of anything that was happening beyond the door I was held behind.” Here is the full statement provided by Bergdahl’s lawyer, Eugene Fidell. Bowe Bergdahl in his own words
import useGqlHandler from "./useGqlHandler"; import { assignMenuLifecycleEvents, tracker } from "./mocks/lifecycleEvents"; const id = "menu-lifecycle-events"; const slug = "menu-lifecycle-events"; const title = "Menu Lifecycle Events"; const description = "Menu Description"; const items: any[] = []; describe("Menu Lifecycle Events", () => { const handler = useGqlHandler({ plugins: [assignMenuLifecycleEvents()] }); const { createMenu, updateMenu, deleteMenu } = handler; beforeEach(async () => { tracker.reset(); }); it("should trigger create lifecycle events", async () => { const [response] = await createMenu({ data: { id, title, slug, description, items } }); expect(response).toMatchObject({ data: { pageBuilder: { createMenu: { data: { title, slug, items, description }, error: null } } } }); expect(tracker.isExecutedOnce("menu:beforeCreate")).toEqual(true); expect(tracker.isExecutedOnce("menu:afterCreate")).toEqual(true); expect(tracker.isExecutedOnce("menu:beforeUpdate")).toEqual(false); expect(tracker.isExecutedOnce("menu:afterUpdate")).toEqual(false); expect(tracker.isExecutedOnce("menu:beforeDelete")).toEqual(false); expect(tracker.isExecutedOnce("menu:afterDelete")).toEqual(false); }); it("should trigger update lifecycle events", async () => { await createMenu({ data: { id, title, slug, description, items } }); tracker.reset(); const [response] = await updateMenu({ slug: slug, data: { slug, title: `${title} updated` } }); expect(response).toMatchObject({ data: { pageBuilder: { updateMenu: { data: { title: `${title} updated`, slug }, error: null } } } }); expect(tracker.isExecutedOnce("menu:beforeCreate")).toEqual(false); expect(tracker.isExecutedOnce("menu:afterCreate")).toEqual(false); expect(tracker.isExecutedOnce("menu:beforeUpdate")).toEqual(true); expect(tracker.isExecutedOnce("menu:afterUpdate")).toEqual(true); expect(tracker.isExecutedOnce("menu:beforeDelete")).toEqual(false); expect(tracker.isExecutedOnce("menu:afterDelete")).toEqual(false); }); it("should trigger delete lifecycle events", async () => { await createMenu({ data: { id, title, slug, description, items } }); tracker.reset(); const [response] = await deleteMenu({ slug }); expect(response).toMatchObject({ data: { pageBuilder: { deleteMenu: { data: { title, items, description, slug }, error: null } } } }); expect(tracker.isExecutedOnce("menu:beforeCreate")).toEqual(false); expect(tracker.isExecutedOnce("menu:afterCreate")).toEqual(false); expect(tracker.isExecutedOnce("menu:beforeUpdate")).toEqual(false); expect(tracker.isExecutedOnce("menu:afterUpdate")).toEqual(false); expect(tracker.isExecutedOnce("menu:beforeDelete")).toEqual(true); expect(tracker.isExecutedOnce("menu:afterDelete")).toEqual(true); }); });
Pocket Certificates using Double Encryption: A Survey : Documents are items that convey information, can be used to certify someone, or can constitute a legal report. Theft of such crucial documents/certificates can obstruct or hinder an individual's or organization's ability to execute their work effectively, as well as result in the loss of personal belongings. "Pocket Certificates" - a traditional document archive with the possibility of securely preserving such papers - is provided in this text. The answer is to utilise a Double Encryption system that combines the AES and 3DES encryption standards. The use of improved security can be considered of as a tradeoff in a system's stability and smooth operation, however there are specific limitations that must be imposed so that the Encryption/Decryption process does not obstruct usability. This work considers such characteristics and strikes a balance between them all. Other Hashing methods are also used, such as bycrypt for securely storing user login data and passport middleware for each application stage's specific user authentication needs. The paper comprises of a comprehensive online application for the safe archiving of essential documents or data. INTRODUCTION Physical documents are currently used by more than 70% of people. Physical copies of documents suffer significant overhead in terms of security, paper storage, manual audits, and other areas, resulting in significant expense and annoyance. The modern workplace necessitates the implementation of suitable security measures for all types of paperwork, digital and otherwise. While stealing papers from a traditional cabinet locker is simple, digital theft, replication, and deletion can be more difficult. The use of encryption technologies in conjunction with proper document structure will ensure that sensitive material remains safe. The Pocket Certificates System is designed to employ both AES and 3DES algorithms in tandem for secure and irreversible document storage. It also seeks to verify that the user's identity is genuine and unharmed, which is accomplished by using the passport function to verify the user's authenticity and the crypt function to store the password in a safe hashed/encrypted format. The system is built to be as dependable, useful, and smooth as possible while maintaining the security of the documents saved in the database. II. LITERATURE REVIEW Almost all govt documents in India are presently available in tangible form across the country. This implies that if a resident has to share a document with an agency in order to acquire a service, an attested photocopy is given, either in physical or digitised form. Utilization of actual duplicates of archive makes gigantic upward with regards to manual confirmation, paper capacity, manual reviews, and so forth bringing about significant expense and bother. This makes issue for different offices to check the legitimacy of these reports, accordingly, making provisos for utilization of phony records/testaments. Because of the idea of these archives not having a solid character appended to it, anybody with same name can for sure abuse another person's report. - III. AES AND DES ENCRIPTION TECHNOLOGY Typical symmetric block cyphers are DES (Data Encryption Standard) and AES (Advanced Encryption Standard). To alleviate the disadvantages of DES, AES was devised. Due to the decreased key size of DES, which makes it less safe, triple DES was created, but it proved to be slower. As a result, the National Institute of Standards and Technology later introduced AES. A. DES (Data Encryption Standard) The Feistel structure divides plaintext into two halves, which is the basis for DES. DES generates 64-bit Ciphertext from 64-bit plain text and a 56-bit key. - ©IJRASET: All Rights are Reserved | SJ Impact Factor 7.538 | ISRA Journal Impact Factor 7.894 | The following functions are included in each round: Expansion Permutation: The 32-bit right component is enlarged to a 48-bit right portion in this example. 1) XOR (Whitener): DES performs an XOR operation on the enlarged right section and the round key after the expansion permutation. This action necessitates the usage of the round key. The 48-bit right part is Xored with the 48-bit subkey extracted from the 56-bit key, yielding a 48-bit output. 2) Substitution Boxes (S-boxes): The S-boxes are in charge of the actual mixing (confusion). Eight S-boxes, each with a 6-bit input and 4-bit output, are used in the DES algorithm. The 48-bit output from the Xor stage is reduced to 32 bits once more. 3) P-box: The 32-bit result from S-box is permuted once again, resulting in 32-bit permuted output. B. AES (Advanced Encryption Standard) Because DES utilises a relatively short encryption key and the technique is rather sluggish, AES was created to replace it. The AES method uses a 128-bit plaintext and a 128-bit secret key to create a 128-bit block that can be represented as a 4 X 4 square matrix. An initial transformation is performed on this 4 X 4 square matrix. The 10 rounds come after this phase. The following stages are included in the nine rounds: The following is the procedure for carrying out the shift: a) The first row has not been moved. b) The second row is moved one (byte) to the left. c) The third row has been moved two spaces to the left. d) The fourth row is moved three spaces to the left. e) The outcome is a new matrix made up of the same 16 bytes that have been moved in relation to each other. 3) Mix Columns: The matrix's columns are shuffled from right to left. Each four-byte column is now altered using a specific mathematical function. This method takes four bytes from one column as input and returns four entirely new bytes that replace the original column. As a consequence, a new matrix with 16 additional bytes is created. It's worth mentioning that in the final round, this step is bypassed. 4) Add Round Keys: This does a Xor of the current block and the expanded key. The final tenth round uses just Subbytes, Shift Rows, and Add round keys phases, yielding a ciphertext of 16 bytes (128 bits). IV. PROPOSED SYSTEM Pocket Certificates is a sophisticated programme in which file storage makes it highly efficient and trustworthy because we don't have to carry all of our documents with us all of the time. Legal documents, such as passports and birth certificates, are extremely valuable and can be exploited. Putting information on any server is a risky move since it may be hacked, and keeping it on our phone is more worse. To avoid any type of internal or external hacking, we designed a mechanism that saves the submitted document in an encrypted form and keeps it in the Internal Memory. The key benefit of this approach is that it requires a Secure Pin to access the file that we input when we register. If our phone is in someone's hands, they won't be able to access the data because of the secure pin. The files are protected in a variety of ways to ensure that no unauthorised individuals have access to them. To support the application, we use SQL as the backend. ©IJRASET: All Rights are Reserved | SJ Impact Factor 7.538 | ISRA Journal Impact Factor 7.894 | ENCRYPTION AND DECRYPTION PHASE We all function on the internet, interact on the internet, and want our data and information to be safe, which cryptography allows us to achieve. Cryptography protects our personal data and information from other users and attackers. Encryption and decryption are the two most important functions of cryptography. , A. Encryption Techniques Encryption is the process of converting a sender's original communication into an unreadable format that no one on the network can read or understand. It turns a regular communication, such as plain text, into ciphertext, which is nonsensical or worthless. The unintelligible version of the message is completely different from the original message. As a result, attackers and many other agents are unable to read the data since senders use an encryption technique to convey the data. It occurs at the sender's end. Using the secret key or public key, the communication may be readily encrypted. The process of applying the encryption technique and converting the original message and data to ciphertext is depicted in the diagram below. B. Decryption Techniques Decryption is the process of converting an encrypted code or data into a form that can be understood and read by a person or computer. This is referred to as decrypting encrypted data. It occurs at the receiving end. The secret key or the private key can be used to decode the communication. The decryption procedure is shown in the picture below, as well as the encrypted text (i.e., the ciphertext is transformed back to the original message). C. Keys are available in a variety of shapes and sizes. There are a few important presents that assist in the encryption and decryption process. Let's take a closer look at the keys that are available. D. Key That Is Symmetric This key is used in the Symmetric Encryption algorithm, which is also known as the Symmetric-key encryption algorithm. The encryption of plaintext on the sender's side and the decryption of ciphertext on the receiver's side are both done with the same cryptographic keys. E. Key That Is Asymmetric The asymmetric key encryption algorithm employs two sets of keys for encryption. These two distinct keys are used to encrypt and decrypt data, respectively. The public key is accessible to everybody, but the secret key is only accessible to the message's recipient. When compared to symmetric key encryption, this gives higher security. F. Key that is Made Public The keys that are used to encrypt the message for the receiver are known as public keys. This cryptography is a key-based encryption scheme using two pairs of keys. G. Secret Key Because the private key may be used to encrypt and decrypt data, it is commonly employed with asymmetric encryption algorithms. It might also be a component of an asymmetric public/private key pair. H. Key That Has Been Pre-Shared PSK is a shared secret key that was previously shared between two distinct organisations or persons through a secure channel before being utilised. VI. CRYPTOGRAPHY TECHNIQUES PHASE Here are some simple codes and more advanced contemporary encryption methods that are now utilised on the Internet. A. Simple Codes This category encompasses any method of writing a message side by side that makes it difficult for others to read. This entails writing in a different alphabet. We can see Icelandic runes and IPA, as well as other niche-built alphabets like the Deseret Alphabet, here. ©IJRASET: All Rights are Reserved | SJ Impact Factor 7.538 | ISRA Journal Impact Factor 7.894 | We can utilise language to code in this. We investigated the origins of invented languages like Elvish and Esperanto. The book Code Talker by Chester Naz and Judith Schiess Avila discusses how the Navajo language was utilised as a code during WWII and how it was never cracked under harsh situations. If the Navajo language lacked words for a concept, the code speakers came up with a phrase. For example, the Navajo term for "hummingbird" had become a fighter jet, while "iron cap" had been Germany. B. Symmetric Encryption Symmetrical encryption is a kind of encryption that uses just one key to encode and decode electronic data (a secret key). Symmetrical encryption techniques like substitution cyphers exist, but current symmetric encryption may be far more sophisticated. Using symmetrical encryption techniques, data is turned into a format that no one can decipher without a secret key. Symmetric encryption is an older algorithm than asymmetric encryption, yet it is quicker and more efficient. Because of symmetric encryption's superior performance and quickness as compared to asymmetric encryption. Symmetric key cryptography, on the other hand, uses the same key for both encryption and decryption. Asymmetric key cryptography uses one key for encryption and a separate key for decryption at the same time. Symmetric encryption is common for large amounts of data, such as database encryption and bulk encryption. The secret key can only be encrypted or decrypted by the database itself in the event of a database. C. Asymmetric Encryption Public-key cryptography is another name for asymmetric encryption. Asymmetric key encryption aids in the resolution of the symmetric key cryptography key exchange problem. In asymmetrical encryption, two keys are utilised to encrypt plain text. The secret keys are shared across the internet or a large network. Because anybody with a secret key may decrypt the message, asymmetric encryption employs two matching keys to boost security. A public key will be publicly accessible to everyone who chooses to send you a message, while the second private key will be kept hidden for you to comprehend alone. A private key can decode a message encrypted using a public key. With a public key, a communication encrypted with a private key may be deciphered. D. Steganography Steganography is a technology that allows a message to be hidden inside another message. People employed invisible ink, minute changes, and other means to hide messages in the past. However, in today's technological world, Steganography is a technique for hiding data, which can be a file, message, picture, or other type of data, among other files, messages, or images. E. Hashing Hashing is a cryptographic technique for converting any type of data into a single string. Any data may be hashed using a hashing algorithm, regardless of its size or nature. It turns data of arbitrary length into a fixed hashed value. Hashing differs from other encryption methods in that it does not allow for reverse encryption; that is, it cannot be decoded using keys. The most extensively used hashing algorithms are MD5, SHA1, and SHA 256. VII. FUTURE SCOPE 1) Demand Balancing: Because the system will only be accessible to administrators, the amount of load placed on the server will be restricted to the duration of admin access. 2) Easy Accessibility: Records and other information may be retrieved and stored with ease. 3) User-Friendly: The website will cater to all users in a highly user-friendly manner. 4) Efficient and Dependable: Keeping everything secure and database on the server, which will be available according to user requirements without any maintenance costs, will be a lot more efficient than storing all client data on spreadsheets or in physical record books. 5) Simple to Maintain: Pocket Certificates with Double Encryption are designed to be simple to maintain. As a result, upkeep is also simple. VIII. CONCLUSION In this work, a dual encrypted method for storing users' private papers is presented. The fundamental goal of using many encryption layers was to maintain the CIA trinity of secrecy, authenticity, and integrity of the user's data as well as the system's validity. Most assaults, such as brute force and the use of other tools to compromise the system's security, are prevented by using many levels of encryption. Multiple encryptions may slow down the system's speed, but it may slow down assailants, who would need a lot more storage if they used comparison lists on more than one encryption level. IX. ACKNOWLEDGMENT I want to specially thank Dr. Umarani .C for guiding me throughout this research paper, which has expanded my knowledge on data security and cyber security. Without her support I do not think this research paper will be been a success, I am very thankful.
{-# LANGUAGE OverloadedStrings #-} module CmdExport where import Turtle import Turtle.Bytes as TB import Prelude hiding (FilePath) import Command import Repository -- | Speciffic command options. data CmdOptions = CmdOptions { cmdRepo :: Repository , cmdBlob :: Text , cmdStat :: Bool } deriving (Eq, Show) -- | Option parser. parseOptions :: Parser CmdOptions parseOptions = CmdOptions <$> fmap Repository (optPath "repository" 'R' "Repository path") <*> argText "BLOB" "blob hash value" <*> switch "stat" 'n' "don't export, just print size" parser :: CommandName -> Parser Command parser name = runCmd <$> subcommand name "Export blob" parseOptions runCmd :: CmdOptions -> Command runCmd cmd _problem _ctx = do let blobHash = cmdBlob cmd repo <- using $ managed (withLockedRepo (cmdRepo cmd) Shared) case cmdStat cmd of False -> TB.stdout $ exportBlob repo blobHash True -> do size <- statBlob repo blobHash liftIO $ print size
package aQute.bnd.osgi; import java.io.*; public abstract class AbstractResource implements Resource { String extra; byte[] calculated; long lastModified; protected AbstractResource(long modified) { lastModified = modified; } public String getExtra() { return extra; } public long lastModified() { return lastModified; } public InputStream openInputStream() throws IOException { return new ByteArrayInputStream(getLocalBytes()); } private byte[] getLocalBytes() throws IOException { try { if (calculated != null) return calculated; return calculated = getBytes(); } catch (IOException e) { throw e; } catch (Exception e) { IOException ee = new IOException("Opening resource"); ee.initCause(e); throw ee; } } public void setExtra(String extra) { this.extra = extra; } public void write(OutputStream out) throws IOException { out.write(getLocalBytes()); } abstract protected byte[] getBytes() throws Exception; public long size() throws IOException { return getLocalBytes().length; } }
/** * Launches a file using the appropriate method */ private void launchFile(String file, String urlOrQuery) { if (file == null) { displayNoFileSelectedTooltip(); return; } RunTargetType appType = RunButtonTargetPopup.RunTargetType.parseTargetType(file); launchPreview(file, StringUtils.nullToEmpty(urlOrQuery)); }
<reponame>NDNLink/NDNProtocol // Copyright 2020 Parity Technologies (UK) Ltd. // This file is part of Polkadot. // Polkadot 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. // Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>. //! # Overseer //! //! `overseer` implements the Overseer architecture described in the //! [implementers-guide](https://github.com/paritytech/polkadot/blob/master/roadmap/implementers-guide/guide.md). //! For the motivations behind implementing the overseer itself you should //! check out that guide, documentation in this crate will be mostly discussing //! technical stuff. //! //! An `Overseer` is something that allows spawning/stopping and overseing //! asynchronous tasks as well as establishing a well-defined and easy to use //! protocol that the tasks can use to communicate with each other. It is desired //! that this protocol is the only way tasks communicate with each other, however //! at this moment there are no foolproof guards against other ways of communication. //! //! The `Overseer` is instantiated with a pre-defined set of `Subsystems` that //! share the same behavior from `Overseer`'s point of view. //! //! ```text //! +-----------------------------+ //! | Overseer | //! +-----------------------------+ //! //! ................| Overseer "holds" these and uses |.............. //! . them to (re)start things . //! . . //! . +-------------------+ +---------------------+ . //! . | Subsystem1 | | Subsystem2 | . //! . +-------------------+ +---------------------+ . //! . | | . //! .................................................................. //! | | //! start() start() //! V V //! ..................| Overseer "runs" these |....................... //! . +--------------------+ +---------------------+ . //! . | SubsystemInstance1 | | SubsystemInstance2 | . //! . +--------------------+ +---------------------+ . //! .................................................................. //! ``` use std::fmt::Debug; use std::pin::Pin; use std::sync::Arc; use std::task::Poll; use std::time::Duration; use std::collections::{hash_map, HashMap}; use futures::channel::{mpsc, oneshot}; use futures::{ pending, poll, select, future::BoxFuture, stream::{self, FuturesUnordered}, Future, FutureExt, SinkExt, StreamExt, }; use futures_timer::Delay; use streamunordered::{StreamYield, StreamUnordered}; use polkadot_primitives::v1::{Block, BlockNumber, Hash}; use client::{BlockImportNotification, BlockchainEvents, FinalityNotification}; use polkadot_subsystem::messages::{ CandidateValidationMessage, CandidateBackingMessage, CandidateSelectionMessage, ChainApiMessage, StatementDistributionMessage, AvailabilityDistributionMessage, BitfieldSigningMessage, BitfieldDistributionMessage, ProvisionerMessage, PoVDistributionMessage, RuntimeApiMessage, AvailabilityStoreMessage, NetworkBridgeMessage, AllMessages, CollationGenerationMessage, CollatorProtocolMessage, }; pub use polkadot_subsystem::{ Subsystem, SubsystemContext, OverseerSignal, FromOverseer, SubsystemError, SubsystemResult, SpawnedSubsystem, ActiveLeavesUpdate, metrics::{self, prometheus}, }; use polkadot_node_primitives::SpawnNamed; // A capacity of bounded channels inside the overseer. const CHANNEL_CAPACITY: usize = 1024; // A graceful `Overseer` teardown time delay. const STOP_DELAY: u64 = 1; // Target for logs. const LOG_TARGET: &'static str = "overseer"; /// A type of messages that are sent from [`Subsystem`] to [`Overseer`]. /// /// It wraps a system-wide [`AllMessages`] type that represents all possible /// messages in the system. /// /// [`AllMessages`]: enum.AllMessages.html /// [`Subsystem`]: trait.Subsystem.html /// [`Overseer`]: struct.Overseer.html enum ToOverseer { /// This is a message sent by a `Subsystem`. SubsystemMessage(AllMessages), /// A message that wraps something the `Subsystem` is desiring to /// spawn on the overseer and a `oneshot::Sender` to signal the result /// of the spawn. SpawnJob { name: &'static str, s: BoxFuture<'static, ()>, }, /// Same as `SpawnJob` but for blocking tasks to be executed on a /// dedicated thread pool. SpawnBlockingJob { name: &'static str, s: BoxFuture<'static, ()>, }, } /// An event telling the `Overseer` on the particular block /// that has been imported or finalized. /// /// This structure exists solely for the purposes of decoupling /// `Overseer` code from the client code and the necessity to call /// `HeaderBackend::block_number_from_id()`. pub struct BlockInfo { /// hash of the block. pub hash: Hash, /// hash of the parent block. pub parent_hash: Hash, /// block's number. pub number: BlockNumber, } impl From<BlockImportNotification<Block>> for BlockInfo { fn from(n: BlockImportNotification<Block>) -> Self { BlockInfo { hash: n.hash, parent_hash: n.header.parent_hash, number: n.header.number, } } } impl From<FinalityNotification<Block>> for BlockInfo { fn from(n: FinalityNotification<Block>) -> Self { BlockInfo { hash: n.hash, parent_hash: n.header.parent_hash, number: n.header.number, } } } /// Some event from outer world. enum Event { BlockImported(BlockInfo), BlockFinalized(BlockInfo), MsgToSubsystem(AllMessages), ExternalRequest(ExternalRequest), Stop, } /// Some request from outer world. enum ExternalRequest { WaitForActivation { hash: Hash, response_channel: oneshot::Sender<()>, }, } /// A handler used to communicate with the [`Overseer`]. /// /// [`Overseer`]: struct.Overseer.html #[derive(Clone)] pub struct OverseerHandler { events_tx: mpsc::Sender<Event>, } impl OverseerHandler { /// Inform the `Overseer` that that some block was imported. pub async fn block_imported(&mut self, block: BlockInfo) -> SubsystemResult<()> { self.events_tx.send(Event::BlockImported(block)).await.map_err(Into::into) } /// Send some message to one of the `Subsystem`s. pub async fn send_msg(&mut self, msg: AllMessages) -> SubsystemResult<()> { self.events_tx.send(Event::MsgToSubsystem(msg)).await.map_err(Into::into) } /// Inform the `Overseer` that that some block was finalized. pub async fn block_finalized(&mut self, block: BlockInfo) -> SubsystemResult<()> { self.events_tx.send(Event::BlockFinalized(block)).await.map_err(Into::into) } /// Wait for a block with the given hash to be in the active-leaves set. /// This method is used for external code like `Proposer` that doesn't subscribe to Overseer's signals. /// /// The response channel responds if the hash was activated and is closed if the hash was deactivated. /// Note that due the fact the overseer doesn't store the whole active-leaves set, only deltas, /// the response channel may never return if the hash was deactivated before this call. /// In this case, it's the caller's responsibility to ensure a timeout is set. pub async fn wait_for_activation(&mut self, hash: Hash, response_channel: oneshot::Sender<()>) -> SubsystemResult<()> { self.events_tx.send(Event::ExternalRequest(ExternalRequest::WaitForActivation { hash, response_channel })).await.map_err(Into::into) } /// Tell `Overseer` to shutdown. pub async fn stop(&mut self) -> SubsystemResult<()> { self.events_tx.send(Event::Stop).await.map_err(Into::into) } } /// Glues together the [`Overseer`] and `BlockchainEvents` by forwarding /// import and finality notifications into the [`OverseerHandler`]. /// /// [`Overseer`]: struct.Overseer.html /// [`OverseerHandler`]: struct.OverseerHandler.html pub async fn forward_events<P: BlockchainEvents<Block>>( client: Arc<P>, mut handler: OverseerHandler, ) -> SubsystemResult<()> { let mut finality = client.finality_notification_stream(); let mut imports = client.import_notification_stream(); loop { select! { f = finality.next() => { match f { Some(block) => { handler.block_finalized(block.into()).await?; } None => break, } }, i = imports.next() => { match i { Some(block) => { handler.block_imported(block.into()).await?; } None => break, } }, complete => break, } } Ok(()) } impl Debug for ToOverseer { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ToOverseer::SubsystemMessage(msg) => { write!(f, "OverseerMessage::SubsystemMessage({:?})", msg) } ToOverseer::SpawnJob { .. } => write!(f, "OverseerMessage::Spawn(..)"), ToOverseer::SpawnBlockingJob { .. } => write!(f, "OverseerMessage::SpawnBlocking(..)") } } } /// A running instance of some [`Subsystem`]. /// /// [`Subsystem`]: trait.Subsystem.html struct SubsystemInstance<M> { tx: mpsc::Sender<FromOverseer<M>>, } /// A context type that is given to the [`Subsystem`] upon spawning. /// It can be used by [`Subsystem`] to communicate with other [`Subsystem`]s /// or to spawn it's [`SubsystemJob`]s. /// /// [`Overseer`]: struct.Overseer.html /// [`Subsystem`]: trait.Subsystem.html /// [`SubsystemJob`]: trait.SubsystemJob.html #[derive(Debug)] pub struct OverseerSubsystemContext<M>{ rx: mpsc::Receiver<FromOverseer<M>>, tx: mpsc::Sender<ToOverseer>, } #[async_trait::async_trait] impl<M: Send + 'static> SubsystemContext for OverseerSubsystemContext<M> { type Message = M; async fn try_recv(&mut self) -> Result<Option<FromOverseer<M>>, ()> { match poll!(self.rx.next()) { Poll::Ready(Some(msg)) => Ok(Some(msg)), Poll::Ready(None) => Err(()), Poll::Pending => Ok(None), } } async fn recv(&mut self) -> SubsystemResult<FromOverseer<M>> { self.rx.next().await.ok_or(SubsystemError) } async fn spawn(&mut self, name: &'static str, s: Pin<Box<dyn Future<Output = ()> + Send>>) -> SubsystemResult<()> { self.tx.send(ToOverseer::SpawnJob { name, s, }).await.map_err(Into::into) } async fn spawn_blocking(&mut self, name: &'static str, s: Pin<Box<dyn Future<Output = ()> + Send>>) -> SubsystemResult<()> { self.tx.send(ToOverseer::SpawnBlockingJob { name, s, }).await.map_err(Into::into) } async fn send_message(&mut self, msg: AllMessages) -> SubsystemResult<()> { self.tx.send(ToOverseer::SubsystemMessage(msg)).await.map_err(Into::into) } async fn send_messages<T>(&mut self, msgs: T) -> SubsystemResult<()> where T: IntoIterator<Item = AllMessages> + Send, T::IntoIter: Send { let mut msgs = stream::iter(msgs.into_iter().map(ToOverseer::SubsystemMessage).map(Ok)); self.tx.send_all(&mut msgs).await.map_err(Into::into) } } /// A subsystem that we oversee. /// /// Ties together the [`Subsystem`] itself and it's running instance /// (which may be missing if the [`Subsystem`] is not running at the moment /// for whatever reason). /// /// [`Subsystem`]: trait.Subsystem.html struct OverseenSubsystem<M> { instance: Option<SubsystemInstance<M>>, } /// The `Overseer` itself. pub struct Overseer<S: SpawnNamed> { /// A candidate validation subsystem. candidate_validation_subsystem: OverseenSubsystem<CandidateValidationMessage>, /// A candidate backing subsystem. candidate_backing_subsystem: OverseenSubsystem<CandidateBackingMessage>, /// A candidate selection subsystem. candidate_selection_subsystem: OverseenSubsystem<CandidateSelectionMessage>, /// A statement distribution subsystem. statement_distribution_subsystem: OverseenSubsystem<StatementDistributionMessage>, /// An availability distribution subsystem. availability_distribution_subsystem: OverseenSubsystem<AvailabilityDistributionMessage>, /// A bitfield signing subsystem. bitfield_signing_subsystem: OverseenSubsystem<BitfieldSigningMessage>, /// A bitfield distribution subsystem. bitfield_distribution_subsystem: OverseenSubsystem<BitfieldDistributionMessage>, /// A provisioner subsystem. provisioner_subsystem: OverseenSubsystem<ProvisionerMessage>, /// A PoV distribution subsystem. pov_distribution_subsystem: OverseenSubsystem<PoVDistributionMessage>, /// A runtime API subsystem. runtime_api_subsystem: OverseenSubsystem<RuntimeApiMessage>, /// An availability store subsystem. availability_store_subsystem: OverseenSubsystem<AvailabilityStoreMessage>, /// A network bridge subsystem. network_bridge_subsystem: OverseenSubsystem<NetworkBridgeMessage>, /// A Chain API subsystem. chain_api_subsystem: OverseenSubsystem<ChainApiMessage>, /// A Collation Generation subsystem. collation_generation_subsystem: OverseenSubsystem<CollationGenerationMessage>, /// A Collator Protocol subsystem. collator_protocol_subsystem: OverseenSubsystem<CollatorProtocolMessage>, /// Spawner to spawn tasks to. s: S, /// Here we keep handles to spawned subsystems to be notified when they terminate. running_subsystems: FuturesUnordered<BoxFuture<'static, ()>>, /// Gather running subsystms' outbound streams into one. running_subsystems_rx: StreamUnordered<mpsc::Receiver<ToOverseer>>, /// Events that are sent to the overseer from the outside world events_rx: mpsc::Receiver<Event>, /// External listeners waiting for a hash to be in the active-leave set. activation_external_listeners: HashMap<Hash, Vec<oneshot::Sender<()>>>, /// A set of leaves that `Overseer` starts working with. /// /// Drained at the beginning of `run` and never used again. leaves: Vec<(Hash, BlockNumber)>, /// The set of the "active leaves". active_leaves: HashMap<Hash, BlockNumber>, /// Various Prometheus metrics. metrics: Metrics, } /// This struct is passed as an argument to create a new instance of an [`Overseer`]. /// /// As any entity that satisfies the interface may act as a [`Subsystem`] this allows /// mocking in the test code: /// /// Each [`Subsystem`] is supposed to implement some interface that is generic over /// message type that is specific to this [`Subsystem`]. At the moment not all /// subsystems are implemented and the rest can be mocked with the [`DummySubsystem`]. /// /// [`Subsystem`]: trait.Subsystem.html /// [`DummySubsystem`]: struct.DummySubsystem.html pub struct AllSubsystems<CV, CB, CS, SD, AD, BS, BD, P, PoVD, RA, AS, NB, CA, CG, CP> { /// A candidate validation subsystem. pub candidate_validation: CV, /// A candidate backing subsystem. pub candidate_backing: CB, /// A candidate selection subsystem. pub candidate_selection: CS, /// A statement distribution subsystem. pub statement_distribution: SD, /// An availability distribution subsystem. pub availability_distribution: AD, /// A bitfield signing subsystem. pub bitfield_signing: BS, /// A bitfield distribution subsystem. pub bitfield_distribution: BD, /// A provisioner subsystem. pub provisioner: P, /// A PoV distribution subsystem. pub pov_distribution: PoVD, /// A runtime API subsystem. pub runtime_api: RA, /// An availability store subsystem. pub availability_store: AS, /// A network bridge subsystem. pub network_bridge: NB, /// A Chain API subsystem. pub chain_api: CA, /// A Collation Generation subsystem. pub collation_generation: CG, /// A Collator Protocol subsystem. pub collator_protocol: CP, } /// Overseer Prometheus metrics. #[derive(Clone)] struct MetricsInner { activated_heads_total: prometheus::Counter<prometheus::U64>, deactivated_heads_total: prometheus::Counter<prometheus::U64>, } #[derive(Default, Clone)] struct Metrics(Option<MetricsInner>); impl Metrics { fn on_head_activated(&self) { if let Some(metrics) = &self.0 { metrics.activated_heads_total.inc(); } } fn on_head_deactivated(&self) { if let Some(metrics) = &self.0 { metrics.deactivated_heads_total.inc(); } } } impl metrics::Metrics for Metrics { fn try_register(registry: &prometheus::Registry) -> Result<Self, prometheus::PrometheusError> { let metrics = MetricsInner { activated_heads_total: prometheus::register( prometheus::Counter::new( "parachain_activated_heads_total", "Number of activated heads." )?, registry, )?, deactivated_heads_total: prometheus::register( prometheus::Counter::new( "parachain_deactivated_heads_total", "Number of deactivated heads." )?, registry, )?, }; Ok(Metrics(Some(metrics))) } } impl<S> Overseer<S> where S: SpawnNamed, { /// Create a new intance of the `Overseer` with a fixed set of [`Subsystem`]s. /// /// ```text /// +------------------------------------+ /// | Overseer | /// +------------------------------------+ /// / | | \ /// ................. subsystems................................... /// . +-----------+ +-----------+ +----------+ +---------+ . /// . | | | | | | | | . /// . +-----------+ +-----------+ +----------+ +---------+ . /// ............................................................... /// | /// probably `spawn` /// a `job` /// | /// V /// +-----------+ /// | | /// +-----------+ /// /// ``` /// /// [`Subsystem`]: trait.Subsystem.html /// /// # Example /// /// The [`Subsystems`] may be any type as long as they implement an expected interface. /// Here, we create a mock validation subsystem and a few dummy ones and start the `Overseer` with them. /// For the sake of simplicity the termination of the example is done with a timeout. /// ``` /// # use std::time::Duration; /// # use futures::{executor, pin_mut, select, FutureExt}; /// # use futures_timer::Delay; /// # use polkadot_overseer::{Overseer, AllSubsystems}; /// # use polkadot_subsystem::{ /// # Subsystem, DummySubsystem, SpawnedSubsystem, SubsystemContext, /// # messages::CandidateValidationMessage, /// # }; /// /// struct ValidationSubsystem; /// /// impl<C> Subsystem<C> for ValidationSubsystem /// where C: SubsystemContext<Message=CandidateValidationMessage> /// { /// type Metrics = (); /// /// fn start( /// self, /// mut ctx: C, /// ) -> SpawnedSubsystem { /// SpawnedSubsystem { /// name: "validation-subsystem", /// future: Box::pin(async move { /// loop { /// Delay::new(Duration::from_secs(1)).await; /// } /// }), /// } /// } /// } /// /// # fn main() { executor::block_on(async move { /// let spawner = sp_core::testing::TaskExecutor::new(); /// let all_subsystems = AllSubsystems { /// candidate_validation: ValidationSubsystem, /// candidate_backing: DummySubsystem, /// candidate_selection: DummySubsystem, /// statement_distribution: DummySubsystem, /// availability_distribution: DummySubsystem, /// bitfield_signing: DummySubsystem, /// bitfield_distribution: DummySubsystem, /// provisioner: DummySubsystem, /// pov_distribution: DummySubsystem, /// runtime_api: DummySubsystem, /// availability_store: DummySubsystem, /// network_bridge: DummySubsystem, /// chain_api: DummySubsystem, /// collation_generation: DummySubsystem, /// collator_protocol: DummySubsystem, /// }; /// let (overseer, _handler) = Overseer::new( /// vec![], /// all_subsystems, /// None, /// spawner, /// ).unwrap(); /// /// let timer = Delay::new(Duration::from_millis(50)).fuse(); /// /// let overseer_fut = overseer.run().fuse(); /// pin_mut!(timer); /// pin_mut!(overseer_fut); /// /// select! { /// _ = overseer_fut => (), /// _ = timer => (), /// } /// # /// # }); } /// ``` pub fn new<CV, CB, CS, SD, AD, BS, BD, P, PoVD, RA, AS, NB, CA, CG, CP>( leaves: impl IntoIterator<Item = BlockInfo>, all_subsystems: AllSubsystems<CV, CB, CS, SD, AD, BS, BD, P, PoVD, RA, AS, NB, CA, CG, CP>, prometheus_registry: Option<&prometheus::Registry>, mut s: S, ) -> SubsystemResult<(Self, OverseerHandler)> where CV: Subsystem<OverseerSubsystemContext<CandidateValidationMessage>> + Send, CB: Subsystem<OverseerSubsystemContext<CandidateBackingMessage>> + Send, CS: Subsystem<OverseerSubsystemContext<CandidateSelectionMessage>> + Send, SD: Subsystem<OverseerSubsystemContext<StatementDistributionMessage>> + Send, AD: Subsystem<OverseerSubsystemContext<AvailabilityDistributionMessage>> + Send, BS: Subsystem<OverseerSubsystemContext<BitfieldSigningMessage>> + Send, BD: Subsystem<OverseerSubsystemContext<BitfieldDistributionMessage>> + Send, P: Subsystem<OverseerSubsystemContext<ProvisionerMessage>> + Send, PoVD: Subsystem<OverseerSubsystemContext<PoVDistributionMessage>> + Send, RA: Subsystem<OverseerSubsystemContext<RuntimeApiMessage>> + Send, AS: Subsystem<OverseerSubsystemContext<AvailabilityStoreMessage>> + Send, NB: Subsystem<OverseerSubsystemContext<NetworkBridgeMessage>> + Send, CA: Subsystem<OverseerSubsystemContext<ChainApiMessage>> + Send, CG: Subsystem<OverseerSubsystemContext<CollationGenerationMessage>> + Send, CP: Subsystem<OverseerSubsystemContext<CollatorProtocolMessage>> + Send, { let (events_tx, events_rx) = mpsc::channel(CHANNEL_CAPACITY); let handler = OverseerHandler { events_tx: events_tx.clone(), }; let mut running_subsystems_rx = StreamUnordered::new(); let mut running_subsystems = FuturesUnordered::new(); let candidate_validation_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.candidate_validation, )?; let candidate_backing_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.candidate_backing, )?; let candidate_selection_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.candidate_selection, )?; let statement_distribution_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.statement_distribution, )?; let availability_distribution_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.availability_distribution, )?; let bitfield_signing_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.bitfield_signing, )?; let bitfield_distribution_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.bitfield_distribution, )?; let provisioner_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.provisioner, )?; let pov_distribution_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.pov_distribution, )?; let runtime_api_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.runtime_api, )?; let availability_store_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.availability_store, )?; let network_bridge_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.network_bridge, )?; let chain_api_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.chain_api, )?; let collation_generation_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.collation_generation, )?; let collator_protocol_subsystem = spawn( &mut s, &mut running_subsystems, &mut running_subsystems_rx, all_subsystems.collator_protocol, )?; let leaves = leaves .into_iter() .map(|BlockInfo { hash, parent_hash: _, number }| (hash, number)) .collect(); let active_leaves = HashMap::new(); let metrics = <Metrics as metrics::Metrics>::register(prometheus_registry); let activation_external_listeners = HashMap::new(); let this = Self { candidate_validation_subsystem, candidate_backing_subsystem, candidate_selection_subsystem, statement_distribution_subsystem, availability_distribution_subsystem, bitfield_signing_subsystem, bitfield_distribution_subsystem, provisioner_subsystem, pov_distribution_subsystem, runtime_api_subsystem, availability_store_subsystem, network_bridge_subsystem, chain_api_subsystem, collation_generation_subsystem, collator_protocol_subsystem, s, running_subsystems, running_subsystems_rx, events_rx, activation_external_listeners, leaves, active_leaves, metrics, }; Ok((this, handler)) } // Stop the overseer. async fn stop(mut self) { if let Some(ref mut s) = self.candidate_validation_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.candidate_backing_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.candidate_selection_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.statement_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.availability_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.bitfield_signing_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.bitfield_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.provisioner_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.pov_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.runtime_api_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.availability_store_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.network_bridge_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.chain_api_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.collator_protocol_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } if let Some(ref mut s) = self.collation_generation_subsystem.instance { let _ = s.tx.send(FromOverseer::Signal(OverseerSignal::Conclude)).await; } let mut stop_delay = Delay::new(Duration::from_secs(STOP_DELAY)).fuse(); loop { select! { _ = self.running_subsystems.next() => { if self.running_subsystems.is_empty() { break; } }, _ = stop_delay => break, complete => break, } } } /// Run the `Overseer`. pub async fn run(mut self) -> SubsystemResult<()> { let leaves = std::mem::take(&mut self.leaves); let mut update = ActiveLeavesUpdate::default(); for (hash, number) in leaves.into_iter() { update.activated.push(hash); self.active_leaves.insert(hash, number); self.on_head_activated(&hash); } self.broadcast_signal(OverseerSignal::ActiveLeaves(update)).await?; loop { while let Poll::Ready(Some(msg)) = poll!(&mut self.events_rx.next()) { match msg { Event::MsgToSubsystem(msg) => { self.route_message(msg).await; } Event::Stop => { self.stop().await; return Ok(()); } Event::BlockImported(block) => { self.block_imported(block).await?; } Event::BlockFinalized(block) => { self.block_finalized(block).await?; } Event::ExternalRequest(request) => { self.handle_external_request(request); } } } while let Poll::Ready(Some((StreamYield::Item(msg), _))) = poll!( &mut self.running_subsystems_rx.next() ) { match msg { ToOverseer::SubsystemMessage(msg) => self.route_message(msg).await, ToOverseer::SpawnJob { name, s } => { self.spawn_job(name, s); } ToOverseer::SpawnBlockingJob { name, s } => { self.spawn_blocking_job(name, s); } } } // Some subsystem exited? It's time to panic. if let Poll::Ready(Some(finished)) = poll!(self.running_subsystems.next()) { log::error!(target: LOG_TARGET, "Subsystem finished unexpectedly {:?}", finished); self.stop().await; return Err(SubsystemError); } // Looks like nothing is left to be polled, let's take a break. pending!(); } } async fn block_imported(&mut self, block: BlockInfo) -> SubsystemResult<()> { let mut update = ActiveLeavesUpdate::default(); if let Some(number) = self.active_leaves.remove(&block.parent_hash) { if let Some(expected_parent_number) = block.number.checked_sub(1) { debug_assert_eq!(expected_parent_number, number); } update.deactivated.push(block.parent_hash); self.on_head_deactivated(&block.parent_hash); } match self.active_leaves.entry(block.hash) { hash_map::Entry::Vacant(entry) => { update.activated.push(block.hash); entry.insert(block.number); self.on_head_activated(&block.hash); }, hash_map::Entry::Occupied(entry) => { debug_assert_eq!(*entry.get(), block.number); } } self.clean_up_external_listeners(); self.broadcast_signal(OverseerSignal::ActiveLeaves(update)).await?; Ok(()) } async fn block_finalized(&mut self, block: BlockInfo) -> SubsystemResult<()> { let mut update = ActiveLeavesUpdate::default(); self.active_leaves.retain(|h, n| { if *n <= block.number { update.deactivated.push(*h); false } else { true } }); for deactivated in &update.deactivated { self.on_head_deactivated(deactivated) } self.broadcast_signal(OverseerSignal::ActiveLeaves(update)).await?; self.broadcast_signal(OverseerSignal::BlockFinalized(block.hash)).await?; Ok(()) } async fn broadcast_signal(&mut self, signal: OverseerSignal) -> SubsystemResult<()> { if let Some(ref mut s) = self.candidate_validation_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.candidate_backing_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.candidate_selection_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.statement_distribution_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.availability_distribution_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.bitfield_distribution_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.bitfield_signing_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.provisioner_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.pov_distribution_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.runtime_api_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.availability_store_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.network_bridge_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.chain_api_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.collator_protocol_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } if let Some(ref mut s) = self.collation_generation_subsystem.instance { s.tx.send(FromOverseer::Signal(signal.clone())).await?; } Ok(()) } async fn route_message(&mut self, msg: AllMessages) { match msg { AllMessages::CandidateValidation(msg) => { if let Some(ref mut s) = self.candidate_validation_subsystem.instance { let _= s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::CandidateBacking(msg) => { if let Some(ref mut s) = self.candidate_backing_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::CandidateSelection(msg) => { if let Some(ref mut s) = self.candidate_selection_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::StatementDistribution(msg) => { if let Some(ref mut s) = self.statement_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::AvailabilityDistribution(msg) => { if let Some(ref mut s) = self.availability_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::BitfieldDistribution(msg) => { if let Some(ref mut s) = self.bitfield_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::BitfieldSigning(msg) => { if let Some(ref mut s) = self.bitfield_signing_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication{ msg }).await; } } AllMessages::Provisioner(msg) => { if let Some(ref mut s) = self.provisioner_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::PoVDistribution(msg) => { if let Some(ref mut s) = self.pov_distribution_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::RuntimeApi(msg) => { if let Some(ref mut s) = self.runtime_api_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::AvailabilityStore(msg) => { if let Some(ref mut s) = self.availability_store_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::NetworkBridge(msg) => { if let Some(ref mut s) = self.network_bridge_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::ChainApi(msg) => { if let Some(ref mut s) = self.chain_api_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::CollationGeneration(msg) => { if let Some(ref mut s) = self.collation_generation_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } AllMessages::CollatorProtocol(msg) => { if let Some(ref mut s) = self.collator_protocol_subsystem.instance { let _ = s.tx.send(FromOverseer::Communication { msg }).await; } } } } fn on_head_activated(&mut self, hash: &Hash) { self.metrics.on_head_activated(); if let Some(listeners) = self.activation_external_listeners.remove(hash) { for listener in listeners { // it's fine if the listener is no longer interested let _ = listener.send(()); } } } fn on_head_deactivated(&mut self, hash: &Hash) { self.metrics.on_head_deactivated(); if let Some(listeners) = self.activation_external_listeners.remove(hash) { // clean up and signal to listeners the block is deactivated drop(listeners); } } fn clean_up_external_listeners(&mut self) { self.activation_external_listeners.retain(|_, v| { // remove dead listeners v.retain(|c| !c.is_canceled()); !v.is_empty() }) } fn handle_external_request(&mut self, request: ExternalRequest) { match request { ExternalRequest::WaitForActivation { hash, response_channel } => { if self.active_leaves.get(&hash).is_some() { // it's fine if the listener is no longer interested let _ = response_channel.send(()); } else { self.activation_external_listeners.entry(hash).or_default().push(response_channel); } } } } fn spawn_job(&mut self, name: &'static str, j: BoxFuture<'static, ()>) { self.s.spawn(name, j); } fn spawn_blocking_job(&mut self, name: &'static str, j: BoxFuture<'static, ()>) { self.s.spawn_blocking(name, j); } } fn spawn<S: SpawnNamed, M: Send + 'static>( spawner: &mut S, futures: &mut FuturesUnordered<BoxFuture<'static, ()>>, streams: &mut StreamUnordered<mpsc::Receiver<ToOverseer>>, s: impl Subsystem<OverseerSubsystemContext<M>>, ) -> SubsystemResult<OverseenSubsystem<M>> { let (to_tx, to_rx) = mpsc::channel(CHANNEL_CAPACITY); let (from_tx, from_rx) = mpsc::channel(CHANNEL_CAPACITY); let ctx = OverseerSubsystemContext { rx: to_rx, tx: from_tx }; let SpawnedSubsystem { future, name } = s.start(ctx); let (tx, rx) = oneshot::channel(); let fut = Box::pin(async move { future.await; let _ = tx.send(()); }); spawner.spawn(name, fut); streams.push(from_rx); futures.push(Box::pin(rx.map(|_| ()))); let instance = Some(SubsystemInstance { tx: to_tx, }); Ok(OverseenSubsystem { instance, }) } #[cfg(test)] mod tests { use std::sync::atomic; use futures::{executor, pin_mut, select, channel::mpsc, FutureExt}; use polkadot_primitives::v1::{BlockData, CollatorPair, PoV}; use polkadot_subsystem::DummySubsystem; use polkadot_subsystem::messages::RuntimeApiRequest; use polkadot_node_primitives::{Collation, CollationGenerationConfig}; use polkadot_node_network_protocol::{PeerId, ReputationChange, NetworkBridgeEvent}; use sp_core::crypto::Pair as _; use super::*; struct TestSubsystem1(mpsc::Sender<usize>); impl<C> Subsystem<C> for TestSubsystem1 where C: SubsystemContext<Message=CandidateValidationMessage> { type Metrics = (); fn start(self, mut ctx: C) -> SpawnedSubsystem { let mut sender = self.0; SpawnedSubsystem { name: "test-subsystem-1", future: Box::pin(async move { let mut i = 0; loop { match ctx.recv().await { Ok(FromOverseer::Communication { .. }) => { let _ = sender.send(i).await; i += 1; continue; } Ok(FromOverseer::Signal(OverseerSignal::Conclude)) => return, Err(_) => return, _ => (), } } }), } } } struct TestSubsystem2(mpsc::Sender<usize>); impl<C> Subsystem<C> for TestSubsystem2 where C: SubsystemContext<Message=CandidateBackingMessage> { type Metrics = (); fn start(self, mut ctx: C) -> SpawnedSubsystem { let sender = self.0.clone(); SpawnedSubsystem { name: "test-subsystem-2", future: Box::pin(async move { let _sender = sender; let mut c: usize = 0; loop { if c < 10 { let (tx, _) = oneshot::channel(); ctx.send_message( AllMessages::CandidateValidation( CandidateValidationMessage::ValidateFromChainState( Default::default(), PoV { block_data: BlockData(Vec::new()), }.into(), tx, ) ) ).await.unwrap(); c += 1; continue; } match ctx.try_recv().await { Ok(Some(FromOverseer::Signal(OverseerSignal::Conclude))) => { break; } Ok(Some(_)) => { continue; } Err(_) => return, _ => (), } pending!(); } }), } } } struct TestSubsystem4; impl<C> Subsystem<C> for TestSubsystem4 where C: SubsystemContext<Message=CandidateBackingMessage> { type Metrics = (); fn start(self, mut _ctx: C) -> SpawnedSubsystem { SpawnedSubsystem { name: "test-subsystem-4", future: Box::pin(async move { // Do nothing and exit. }), } } } // Checks that a minimal configuration of two jobs can run and exchange messages. #[test] fn overseer_works() { let spawner = sp_core::testing::TaskExecutor::new(); executor::block_on(async move { let (s1_tx, mut s1_rx) = mpsc::channel(64); let (s2_tx, mut s2_rx) = mpsc::channel(64); let all_subsystems = AllSubsystems { candidate_validation: TestSubsystem1(s1_tx), candidate_backing: TestSubsystem2(s2_tx), candidate_selection: DummySubsystem, statement_distribution: DummySubsystem, availability_distribution: DummySubsystem, bitfield_signing: DummySubsystem, bitfield_distribution: DummySubsystem, provisioner: DummySubsystem, pov_distribution: DummySubsystem, runtime_api: DummySubsystem, availability_store: DummySubsystem, network_bridge: DummySubsystem, chain_api: DummySubsystem, collation_generation: DummySubsystem, collator_protocol: DummySubsystem, }; let (overseer, mut handler) = Overseer::new( vec![], all_subsystems, None, spawner, ).unwrap(); let overseer_fut = overseer.run().fuse(); pin_mut!(overseer_fut); let mut s1_results = Vec::new(); let mut s2_results = Vec::new(); loop { select! { a = overseer_fut => break, s1_next = s1_rx.next() => { match s1_next { Some(msg) => { s1_results.push(msg); if s1_results.len() == 10 { handler.stop().await.unwrap(); } } None => break, } }, s2_next = s2_rx.next() => { match s2_next { Some(msg) => s2_results.push(s2_next), None => break, } }, complete => break, } } assert_eq!(s1_results, (0..10).collect::<Vec<_>>()); }); } // Checks activated/deactivated metrics are updated properly. #[test] fn overseer_metrics_work() { let spawner = sp_core::testing::TaskExecutor::new(); executor::block_on(async move { let first_block_hash = [1; 32].into(); let second_block_hash = [2; 32].into(); let third_block_hash = [3; 32].into(); let first_block = BlockInfo { hash: first_block_hash, parent_hash: [0; 32].into(), number: 1, }; let second_block = BlockInfo { hash: second_block_hash, parent_hash: first_block_hash, number: 2, }; let third_block = BlockInfo { hash: third_block_hash, parent_hash: second_block_hash, number: 3, }; let all_subsystems = AllSubsystems { collation_generation: DummySubsystem, candidate_validation: DummySubsystem, candidate_backing: DummySubsystem, candidate_selection: DummySubsystem, collator_protocol: DummySubsystem, statement_distribution: DummySubsystem, availability_distribution: DummySubsystem, bitfield_signing: DummySubsystem, bitfield_distribution: DummySubsystem, provisioner: DummySubsystem, pov_distribution: DummySubsystem, runtime_api: DummySubsystem, availability_store: DummySubsystem, network_bridge: DummySubsystem, chain_api: DummySubsystem, }; let registry = prometheus::Registry::new(); let (overseer, mut handler) = Overseer::new( vec![first_block], all_subsystems, Some(&registry), spawner, ).unwrap(); let overseer_fut = overseer.run().fuse(); pin_mut!(overseer_fut); handler.block_imported(second_block).await.unwrap(); handler.block_imported(third_block).await.unwrap(); handler.stop().await.unwrap(); select! { res = overseer_fut => { assert!(res.is_ok()); let (activated, deactivated) = extract_metrics(&registry); assert_eq!(activated, 3); assert_eq!(deactivated, 2); }, complete => (), } }); } fn extract_metrics(registry: &prometheus::Registry) -> (u64, u64) { let gather = registry.gather(); assert_eq!(gather[0].get_name(), "parachain_activated_heads_total"); assert_eq!(gather[1].get_name(), "parachain_deactivated_heads_total"); let activated = gather[0].get_metric()[0].get_counter().get_value() as u64; let deactivated = gather[1].get_metric()[0].get_counter().get_value() as u64; (activated, deactivated) } // Spawn a subsystem that immediately exits. // // Should immediately conclude the overseer itself with an error. #[test] fn overseer_panics_on_subsystem_exit() { let spawner = sp_core::testing::TaskExecutor::new(); executor::block_on(async move { let (s1_tx, _) = mpsc::channel(64); let all_subsystems = AllSubsystems { candidate_validation: TestSubsystem1(s1_tx), candidate_backing: TestSubsystem4, candidate_selection: DummySubsystem, statement_distribution: DummySubsystem, availability_distribution: DummySubsystem, bitfield_signing: DummySubsystem, bitfield_distribution: DummySubsystem, provisioner: DummySubsystem, pov_distribution: DummySubsystem, runtime_api: DummySubsystem, availability_store: DummySubsystem, network_bridge: DummySubsystem, chain_api: DummySubsystem, collation_generation: DummySubsystem, collator_protocol: DummySubsystem, }; let (overseer, _handle) = Overseer::new( vec![], all_subsystems, None, spawner, ).unwrap(); let overseer_fut = overseer.run().fuse(); pin_mut!(overseer_fut); select! { res = overseer_fut => assert!(res.is_err()), complete => (), } }) } struct TestSubsystem5(mpsc::Sender<OverseerSignal>); impl<C> Subsystem<C> for TestSubsystem5 where C: SubsystemContext<Message=CandidateValidationMessage> { type Metrics = (); fn start(self, mut ctx: C) -> SpawnedSubsystem { let mut sender = self.0.clone(); SpawnedSubsystem { name: "test-subsystem-5", future: Box::pin(async move { loop { match ctx.try_recv().await { Ok(Some(FromOverseer::Signal(OverseerSignal::Conclude))) => break, Ok(Some(FromOverseer::Signal(s))) => { sender.send(s).await.unwrap(); continue; }, Ok(Some(_)) => continue, Err(_) => return, _ => (), } pending!(); } }), } } } struct TestSubsystem6(mpsc::Sender<OverseerSignal>); impl<C> Subsystem<C> for TestSubsystem6 where C: SubsystemContext<Message=CandidateBackingMessage> { type Metrics = (); fn start(self, mut ctx: C) -> SpawnedSubsystem { let mut sender = self.0.clone(); SpawnedSubsystem { name: "test-subsystem-6", future: Box::pin(async move { loop { match ctx.try_recv().await { Ok(Some(FromOverseer::Signal(OverseerSignal::Conclude))) => break, Ok(Some(FromOverseer::Signal(s))) => { sender.send(s).await.unwrap(); continue; }, Ok(Some(_)) => continue, Err(_) => return, _ => (), } pending!(); } }), } } } // Tests that starting with a defined set of leaves and receiving // notifications on imported blocks triggers expected `StartWork` and `StopWork` heartbeats. #[test] fn overseer_start_stop_works() { let spawner = sp_core::testing::TaskExecutor::new(); executor::block_on(async move { let first_block_hash = [1; 32].into(); let second_block_hash = [2; 32].into(); let third_block_hash = [3; 32].into(); let first_block = BlockInfo { hash: first_block_hash, parent_hash: [0; 32].into(), number: 1, }; let second_block = BlockInfo { hash: second_block_hash, parent_hash: first_block_hash, number: 2, }; let third_block = BlockInfo { hash: third_block_hash, parent_hash: second_block_hash, number: 3, }; let (tx_5, mut rx_5) = mpsc::channel(64); let (tx_6, mut rx_6) = mpsc::channel(64); let all_subsystems = AllSubsystems { candidate_validation: TestSubsystem5(tx_5), candidate_backing: TestSubsystem6(tx_6), candidate_selection: DummySubsystem, statement_distribution: DummySubsystem, availability_distribution: DummySubsystem, bitfield_signing: DummySubsystem, bitfield_distribution: DummySubsystem, provisioner: DummySubsystem, pov_distribution: DummySubsystem, runtime_api: DummySubsystem, availability_store: DummySubsystem, network_bridge: DummySubsystem, chain_api: DummySubsystem, collation_generation: DummySubsystem, collator_protocol: DummySubsystem, }; let (overseer, mut handler) = Overseer::new( vec![first_block], all_subsystems, None, spawner, ).unwrap(); let overseer_fut = overseer.run().fuse(); pin_mut!(overseer_fut); let mut ss5_results = Vec::new(); let mut ss6_results = Vec::new(); handler.block_imported(second_block).await.unwrap(); handler.block_imported(third_block).await.unwrap(); let expected_heartbeats = vec![ OverseerSignal::ActiveLeaves(ActiveLeavesUpdate::start_work(first_block_hash)), OverseerSignal::ActiveLeaves(ActiveLeavesUpdate { activated: [second_block_hash].as_ref().into(), deactivated: [first_block_hash].as_ref().into(), }), OverseerSignal::ActiveLeaves(ActiveLeavesUpdate { activated: [third_block_hash].as_ref().into(), deactivated: [second_block_hash].as_ref().into(), }), ]; loop { select! { res = overseer_fut => { assert!(res.is_ok()); break; }, res = rx_5.next() => { if let Some(res) = res { ss5_results.push(res); } } res = rx_6.next() => { if let Some(res) = res { ss6_results.push(res); } } complete => break, } if ss5_results.len() == expected_heartbeats.len() && ss6_results.len() == expected_heartbeats.len() { handler.stop().await.unwrap(); } } assert_eq!(ss5_results, expected_heartbeats); assert_eq!(ss6_results, expected_heartbeats); }); } // Tests that starting with a defined set of leaves and receiving // notifications on imported blocks triggers expected `StartWork` and `StopWork` heartbeats. #[test] fn overseer_finalize_works() { let spawner = sp_core::testing::TaskExecutor::new(); executor::block_on(async move { let first_block_hash = [1; 32].into(); let second_block_hash = [2; 32].into(); let third_block_hash = [3; 32].into(); let first_block = BlockInfo { hash: first_block_hash, parent_hash: [0; 32].into(), number: 1, }; let second_block = BlockInfo { hash: second_block_hash, parent_hash: [42; 32].into(), number: 2, }; let third_block = BlockInfo { hash: third_block_hash, parent_hash: second_block_hash, number: 3, }; let (tx_5, mut rx_5) = mpsc::channel(64); let (tx_6, mut rx_6) = mpsc::channel(64); let all_subsystems = AllSubsystems { candidate_validation: TestSubsystem5(tx_5), candidate_backing: TestSubsystem6(tx_6), candidate_selection: DummySubsystem, statement_distribution: DummySubsystem, availability_distribution: DummySubsystem, bitfield_signing: DummySubsystem, bitfield_distribution: DummySubsystem, provisioner: DummySubsystem, pov_distribution: DummySubsystem, runtime_api: DummySubsystem, availability_store: DummySubsystem, network_bridge: DummySubsystem, chain_api: DummySubsystem, collation_generation: DummySubsystem, collator_protocol: DummySubsystem, }; // start with two forks of different height. let (overseer, mut handler) = Overseer::new( vec![first_block, second_block], all_subsystems, None, spawner, ).unwrap(); let overseer_fut = overseer.run().fuse(); pin_mut!(overseer_fut); let mut ss5_results = Vec::new(); let mut ss6_results = Vec::new(); // this should stop work on both forks we started with earlier. handler.block_finalized(third_block).await.unwrap(); let expected_heartbeats = vec![ OverseerSignal::ActiveLeaves(ActiveLeavesUpdate { activated: [first_block_hash, second_block_hash].as_ref().into(), ..Default::default() }), OverseerSignal::ActiveLeaves(ActiveLeavesUpdate { deactivated: [first_block_hash, second_block_hash].as_ref().into(), ..Default::default() }), OverseerSignal::BlockFinalized(third_block_hash), ]; loop { select! { res = overseer_fut => { assert!(res.is_ok()); break; }, res = rx_5.next() => { if let Some(res) = res { ss5_results.push(res); } } res = rx_6.next() => { if let Some(res) = res { ss6_results.push(res); } } complete => break, } if ss5_results.len() == expected_heartbeats.len() && ss6_results.len() == expected_heartbeats.len() { handler.stop().await.unwrap(); } } assert_eq!(ss5_results.len(), expected_heartbeats.len()); assert_eq!(ss6_results.len(), expected_heartbeats.len()); // Notifications on finality for multiple blocks at once // may be received in different orders. for expected in expected_heartbeats { assert!(ss5_results.contains(&expected)); assert!(ss6_results.contains(&expected)); } }); } #[derive(Clone)] struct CounterSubsystem { stop_signals_received: Arc<atomic::AtomicUsize>, signals_received: Arc<atomic::AtomicUsize>, msgs_received: Arc<atomic::AtomicUsize>, } impl CounterSubsystem { fn new( stop_signals_received: Arc<atomic::AtomicUsize>, signals_received: Arc<atomic::AtomicUsize>, msgs_received: Arc<atomic::AtomicUsize>, ) -> Self { Self { stop_signals_received, signals_received, msgs_received, } } } impl<C, M> Subsystem<C> for CounterSubsystem where C: SubsystemContext<Message=M>, M: Send, { type Metrics = (); fn start(self, mut ctx: C) -> SpawnedSubsystem { SpawnedSubsystem { name: "counter-subsystem", future: Box::pin(async move { loop { match ctx.try_recv().await { Ok(Some(FromOverseer::Signal(OverseerSignal::Conclude))) => { self.stop_signals_received.fetch_add(1, atomic::Ordering::SeqCst); break; }, Ok(Some(FromOverseer::Signal(_))) => { self.signals_received.fetch_add(1, atomic::Ordering::SeqCst); continue; }, Ok(Some(FromOverseer::Communication { .. })) => { self.msgs_received.fetch_add(1, atomic::Ordering::SeqCst); continue; }, Err(_) => (), _ => (), } pending!(); } }), } } } fn test_candidate_validation_msg() -> CandidateValidationMessage { let (sender, _) = oneshot::channel(); let pov = Arc::new(PoV { block_data: BlockData(Vec::new()) }); CandidateValidationMessage::ValidateFromChainState(Default::default(), pov, sender) } fn test_candidate_backing_msg() -> CandidateBackingMessage { let (sender, _) = oneshot::channel(); CandidateBackingMessage::GetBackedCandidates(Default::default(), sender) } fn test_candidate_selection_msg() -> CandidateSelectionMessage { CandidateSelectionMessage::default() } fn test_chain_api_msg() -> ChainApiMessage { let (sender, _) = oneshot::channel(); ChainApiMessage::FinalizedBlockNumber(sender) } fn test_collator_generation_msg() -> CollationGenerationMessage { CollationGenerationMessage::Initialize(CollationGenerationConfig { key: CollatorPair::generate().0, collator: Box::new(|_| Box::new(TestCollator)), para_id: Default::default(), }) } struct TestCollator; impl Future for TestCollator { type Output = Collation; fn poll(self: Pin<&mut Self>, _cx: &mut futures::task::Context) -> Poll<Self::Output> { panic!("at the Disco") } } impl Unpin for TestCollator {} fn test_collator_protocol_msg() -> CollatorProtocolMessage { CollatorProtocolMessage::CollateOn(Default::default()) } fn test_network_bridge_event<M>() -> NetworkBridgeEvent<M> { NetworkBridgeEvent::PeerDisconnected(PeerId::random()) } fn test_statement_distribution_msg() -> StatementDistributionMessage { StatementDistributionMessage::NetworkBridgeUpdateV1(test_network_bridge_event()) } fn test_availability_distribution_msg() -> AvailabilityDistributionMessage { AvailabilityDistributionMessage::NetworkBridgeUpdateV1(test_network_bridge_event()) } fn test_bitfield_distribution_msg() -> BitfieldDistributionMessage { BitfieldDistributionMessage::NetworkBridgeUpdateV1(test_network_bridge_event()) } fn test_provisioner_msg() -> ProvisionerMessage { let (sender, _) = oneshot::channel(); ProvisionerMessage::RequestInherentData(Default::default(), sender) } fn test_pov_distribution_msg() -> PoVDistributionMessage { PoVDistributionMessage::NetworkBridgeUpdateV1(test_network_bridge_event()) } fn test_runtime_api_msg() -> RuntimeApiMessage { let (sender, _) = oneshot::channel(); RuntimeApiMessage::Request(Default::default(), RuntimeApiRequest::Validators(sender)) } fn test_availability_store_msg() -> AvailabilityStoreMessage { let (sender, _) = oneshot::channel(); AvailabilityStoreMessage::QueryAvailableData(Default::default(), sender) } fn test_network_bridge_msg() -> NetworkBridgeMessage { NetworkBridgeMessage::ReportPeer(PeerId::random(), ReputationChange::new(42, "")) } // Checks that `stop`, `broadcast_signal` and `broadcast_message` are implemented correctly. #[test] fn overseer_all_subsystems_receive_signals_and_messages() { let spawner = sp_core::testing::TaskExecutor::new(); executor::block_on(async move { let stop_signals_received = Arc::new(atomic::AtomicUsize::new(0)); let signals_received = Arc::new(atomic::AtomicUsize::new(0)); let msgs_received = Arc::new(atomic::AtomicUsize::new(0)); let subsystem = CounterSubsystem::new( stop_signals_received.clone(), signals_received.clone(), msgs_received.clone(), ); let all_subsystems = AllSubsystems { candidate_validation: subsystem.clone(), candidate_backing: subsystem.clone(), candidate_selection: subsystem.clone(), collation_generation: subsystem.clone(), collator_protocol: subsystem.clone(), statement_distribution: subsystem.clone(), availability_distribution: subsystem.clone(), bitfield_signing: subsystem.clone(), bitfield_distribution: subsystem.clone(), provisioner: subsystem.clone(), pov_distribution: subsystem.clone(), runtime_api: subsystem.clone(), availability_store: subsystem.clone(), network_bridge: subsystem.clone(), chain_api: subsystem.clone(), }; let (overseer, mut handler) = Overseer::new( vec![], all_subsystems, None, spawner, ).unwrap(); let overseer_fut = overseer.run().fuse(); pin_mut!(overseer_fut); // send a signal to each subsystem handler.block_imported(BlockInfo { hash: Default::default(), parent_hash: Default::default(), number: Default::default(), }).await.unwrap(); // send a msg to each subsystem // except for BitfieldSigning as the message is not instantiable handler.send_msg(AllMessages::CandidateValidation(test_candidate_validation_msg())).await.unwrap(); handler.send_msg(AllMessages::CandidateBacking(test_candidate_backing_msg())).await.unwrap(); handler.send_msg(AllMessages::CandidateSelection(test_candidate_selection_msg())).await.unwrap(); handler.send_msg(AllMessages::CollationGeneration(test_collator_generation_msg())).await.unwrap(); handler.send_msg(AllMessages::CollatorProtocol(test_collator_protocol_msg())).await.unwrap(); handler.send_msg(AllMessages::StatementDistribution(test_statement_distribution_msg())).await.unwrap(); handler.send_msg(AllMessages::AvailabilityDistribution(test_availability_distribution_msg())).await.unwrap(); // handler.send_msg(AllMessages::BitfieldSigning(test_bitfield_signing_msg())).await.unwrap(); handler.send_msg(AllMessages::BitfieldDistribution(test_bitfield_distribution_msg())).await.unwrap(); handler.send_msg(AllMessages::Provisioner(test_provisioner_msg())).await.unwrap(); handler.send_msg(AllMessages::PoVDistribution(test_pov_distribution_msg())).await.unwrap(); handler.send_msg(AllMessages::RuntimeApi(test_runtime_api_msg())).await.unwrap(); handler.send_msg(AllMessages::AvailabilityStore(test_availability_store_msg())).await.unwrap(); handler.send_msg(AllMessages::NetworkBridge(test_network_bridge_msg())).await.unwrap(); handler.send_msg(AllMessages::ChainApi(test_chain_api_msg())).await.unwrap(); // send a stop signal to each subsystems handler.stop().await.unwrap(); select! { res = overseer_fut => { const NUM_SUBSYSTEMS: usize = 15; assert_eq!(stop_signals_received.load(atomic::Ordering::SeqCst), NUM_SUBSYSTEMS); // x2 because of broadcast_signal on startup assert_eq!(signals_received.load(atomic::Ordering::SeqCst), 2 * NUM_SUBSYSTEMS); // -1 for BitfieldSigning assert_eq!(msgs_received.load(atomic::Ordering::SeqCst), NUM_SUBSYSTEMS - 1); assert!(res.is_ok()); }, complete => (), } }); } }
<reponame>dheraclio/dependometer package com.valtech.source.dependometer.app.controller.compilationunit; public interface HandleCompilationUnitTangleCollectedEventIf { public void handleEvent( CompilationUnitTangleCollectedEvent event); }
def is_adversarial(self, predictions, annotation): if self._model_name.startswith("pytorchhub_"): if len(predictions.pred[0]) == 0: return True if predictions.pred[0][0, 5] != annotation: return True return False elif self._model_name.startswith("paddlehub_"): if not predictions[0]['data']: return True if predictions[0]['data'][0]['label'] is not annotation: return True return False elif predictions is None: return True else: return self._target_class not in predictions['classes']
//String return string to li tag func (li ListItem) String() string { ret := "<li" + li.Attrs() + ">" if li.Text != "" { if li.HTMLEncode { ret += html.EscapeString(li.Text) } else { ret += li.Text } } for _, el := range li.Body { ret += el.String() } ret += "</li>" return ret }
#include <bits/stdc++.h> using namespace std; #define LMX (LLONG_MAX >> 1) typedef long long int i64; typedef vector<int> vii; typedef vector<i64> vll; typedef vector<string> vss; template<typename T> void read(vector<T> &v) { for(auto &a: v) cin >> a; } int main() { int m, n, a = 0; cin >> m >> n; vii v(m), u(n); read(v); read(u); for(int i = 0, j = 0; i < m && j < n; i++) { if(v[i] <= u[j]) { j++; a++; } } cout << a << endl; return 0; }
/** * The MetricFetcher can be used to fetch metrics from the JobManager and all registered TaskManagers. * * <p>Metrics will only be fetched when {@link MetricFetcher#update()} is called, provided that a sufficient time since * the last call has passed. */ public class MetricFetcher { private static final Logger LOG = LoggerFactory.getLogger(MetricFetcher.class); private final JobManagerRetriever retriever; private final MetricQueryServiceRetriever queryServiceRetriever; private final Executor executor; private final Time timeout; private MetricStore metrics = new MetricStore(); private MetricDumpDeserializer deserializer = new MetricDumpDeserializer(); private long lastUpdateTime; public MetricFetcher( JobManagerRetriever retriever, MetricQueryServiceRetriever queryServiceRetriever, Executor executor, Time timeout) { this.retriever = Preconditions.checkNotNull(retriever); this.queryServiceRetriever = Preconditions.checkNotNull(queryServiceRetriever); this.executor = Preconditions.checkNotNull(executor); this.timeout = Preconditions.checkNotNull(timeout); } /** * Returns the MetricStore containing all stored metrics. * * @return MetricStore containing all stored metrics; */ public MetricStore getMetricStore() { return metrics; } /** * This method can be used to signal this MetricFetcher that the metrics are still in use and should be updated. */ public void update() { synchronized (this) { long currentTime = System.currentTimeMillis(); if (currentTime - lastUpdateTime > 10000) { // 10 seconds have passed since the last update lastUpdateTime = currentTime; fetchMetrics(); } } } private void fetchMetrics() { try { Optional<JobManagerGateway> optJobManagerGateway = retriever.getJobManagerGatewayNow(); if (optJobManagerGateway.isPresent()) { final JobManagerGateway jobManagerGateway = optJobManagerGateway.get(); /** * Remove all metrics that belong to a job that is not running and no longer archived. */ CompletableFuture<MultipleJobsDetails> jobDetailsFuture = jobManagerGateway.requestJobDetails(true, true, timeout); jobDetailsFuture.whenCompleteAsync( (MultipleJobsDetails jobDetails, Throwable throwable) -> { if (throwable != null) { LOG.debug("Fetching of JobDetails failed.", throwable); } else { ArrayList<String> toRetain = new ArrayList<>(); for (JobDetails job : jobDetails.getRunningJobs()) { toRetain.add(job.getJobId().toString()); } for (JobDetails job : jobDetails.getFinishedJobs()) { toRetain.add(job.getJobId().toString()); } synchronized (metrics) { metrics.jobs.keySet().retainAll(toRetain); } } }, executor); String jobManagerPath = jobManagerGateway.getAddress(); String jmQueryServicePath = jobManagerPath.substring(0, jobManagerPath.lastIndexOf('/') + 1) + MetricQueryService.METRIC_QUERY_SERVICE_NAME; retrieveAndQueryMetrics(jmQueryServicePath); /** * We first request the list of all registered task managers from the job manager, and then * request the respective metric dump from each task manager. * * <p>All stored metrics that do not belong to a registered task manager will be removed. */ CompletableFuture<Collection<Instance>> taskManagersFuture = jobManagerGateway.requestTaskManagerInstances(timeout); taskManagersFuture.whenCompleteAsync( (Collection<Instance> taskManagers, Throwable throwable) -> { if (throwable != null) { LOG.debug("Fetching list of registered TaskManagers failed.", throwable); } else { List<String> activeTaskManagers = taskManagers.stream().map( taskManagerInstance -> { final String taskManagerAddress = taskManagerInstance.getTaskManagerGateway().getAddress(); final String tmQueryServicePath = taskManagerAddress.substring(0, taskManagerAddress.lastIndexOf('/') + 1) + MetricQueryService.METRIC_QUERY_SERVICE_NAME + "_" + taskManagerInstance.getTaskManagerID().getResourceIdString(); retrieveAndQueryMetrics(tmQueryServicePath); return taskManagerInstance.getId().toString(); }).collect(Collectors.toList()); synchronized (metrics) { metrics.taskManagers.keySet().retainAll(activeTaskManagers); } } }, executor); } } catch (Exception e) { LOG.warn("Exception while fetching metrics.", e); } } /** * Retrieves and queries the specified QueryServiceGateway. * * @param queryServicePath specifying the QueryServiceGateway */ private void retrieveAndQueryMetrics(String queryServicePath) { final CompletableFuture<MetricQueryServiceGateway> queryServiceGatewayFuture = queryServiceRetriever.retrieveService(queryServicePath); queryServiceGatewayFuture.whenCompleteAsync( (MetricQueryServiceGateway queryServiceGateway, Throwable t) -> { if (t != null) { LOG.debug("Could not retrieve QueryServiceGateway.", t); } else { queryMetrics(queryServiceGateway); } }, executor); } /** * Query the metrics from the given QueryServiceGateway. * * @param queryServiceGateway to query for metrics */ private void queryMetrics(final MetricQueryServiceGateway queryServiceGateway) { queryServiceGateway .queryMetrics(timeout) .whenCompleteAsync( (MetricDumpSerialization.MetricSerializationResult result, Throwable t) -> { if (t != null) { LOG.debug("Fetching metrics failed.", t); } else { List<MetricDump> dumpedMetrics = deserializer.deserialize(result); synchronized (metrics) { for (MetricDump metric : dumpedMetrics) { metrics.add(metric); } } } }, executor); } }
import { Box, Heading, Link, Text } from '@sajari/react-components'; import { getStylesObject } from '@sajari/react-sdk-utils'; import { useSearchUIContext } from '../../../ContextProvider'; import { useBannerStyle } from './styles'; import { BannerItemProps } from './types'; const BannerItem = ({ banner, numberOfCols = 1 }: BannerItemProps) => { const { disableDefaultStyles = false, customClassNames, tracking } = useSearchUIContext(); const { title, description, targetUrl, imageUrl, width, height, textColor } = banner; const colSpan = Math.min(width ?? 1, numberOfCols); const styles = getStylesObject( useBannerStyle({ banner, isOnItsOwnRow: colSpan >= numberOfCols }), disableDefaultStyles, ); const onClick = () => tracking.onPromotionClick(banner); return ( <Box css={[ styles.container, customClassNames.banners?.container, { gridColumnEnd: `span ${colSpan}`, gridRowEnd: `span ${height}`, }, ]} > <Box data-testid="banner-image-container" css={styles.imageContainer}> <Link href={targetUrl} css={styles.link} onClick={onClick}> <img src={imageUrl} css={styles.image} alt="" loading="lazy" /> </Link> </Box> {title || description ? ( <Box css={styles.textContainer}> {title ? ( <Heading as="h2" className={customClassNames.banners?.heading} css={[{ color: textColor }, styles.heading]}> {title} </Heading> ) : null} {description ? ( <Text className={customClassNames.banners?.description} css={[{ color: textColor }, styles.description]}> {description} </Text> ) : null} </Box> ) : null} </Box> ); }; export default BannerItem;
def add_node_loopback(self, nodes, ospf_area=None): pass
def sample_obj_array(arr): samples = [sample(arr_i) for arr_i in arr] return samples
def subscribe(self, observer): if hasattr(observer, data_received) and observer not in self.observers: self.observers.append(observer) else: raise SubscriptionError()
<filename>agile-itsm-web/agile-itsm-web-portal/src/main/java/br/com/centralit/citcorpore/bean/CausaIncidenteDTO.java package br.com.centralit.citcorpore.bean; import br.com.citframework.dto.IDto; public class CausaIncidenteDTO implements IDto { private Integer idCausaIncidente; private Integer idCausaIncidentePai; private String descricaoCausa; private java.sql.Date dataInicio; private java.sql.Date dataFim; private Integer nivel; public Integer getIdCausaIncidente(){ return this.idCausaIncidente; } public void setIdCausaIncidente(Integer parm){ this.idCausaIncidente = parm; } public Integer getIdCausaIncidentePai(){ return this.idCausaIncidentePai; } public void setIdCausaIncidentePai(Integer parm){ this.idCausaIncidentePai = parm; } public String getDescricaoCausa(){ return this.descricaoCausa; } public void setDescricaoCausa(String parm){ this.descricaoCausa = parm; } public String getDescricaoCausaNivel(){ if (this.getNivel() == null){ return this.descricaoCausa; } String str = ""; for (int i = 0; i < this.getNivel().intValue(); i++){ str += "...."; } return str + this.descricaoCausa; } public java.sql.Date getDataInicio(){ return this.dataInicio; } public void setDataInicio(java.sql.Date parm){ this.dataInicio = parm; } public java.sql.Date getDataFim(){ return this.dataFim; } public void setDataFim(java.sql.Date parm){ this.dataFim = parm; } public Integer getNivel() { return nivel; } public void setNivel(Integer nivel) { this.nivel = nivel; } }
inp = input() temp = inp.split() n = int(temp[0]) m = int(temp[1]) a = int(temp[2]) b = int(temp[3]) if n%m == 0: print(0) else: num_to_remove = n%m num_to_add = m - n%m cost_to_remove = b*num_to_remove cost_to_add = a*num_to_add print(min(cost_to_remove,cost_to_add))
def _get_all_info_states_data(state: pyspiel.State, info_states: dict, state_data: dict, include_terminal_states) -> None: r = -1 print(f"Len: {len(state_data)}", end='\r') if state.is_terminal(): if include_terminal_states: r = 0 if state.returns()[0] > 0 else 1 else: return info_tuple = ( state.information_state_string(0), state.information_state_string(1), ) data = [(state.legal_actions(0), state.legal_actions(1)), r] if info_tuple not in info_states: info_states[info_tuple] = data if not state.is_terminal(): if state.information_state_string( state.current_player()) not in state_data: state_data[state.information_state_string( state.current_player())] = state else: return if state.is_terminal(): return for action in state.legal_actions(): new_state = state.child(action) _get_all_info_states(new_state, info_states, state_data, include_terminal_states)
/** * Note this command won't remove the typeToBeReplaced from its container in case it's being iterated over * * @param typeToBeReplaced * @param newType * @param library */ public void swapType(ImportType typeToBeReplaced, Type newType, GeppettoLibrary library) { Command replaceCommand = ReplaceCommand .create(editingDomain, typeToBeReplaced.eContainer(), GeppettoPackage.Literals.GEPPETTO_LIBRARY__TYPES, typeToBeReplaced, Collections.singleton(newType)); editingDomain.getCommandStack().execute(replaceCommand); markAsUnsynched((ISynchable) newType.eContainer()); List<Variable> referencedVars = new ArrayList<Variable>(typeToBeReplaced.getReferencedVariables()); for(Variable v : referencedVars) { Command replaceInVarCommand = ReplaceCommand.create(editingDomain, v, VariablesPackage.Literals.VARIABLE__TYPES, typeToBeReplaced, Collections.singleton(newType)); editingDomain.getCommandStack().execute(replaceInVarCommand); markAsUnsynched(v); } }
/** * method to create dialog object * @param title title of dialog * @param data items of spinner * @param selected selected items position * @return the dialog */ public static MultipleDialog newInstance(String title, String[] data, List<Integer> selected) { MultipleDialog instance = new MultipleDialog(); Bundle arguments = new Bundle(); arguments.putStringArray("data", data); arguments.putString("title", title); arguments.putIntegerArrayList("selected", (ArrayList<Integer>) selected); instance.setArguments(arguments); return instance; }
def fetch_jarvis(key="jarvis", **kwargs): jarvis_files = [f"jarvis{i}.csv.bz2" for i in range(11)] dataset = _from_cache(jarvis_files, key, **kwargs) dataset = dataset.drop(dataset.columns[-1], axis=1) dataset.columns = ["Formula"] + JarvisCFID().feature_labels() return dataset
<gh_stars>1000+ export default function Logo(props: any) { return ( <img // Grab dynamically from merchant's predefined logo src={ props.image || 'https://cdn.builder.io/api/v1/image/assets%2Fe7eb284a1bc549c8856f32d1fc7a44cf%2F77b22e5949524b3190561953907db4e7' } style={{ height: 75, width: 230, objectFit: 'contain', objectPosition: 'center', }} /> ) }
def send_email(subject: str, recipients: List, message: str, attachments: List = None, zip_files: bool = False): mail_server = os.environ['MAIL_SERVER'] mail_server_port = os.environ['MAIL_SERVER_PORT'] mail_address = os.environ['MAIL_SENDER_ADDRESS'] mail_msg = MIMEMultipart() mail_msg['Subject'] = subject mail_msg['From'] = mail_address mail_msg['BCC'] = ','.join(recipients) mail_msg.attach(MIMEText(message)) if zip_files: with tempfile.TemporaryFile(prefix="reports", suffix="zip") as zf: zip = zipfile.ZipFile(zf, 'w', zipfile.ZIP_DEFLATED) for path in attachments: zip.write(path, arcname=os.path.basename(path)) zip.close() size = zf.tell() if size < mail_size_threshold: zf.seek(0) part = MIMEBase("application", "zip") part.set_payload(zf.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="reports.zip"') mail_msg.attach(part) else: if attachments is not None: for path in attachments: part = MIMEBase("application", "octet-stream") with open(path, 'rb') as file: part.set_payload(file.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(path))) mail_msg.attach(part) server = smtplib.SMTP(mail_server, mail_server_port) try: server.ehlo() if mail_server_port == '587': context = ssl.SSLContext(ssl.PROTOCOL_TLS) server.starttls(context=context) server.ehlo() server.sendmail(mail_address, recipients, mail_msg.as_string()) except ssl.SSLError as ssl_e: print('SSL error: ' + str(ssl_e)) if fallback_to_insecure_smtp: print("Falling back to insecure SMTP") server = smtplib.SMTP(mail_server, 25) server.ehlo() server.sendmail(mail_address, recipients, mail_msg.as_string()) pass except Exception as e: print("Cannot send email, details: " + str(e)) finally: try: server.quit() except smtplib.SMTPServerDisconnected: pass
/*************************************************************************/ /*! Sorts an array of da_pskv_t in increasing order */ /*************************************************************************/ void da_pskvsorti(size_t n, da_pskv_t *base) { #define da_pskv_lt(a, b) ((a)->val < (b)->val) GK_MKQSORT(da_pskv_t, base, n, da_pskv_lt); #undef da_pskv_lt }
/** * <CODE>FunctionLocation</CODE> provides information about the location * in a program within a <CODE>Function</CODE>. */ public class FunctionLocation extends ProgramLocation { protected Address functionAddr; /** * Create a new FunctionLocation. * * @param program the program of the location * @param locationAddr the address of the listing location (i.e., referent code unit) * @param functionAddr the function address * @param row the row in the field * @param col the display piece on the row * @param charOffset the character position within the display piece specifed by row,col */ protected FunctionLocation(Program program, Address locationAddr, Address functionAddr, int row, int col, int charOffset) { super(program, locationAddr, row, col, charOffset); this.functionAddr = functionAddr; } /** * Default constructor needed for restoring * a program function location from XML */ protected FunctionLocation() { } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (super.equals(obj)) { FunctionLocation loc = (FunctionLocation) obj; return compareAddr(functionAddr, loc.functionAddr) == 0; } return false; } /** * Return the Function symbol address which may differ from the "location address" when * a function is indirectly inferred via a reference. WARNING: The {@link #getAddress()} should * not be used to obtain the function address! * @return the function address corresponding to this program location */ public Address getFunctionAddress() { return functionAddr; } /** * Save this function location to the given save state object. * * @param obj the save state object for saving the location */ @Override public void saveState(SaveState obj) { super.saveState(obj); if (functionAddr != null) { // should never be null, but don't explode obj.putString("_FUNC_ADDRESS", functionAddr.toString()); } } /** * Restore this function location using the given program and save state object. * * @param program1 the program containing the function location * @param obj the save state object for saving the location */ @Override public void restoreState(Program program1, SaveState obj) { super.restoreState(program1, obj); String addrStr = obj.getString("_FUNC_ADDRESS", null); functionAddr = getAddress(program1, addrStr); } private Address getAddress(Program program1, String addressString) { if (addressString == null) { return addr; } Address newAddress = ProgramUtilities.parseAddress(program1, addressString); return newAddress == null ? addr : newAddress; } @Override public boolean isValid(Program p) { if (!super.isValid(p)) { return false; } Listing listing = p.getListing(); if (!addr.equals(functionAddr)) { // ensure that inferred function reference is valid if (listing.getFunctionAt(addr) != null) { return false; } CodeUnit cu = listing.getCodeUnitAt(addr); if (!(cu instanceof Data)) { return false; } Data data = (Data) cu; if (!(data.getDataType() instanceof Pointer)) { return false; } Reference ref = data.getPrimaryReference(0); if (ref == null || !ref.getToAddress().equals(functionAddr)) { return false; } } return listing.getFunctionAt(functionAddr) != null; } @Override public String toString() { if (addr.equals(functionAddr)) { return super.toString(); } return super.toString() + " functionAddr=" + functionAddr; } }
import qualified Data.List as L import qualified Data.Map as M import qualified Data.Set as S import Data.Map((!)) numOcc [] = M.empty numOcc (x:xs) = let m = numOcc xs in case M.lookup x m of Just i -> M.insert x (i+1) m Nothing -> M.insert x 1 m result list = aux (length sort) sort sumOcc where sort = fmap fst $ L.sortOn snd $ M.toList occ occ = numOcc list sumOcc = foldr (+) 0 occ aux l [] s = 0 aux l (x:xs) s = min (s - y*l) (y + aux (l-1) xs (s-y)) where y = occ ! x showR (x:xs) = show (x+1) ++ " " ++ showR xs showR [] = [] main = do t <- getLine >>= return . read :: IO Integer let loop t = if t == 0 then return () else do n <- getLine >>= return . read :: IO Integer a <- getLine >>= return . (fmap read) . words :: IO [Integer] print $ result a loop $ t - 1 loop t
Regulation of stress-responsive mitogen-activated protein (MAP) kinase pathways by TAO2. Previous studies demonstrated that in vitro the protein kinase TAO2 activates MAP/ERK kinases (MEKs) 3, 4, and 6 toward their substrates p38 MAP kinase and c-Jun N-terminal kinase/stress-activated protein kinase (JNK/SAPK). In this study, we examined the ability of TAO2 to activate stress-sensitive MAP kinase pathways in cells and the relationship between activation of TAO2 and potential downstream pathways. Over-expression of TAO2 activated endogenous JNK/SAPK and p38 but not ERK1/2. Cotransfection experiments suggested that TAO2 selectively activates MEK3 and MEK6 but not MEKs 1, 4, or 7. Coimmunoprecipitation demonstrated that endogenous TAO2 specifically associates with MEK3 and MEK6 providing one mechanism for preferential recognition of MEKs upstream of p38. Sorbitol, and to a lesser extent, sodium chloride, Taxol, and nocodazole increased TAO2 activity toward itself and kinase-dead MEKs 3 and 6. Activation of endogenous TAO2 during differentiation of C2C12 myoblasts paralleled activation of p38 but not JNK/SAPK, consistent with the idea that TAO2 is a physiological regulator of p38 under certain circumstances. TAO1 and TAO2 are closely related protein kinases whose cDNAs were originally isolated from rat based on sequence similarity to the yeast p21-activated protein kinase Ste20p (1,2). The domain organization and regulation of TAOs is distinct from yeast p21-activated protein kinases. The kinase domain is at the TAO N terminus, and neither TAO1 nor TAO2 contains consensus motifs for activation by small G proteins. Each TAO is greater than a thousand amino acids in length; thus, each contains a regulatory domain of over 700 amino acids. A kinase that is over 90% identical to TAO2 was also identified in a screen for RNAs overexpressed in human prostate carcinoma; in this context it was named PSK for prostate-derived STE20like kinase (3). A third kinase, named JIK for JNK 1 inhibitory kinase, has a similar organization and size and is over 60% identical to TAOs (4). A chicken TAO-like kinase has also been found and is called KFC for kinase from chicken (5). TAO1 and TAO2 activate stress-sensitive MAP kinase cascades in vitro by phosphorylating the upstream MAP/ERK kinases (MEKs), MEKs 3, 4, 6, and 7 (1,2). Phosphorylation by TAOs increases their activities toward the downstream MAP kinases, p38 MAP kinase, and the c-Jun N-terminal kinases/ stress-activated protein kinases (JNK/SAPKs). These in vitro activities of TAO1 and TAO2 suggest that they function in stress responsive pathways within the cell as MEKK-level kinases. In vitro studies revealed a MEK binding domain just C-terminal to the TAO catalytic domain (2). This domain binds MEK3 and MEK6 with selectivity over other MEK family members; these MEKs are directed toward p38 family members. Both prostate-derived STE20-like kinase and kinase from chicken were reported to activate JNK/SAPKs in cotransfected cells (3,5). JNK inhibitory kinase, in contrast, was reported to inhibit JNK/SAPK activity (4). Effects of these TAO-related kinases on p38 were not reported. Numerous MEKK-level kinases have been implicated in regulating the stress-responsive JNK/SAPK and p38 pathways (reviewed in 6,7). We wished to determine the behavior of TAOs in cells to clarify their roles in regulating these pathways. Thus, TAO2 was coexpressed in cells with various MEKs and MAP kinases, and endogenous MAPKs were immunoprecipitated from TAO2-transfected cells to examine effects of TAO2 expression on their activities. We also developed antibodies that could immunoprecipitate native TAO2 to determine whether TAO2 and MEKs could be coimmunoprecipitated and tested the capacities of various stimuli to activate TAO2. Finally, we examined the relationship between TAO2, p38, and JNK/SAPK activities during differentiation of C2C12 myoblasts. Cell Culture, Cell Lysates, and Transfections-293 cells and Neuro2A cells were grown in Dulbecco's modified Eagle's medium supplemented with 10% fetal bovine serum, 1% L-glutamine, and 100 units/ml penicillin/streptomycin. ATT20, GC-B6, PC12, and PC12M were cultured under similar conditions. C2C12 cells were purchased from ATCC. To prepare whole cell lysates, cells were washed once with cold phosphatebuffered saline and lysed with Triton lysis buffer (20 mM Tris-HCl, pH 7.5, 150 mM NaCl, 0.5% Triton X-100, 80 mM ␤-glycerophosphate, 0.5 mM sodium orthovanadate, 1 mM EDTA, 20 g/ml aprotinin, 10 g/ml pepstatin A, 10 g/ml leupeptin, and 1 mM phenylmethylsulfonyl fluoride). Insoluble material was pelleted by centrifugation, and supernatants were removed, snap frozen in liquid nitrogen, and stored at Ϫ80°C . For cell fractionation, cells were washed once with phosphate-buffered saline and resuspended in hypotonic buffer (10 mM Hepes, pH 7.6, 1.5 mM MgCl 2 , 10 mM NaCl, 1 mM EDTA, 1 mM EGTA, and supplemented with protease inhibitors and phosphatase inhibitors as above). Cells were lysed with a Dounce apparatus, and the nuclei were collected by sedimentation at 800 ϫ g for 5 min. A particulate fraction was collected by sedimenting the supernatant at 100,000 ϫ g for 30 min. The nuclear pellet was washed with 20 mM Hepes, pH 7.6, 2.5% glycerol, 0.42 M NaCl, 1.5 mM MgCl 2 , 1 mM EDTA, and 1 mM EGTA for 30 min. Both the washed nuclear pellet and particulate fraction were lysed with 1% SDS, 10 mM Tris-HCl, pH 7.6, 1 mM EDTA, 1 mM EGTA, and supplemented with protease inhibitors and phosphatase inhibitors as above. Three g of various MEK or MAPK constructs were cotransfected with 2 g of either empty vector control or TAO2 constructs in 293 cells grown to 80% confluence on 60-mm dishes using the calcium phosphate method. Cells were serum-starved for 24 h beginning the second day and then harvested. Alternatively, cells were transfected with 5 g of either empty vector control or TAO2 constructs to examine the activities of endogenous MAPKs. Antibodies, Immunoblots, and Immunoprecipitation-A polyclonal antiserum (U2253) was raised against the antigenic peptide MPAG-GRAGSLKDPDVAELFFK (residues 1-21 of TAO2 protein) in rabbits. This peptide was conjugated to Limulus hemocyanin (14) and dialyzed into phosphate-buffered saline. A total of five boosts were performed. The final bleed of U2253 was used in all subsequent studies involving TAO2 antibodies. For immunoblot analysis, recombinant proteins or cell lysates were subjected to SDS-PAGE and then transferred to nitrocellulose membranes. The membranes were blocked with 5% milk in TBST (20 mM Tris, pH 8.0, 500 mM NaCl, and 0.05% Tween20) overnight and then incubated with primary antibody diluted in TBST plus 0.5% milk at a 1:10,000 dilution for 1 h. After three washes with TBST, the membranes were incubated with secondary antibody diluted in TBST plus 0.5% milk for 30 min. Membranes were washed again with TBST three times and Tris-buffered saline once and then developed using enhanced chemiluminescence. Polyclonal anti-ERK2 A249 and anti-ERK1/2 Y691 were used to immunoprecipitate and to immunoblot endogenous ERKs, respectively (14). Polyclonal anti-p38 P287 (12) or C-20 (from Santa Cruz) was used to immunoprecipitate or to immunoblot endogenous p38, respectively. C-20 recognizes both ␣ and ␤ isoforms of p38. Endogenous JNK/SAPK and MEK6 were immunoprecipitated and immunoblotted with Santa Cruz antibodies, rabbit C-17 and goat N-19, respectively. Anti-Raf1 (C-12) was also purchased from Santa Cruz. Monoclonal anti-HA antibody (12CA5) and anti-Myc antibody (9E10) were obtained from Berkeley Antibody Company and the Cell Culture Center, respectively. MEKs or MAPKs were immunoprecipitated from 0.3 mg of whole cell lysate protein via the above antibodies and 30 l of protein A-Sepharose slurry. Beads were washed three times with 1 ml of 500 mM NaCl and 20 mM Tris-HCl, pH 7.4, washed one time with 1 ml of 20 mM Tris, pH 8.0, and 10 mM MgCl 2 , and subjected to in vitro kinase assays (2). Endogenous TAO2 was immunoprecipitated from 1.5 mg lysate protein as described in (15) with 5 l of TAO2 antibody (U2253) and 30 l of protein A-Sepharose slurry. Beads were washed three times with 1 ml of 750 mM NaCl, 20 mM Tris-HCl, pH 7.4, and 0.1% Triton X-100, washed one time with 1 ml of 20 mM Tris, pH 8.0, and 10 mM MgCl 2 , and subjected to in vitro kinase assays. Kinase assay conditions were as before, except that the ATP concentration was 10 M. Fold changes were calculated as the ratio of the cpm in the substrate in the experimental sample and the control sample. Phosphorylation of substrate bands was quantified by liquid scintillation counting. Differentiation of C2C12 Cells-Mouse myocyte C2C12 cells were purchased from ATCC. Cells were grown in Dulbecco's modified Eagle's medium with 10% fetal bovine serum to 80% confluence and then placed in Dulbecco's modified Eagle's medium with 2% horse serum for 4 days to allow differentiation essentially as described (16,17). Half of this medium was replaced with fresh medium daily. During differentiation, cells were treated daily with either dimethyl sulfoxide (Me 2 SO) diluent or 15 M SB203580 in Me 2 SO. At the indicated times, cells were harvested in detergent lysis buffer as described, and enzymes were isolated and assayed as described in the figure legend. Stress-sensitive MAPKs Are Activated by Cotransfected TAO2-To investigate TAO2 selectivity in intact cells, cotransfection experiments were performed. In a cotransfection assay, an epitope-tagged MAPK construct was transfected into 293 cells with either the empty vector control or with a differently tagged TAO2 construct. The overexpressed MAPK was immunoprecipitated from the cells and assayed using transcription factor substrates (Fig. 1). HA-JNK1, when cotransfected with various TAO2 proteins, became much more active toward its substrate ATF2 (Fig. 1A). Similarly, HA-SAPK␤ was activated by the TAO2 constructs toward ATF2 (Fig. 1B). The activity of HA-p38 on its substrate ATF2 was also greatly enhanced by cotransfected TAO2-(1-320) or TAO2-(1-451) (Fig. 1C). In contrast to these stress-activated MAPKs, ERK2 was not activated toward its substrate Myc-(1-103) by any of the cotransfected TAO2 plasmids (Fig. 1D) further supporting the conclusion that TAO2 is not an upstream activator of the classical ERK pathway. TAO2 Activates Endogenous, Stress-sensitive MAPKs-The above studies demonstrated that JNK/SAPK and p38 can be activated by TAO2 in overexpression systems. Therefore, we examined effects of TAO2 on endogenous MAPKs. Empty vector control, TAO2-(1-451), or kinase-dead TAO2-(1-451)DA were transfected into 293 cells, and endogenous p38, JNK/ SAPK, and ERK1/2 were immunoprecipitated from transfected cells and assayed using transcription factor substrates. Both endogenous p38 and endogenous JNK/SAPK were significantly activated by TAO2-(1-451) toward their substrate ATF2 (Fig. 2, A and B), whereas the activity of endogenous ERK1/2 was not stimulated to an appreciable extent (Fig. 2C). The fulllength TAO2 protein, TAO2-(1-1235), due to its poor expression level, did not appear to activate stress-sensitive MAPKs in similar assays. Full-length TAO1 also failed to express or activate well in mammalian cells (1). Nevertheless, the kinase activity of full-length TAO2 can be detected by autophosphorylation or by reporter assays (data not shown). TAO2 Selectively Activates MEK3 and MEK6 in Cotransfected Cells-A cotransfection approach was also employed to examine substrate specificity of TAO2 for downstream MEKs. The overexpressed MEK proteins were immunoprecipitated from the cells and assayed using the corresponding MAPK as substrate. The MAPK substrates were defective in autophosphorylation to eliminate background phosphorylation. Ras Val12 was included as a positive control for MEK1, and MEKK1 was included as a positive control for MEK4 and MEK7. Activity of MEK1 toward its substrate ERK2KR was not enhanced by cotransfected TAO2 (Fig. 3A, lane 2), nor were MEK4 and MEK7 activated by TAO2 toward their substrate SAPK␤KA (lanes 5 and 8). In comparison, activities of MEK3 and MEK6 toward p38 were significantly stimulated by cotransfected TAO2 (lanes 11 and 13) suggesting that TAO2 selectively activates MEK3 and MEK6 of the p38 pathway in intact cells. A kinase-dead construct, TAO2-(1-451)DA, failed to activate cotransfected MEK6 (lane 14) indicating that TAO2 kinase activity is essential. Endogenous TAO2 Forms a Complex with MEK3 and MEK6 in Vivo-A polyclonal TAO2 antiserum was generated against an N-terminal peptide from TAO2. The antibody was preincubated with antigenic peptide to demonstrate that the peptide blocked recognition of the TAO2 band (Fig. 5A). We examined several cell lines of neuronal origin because Northern analysis indicated TAO2 mRNA is most highly expressed in brain (1). Using the antibody, we found that TAO2 is expressed in numerous cell lines including 293 fibroblasts (Fig. 5B). By fractionation TAO2 is found in both cytosol and particulate fractions of 293 cells but is not detectable in nuclei (Fig. 5C). Given the apparent importance of the MEK3/6 binding site for TAO2 specificity, we determined if endogenous TAO2 associates with MEK3 in vivo. 293 cells were transfected with Myc-MEK3. Endogenous TAO2 was immunoprecipitated from the cells with the anti-TAO2 antibody and blotted with anti-Myc antibody. Myc-MEK3 was detected in the TAO2 immune complexes (Fig. 6A). To investigate whether coprecipitation can be demonstrated with both endogenous proteins, TAO2 was immunoprecipitated from proliferating 293 cells with the anti-TAO2 antibody, and the precipitates were then blotted with a goat anti-MEK6 antibody. Endogenous MEK6 was found in immune complexes with endogenous TAO2 but not with Raf, the MEKK-level activator of the ERK pathway (Fig. 6B), indicating that this interaction is specific. No such interactions could be observed between TAO2 and MEK4 or MEK7 (data not shown), consistent with results above and in vitro binding studies (2). Sorbitol Stimulates the Activity of Endogenous TAO2-We wished to determine whether TAO2 itself can be activated by stress stimuli that reportedly activate JNK/SAPK or p38. To this end, 293 cells were serum-starved for 24 h and then exposed to osmotic stresses, NaCl, sorbitol, or the microtubuledirected drugs, Taxol and nocodazole. Because TAO2 contains many sites of autophosphorylation, autophosphorylation is an easy method to detect its activity (1,2). Endogenous TAO2 was immunoprecipitated from the cells and its ability to autophosphorylate was measured. TAO2 autophosphorylation was most highly stimulated by sorbitol and slightly elevated by NaCl, taxol, and nocodazole (Fig. 7A). Endogenous TAO2 immunoprecipitated from untreated or sorbitol-treated cells was then assayed using kinase-dead MEK3 and MEK6 as substrates to confirm that enhanced autophosphorylation is a reflection of enhanced TAO2 activity under these circumstances. Phosphorylation of both MEK3 and MEK6 by TAO2 was enhanced by sorbitol treatment (Fig. 7B). Thus, sorbitol, and to a lesser extent several other cell stresses, increased TAO2 activity. Activities of Stress-sensitive Kinases and TAO2 during Differentiation of C2C12 Myoblasts-C2C12 myoblasts can be induced to differentiate and form myotubes in culture (16 -18). p38 is activated during the differentiation process, and its activation is required for differentiation induced by either insulin or growth factor withdrawal. In contrast, JNK/SAPK activities have been reported to change little, and AP-1 activity, which is enhanced by JNK/SAPKs, is suppressed during differentiation consistent with no role of JNK/SAPKs in differentiation (16 -18). We wished to determine whether changes in TAO2 activity occurred during differentiation. If so, that would support the idea that activation of endogenous TAO2 parallels activation of p38 but not the JNK/SAPK pathway. C2C12 cells were maintained in differentiation medium with or without the p38 inhibitor SB203580 for 4 days (Fig. 8A). Myotubes were obvious in the day 4 cultures maintained in the absence of SB203580 but were largely absent if cells had been constantly exposed to SB203580. The amount of p38 protein did not change, but, as expected, its activity increased on or before day 2 and remained elevated through day 4 (Fig. 8, B and C). SB203580 suppressed the elevated activity. The amount of TAO2 protein in the cells decreased significantly over the dif- ). B, 30 g of protein from lysates of the indicated cell lines were resolved by SDS-PAGE and immunoblotted with the anti-TAO2 antibody. N2A refers to neuro2A cells. PC12M is a line selected from PC12 because it is a better transfection recipient. PC12M cells differentiate more poorly and are less sensitive to NGF. ATT20 and GC-B6 are pituitary cell lines; NG108 is a neuroblastoma ϫ glioma hybrid. C, 293 cells were fractionated into soluble, particulate, and nuclear fractions as described under "Experimental Procedures." 30 g of protein from each fraction were subjected to SDS-PAGE and immunoblotted with the anti-TAO2 antibody. ferentiation time course in a manner largely or entirely insensitive to SB203580 (Fig. 8B). However, TAO2-specific activity increased over the time course of differentiation also in an SB203580-independent manner despite the decrease in its mass (Fig. 8D). The amount of JNK/SAPK protein in the cells increased; nevertheless, its specific activity decreased over the time course (Fig. 8, B and E). In contrast to p38 and TAO2, JNK/SAPK activity in cells measured on day 0 was substantial perhaps due to the effects of serum growth factors. Because JNK/SAPK activity is not required for differentiation, its activation may be suppressed during this process. Thus, TAO2 activity parallels p38 activity but not JNK/SAPK activity. This is consistent with the idea that TAO2 is coupled to p38 but not JNK/SAPKs in cells. DISCUSSION Recent molecular cloning studies have revealed the existence of a multitude of MEKK-level kinases in mammalian systems including TAO1 and TAO2 (1, 2, 19 -21). This diversity may allow multiple mechanisms for activation of MAP kinase subgroups in a ligand-and cell type-dependent manner. In several cases, MAPK regulation by MEKK-level kinases correlates well with the ability of MEKKs to phosphorylate and activate corresponding MEK proteins in MAPK modules. Thus, we previously examined the substrate specificity of TAOs in vitro and, in this report, TAO2 in cell culture systems. In vitro, the purified, recombinant, catalytic domains of TAO1 and TAO2 activated MEKs 3, 4, and 6 toward their substrates, p38 and JNK/SAPK (1,2). In contrast, when an active TAO2 truncation mutant was cotransfected with various MEK proteins only MEK3 and MEK6 of the p38 pathway were activated. TAO2 truncation mutants activated both cotransfected and endogenous p38 and JNK/SAPKs. By monitoring TAO2, p38, and JNK/SAPK activities during C2C12 differentiation, we were able to show that conditions that lead to activation of endogenous TAO2 are associated with increases in p38 but not JNK/ SAPK activity. This sort of evidence supports the conclusion that TAO proteins are primarily coupled to the p38 pathway and have little role in regulating JNK/SAPK. The specificity for MEKs 3 and 6 may reflect the importance of the MEK binding domain of TAO2. Earlier we identified this TAO domain immediately C-terminal to its kinase domain and found that it recognized an N-terminal motif in MEKs 3 and 6 (1, 2). Thus far, we have not found a direct site for p38 binding on TAO2. Because the JNK/SAPK activators, MEK4 and MEK7, neither bind TAO2 nor are activated by TAO2 in cells, activation of JNK/SAPK by TAO may be due in part to TAO2 overexpression and to the relaxed specificity of MEK6. Indeed, in vitro kinase studies have shown that MEK6 can phosphorylate JNK/SAPK to an appreciable extent, although the specific activity is lower than that of MEK4 toward JNK/SAPK (data not shown). Enzyme-substrate interactions have received much attention in studying molecular determinants of pathway specificity. Evidence for the importance of these interactions comes from studies of cAMP-dependent protein kinase and the ERK and JNK/SAPK MAPK modules among others (22)(23)(24)(25). A docking site for p38 in MEK6 and MEK3b, an alternatively spliced isoform of MEK3, appears to contribute to specificity of p38 signaling (26). The association of TAO with MEK3/6 and p38 indirectly through the MEK in signaling complexes provides compelling evidence for their interrelated functions even in the absence of information regarding their physiological roles. By selectively interacting with and phosphorylating MEK3 and MEK6 in vivo, TAO2 works in spatial proximity to these immediate upstream regulators of p38, thereby facilitating signal transduction from TAO2 to MEK3/6 and subsequently to p38. Certain MEKKs implicated in regulating JNK/SAPK and p38 are reportedly responsive to cellular stresses. For example, MEKK1 can be activated by cross-linking of high affinity IgE receptors or microtubule-directed drugs (15,27,28) and TAK1 is sensitive to UV, sorbitol, and Fas receptor ligation (29). To identify stimuli or ligands that regulate TAO2, we generated a high-titer TAO2 antibody that enabled us to immunoprecipitate endogenous TAO2 proteins from cells treated with a wide array of stimuli. Of the more than twenty stimuli tested, most had no detectable effect on TAO2 activity (data not shown). The osmotic stress, sorbitol, as well as some other stresses, activated TAO2 modestly suggesting that TAO2 may indeed be involved in stress-responsive pathways. Kinase-dead TAO2 did not block activation of p38 by sorbitol (data not shown). However, many MEKKs are activated by sorbitol, and all may contribute to p38 activation. If this is correct, it will be difficult to identify the individual contributions of these MEKKs to sorbitol-induced p38 stimulation. Importantly, we have recently been able to show that kinase-dead TAO2 was effective in blocking activation of p38 by carbachol 2 . Thus, the aggregate of our studies link TAO1/2 to a subset of conditions regulating the p38 MAP kinase cascade.
/* Copyright (c) 2011, <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ @interface CALayer (FunSize) #pragma mark Recursive Sublayer Operations /** @name Recursive Sublayer Operations */ /** Recursively executes a block on this layer and its sublayers (and their sublayers, etc.). * * @param block The block, which will receive each sublayer as a parameter. */ -(void)sublayersBlock:(void (^)(CALayer* layer))block; /** Recursively executes a block on this layer and its sublayers (and their sublayers, etc.). The block can abort the * recursion and iteration by returning `NO`. * * @param block The block, which will receive each sublayer as a parameter. */ -(BOOL)sublayersBlockWithAbort:(BOOL (^)(CALayer* layer))block; /** Recursively executes a block on this layer's sublayers (and their sublayers, etc.). * * @param block The block, which will receive each sublayer as a parameter. */ -(void)sublayersBlockSkippingSelf:(void (^)(CALayer* layer))block; /** Recursively executes a block on this layer's sublayers (and their sublayers, etc.). The block can abort the * recursion and iteration by returning `NO`. * * @param block The block, which will receive each sublayer as a parameter. */ -(BOOL)sublayersBlockWithAbortSkippingSelf:(BOOL (^)(CALayer* layer))block; #pragma mark Superlayer Actions /** @name Superlayer Actions */ /** Executes a block on this layer and its superlayers. * * @param block The block, which will receive each layer as a parameter. */ -(void)superlayerBlock:(void (^)(CALayer* layer))block; /** Executes a block on this layer and its superlayers. The block can stop the upward recursion by returning `NO`. * * @param block The block, which will receive each layer as a parameter. */ -(BOOL)superlayerBlockWithAbort:(BOOL (^)(CALayer* layer))block; /** Executes a block on this layer's superlayers. * * @param block The block, which will receive each layer as a parameter. */ -(void)superlayerBlockSkippingSelf:(void (^)(CALayer* layer))block; /** Executes a block on this layer's superlayers. The block can stop the upward recursion by returning `NO`. * * @param block The block, which will receive each layer as a parameter. */ -(BOOL)superlayerBlockWithAbortSkippingSelf:(BOOL (^)(CALayer* layer))block; /** Finds a superlayer of the layer with the specified class. If the layer is of the specified class, it will be * returned. * * @returns The superlayer, or `nil` if no superlayer with that class exists. * * @param klass The class to find. */ -(CALayer*)superlayerOfClass:(Class)klass; /** Returns an array of the layer's superlayers, with the immediate superlayer as the first element. */ -(NSArray*)superlayers; #pragma mark Animations /** @name Animations */ /** Adds an animation and returns the copied version of it. * * `-addAnimation:forKey:` copies the animation when it is added. This message returns that copy so that it can be * easily used in later code. * * @param animation The animation to add. * @param key The key to animate. */ -(CAAnimation*)addAndReturnAnimation:(CAAnimation*)animation forKey:(NSString*)key; /** Animates a key of the layer. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key from:(id)fromValue to:(id)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key from:(id)fromValue to:(id)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer. The current value is used as the starting value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key to:(id)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer with custom easing. The current value is used as the starting value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key to:(id)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key from:(id)fromValue to:(id)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key from:(id)fromValue to:(id)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer. The current value is used as the starting value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key to:(id)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer with custom easing. The current value is used as the starting value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key to:(id)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; #pragma mark Numbers /** @name Animation with Numbers */ /** Animates a key of the layer from one integer value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromInt:(int)fromValue to:(int)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one integer value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromInt:(int)fromValue to:(int)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to an integer value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toInt:(int)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to an integer value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toInt:(int)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `float` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromFloat:(float)fromValue to:(float)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `float` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromFloat:(float)fromValue to:(float)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to a `float` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toFloat:(float)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to a `float` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toFloat:(float)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `double` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromDouble:(double)fromValue to:(double)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `double` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromDouble:(double)fromValue to:(double)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to a `double` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toDouble:(double)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to a `double` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toDouble:(double)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one integer value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromInt:(int)fromValue to:(int)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one integer value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromInt:(int)fromValue to:(int)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to an integer value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toInt:(int)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to an integer value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toInt:(int)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer from one `float` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromFloat:(float)fromValue to:(float)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `float` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromFloat:(float)fromValue to:(float)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to a `float` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toFloat:(float)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to a `float` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toFloat:(float)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer from one `double` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromDouble:(double)fromValue to:(double)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `double` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromDouble:(double)fromValue to:(double)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to a `double` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toDouble:(double)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to a `double` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toDouble:(double)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; #pragma mark Rects /** @name Animation with Rects */ /** Animates a key of the layer from one `NSRect` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromRect:(NSRect)fromValue to:(NSRect)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `NSRect` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromRect:(NSRect)fromValue to:(NSRect)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to an `NSRect` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toRect:(NSRect)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to an `NSRect` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toRect:(NSRect)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `CGRect` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromCGRect:(CGRect)fromValue to:(CGRect)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `CGRect` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromCGRect:(CGRect)fromValue to:(CGRect)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to a `CGRect` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toCGRect:(CGRect)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to a `CGRect` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toCGRect:(CGRect)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `NSRect` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromRect:(NSRect)fromValue to:(NSRect)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `NSRect` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromRect:(NSRect)fromValue to:(NSRect)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to an `NSRect` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toRect:(NSRect)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to an `NSRect` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toRect:(NSRect)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer from one `CGRect` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromCGRect:(CGRect)fromValue to:(CGRect)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `CGRect` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromCGRect:(CGRect)fromValue to:(CGRect)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to a `CGRect` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toCGRect:(CGRect)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to a `CGRect` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toCGRect:(CGRect)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; #pragma mark Points /** @name Animation with Points */ /** Animates a key of the layer from one `NSPoint` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromPoint:(NSPoint)fromValue to:(NSPoint)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `NSPoint` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromPoint:(NSPoint)fromValue to:(NSPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to an `NSPoint` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toPoint:(NSPoint)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to an `NSPoint` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toPoint:(NSPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `CGPoint` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromCGPoint:(CGPoint)fromValue to:(CGPoint)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `CGPoint` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromCGPoint:(CGPoint)fromValue to:(CGPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to a `CGPoint` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toCGPoint:(CGPoint)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to a `CGPoint` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toCGPoint:(CGPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `NSPoint` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromPoint:(NSPoint)fromValue to:(NSPoint)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `NSPoint` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromPoint:(NSPoint)fromValue to:(NSPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to an `NSPoint` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toPoint:(NSPoint)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to an `NSPoint` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toPoint:(NSPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer from one `CGPoint` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromCGPoint:(CGPoint)fromValue to:(CGPoint)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `CGPoint` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromCGPoint:(CGPoint)fromValue to:(CGPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to a `CGPoint` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toCGPoint:(CGPoint)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to a `CGPoint` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toCGPoint:(CGPoint)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; #pragma mark Sizes /** @name Animation with Sizes */ /** Animates a key of the layer from one `NSSize` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromSize:(NSSize)fromValue to:(NSSize)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `NSSize` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromSize:(NSSize)fromValue to:(NSSize)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to an `NSSize` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toSize:(NSSize)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to an `NSSize` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toSize:(NSSize)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `CGSize` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromCGSize:(CGSize)fromValue to:(CGSize)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `CGSize` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromCGSize:(CGSize)fromValue to:(CGSize)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to a `CGSize` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toCGSize:(CGSize)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to a `CGSize` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toCGSize:(CGSize)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer from one `NSSize` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromSize:(NSSize)fromValue to:(NSSize)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `NSSize` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromSize:(NSSize)fromValue to:(NSSize)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to an `NSSize` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toSize:(NSSize)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to an `NSSize` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toSize:(NSSize)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer from one `CGSize` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromCGSize:(CGSize)fromValue to:(CGSize)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `CGSize` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromCGSize:(CGSize)fromValue to:(CGSize)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to a `CGSize` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toCGSize:(CGSize)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to a `CGSize` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toCGSize:(CGSize)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; #pragma mark Transforms /** @name Animation with Transforms */ /** Animates a key of the layer from one `CATransform3D` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromTransform:(CATransform3D)fromValue to:(CATransform3D)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer from one `CATransform3D` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key fromTransform:(CATransform3D)fromValue to:(CATransform3D)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer to a `CATransform3D` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toTransform:(CATransform3D)toValue time:(NSTimeInterval)seconds completion:(void (^)())block; /** Animates a key of the layer to a `CATransform3D` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. * @param block A block to execute upon completion of the animation. The block will recieve the animation as a * parameter. */ -(void)animate:(NSString*)key toTransform:(CATransform3D)toValue time:(NSTimeInterval)seconds eased:(id)easing completion:(void (^)())block; /** Animates a key of the layer from one `CATransform3D` value to another. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key fromTransform:(CATransform3D)fromValue to:(CATransform3D)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer from one `CATransform3D` value to another with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param fromValue The starting value. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key fromTransform:(CATransform3D)fromValue to:(CATransform3D)toValue time:(NSTimeInterval)seconds eased:(id)easing; /** Animates a key of the layer to a `CATransform3D` value. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. */ -(void)animate:(NSString*)key toTransform:(CATransform3D)toValue time:(NSTimeInterval)seconds; /** Animates a key of the layer to a `CATransform3D` value with custom easing. * * `CABasicAnimation` is used for the animation. * * @param key The key to animate. * @param toValue The ending value. * @param seconds The number of seconds the animation should take. * @param easing The easing function to use. This can be an instance of `CAMediaTimingFunction` or one of the constants * that can be used to construct an instance of that class. */ -(void)animate:(NSString*)key toTransform:(CATransform3D)toValue time:(NSTimeInterval)seconds eased:(id)easing; #pragma mark Hit Testing /** @name Hit Testing */ /** Performs a hit test, then moves up the layer tree until it finds a layer of the specified class. If such a layer is * not found, returns `nil`. * * @param point The point to hit test. * @param klass The layer class to search for. */ -(CALayer*)hitTest:(CGPoint)point forClass:(Class)klass; @end
<reponame>zemahran/spiral<filename>spiral/environments/fluid_wrapper/simulator.cc // Copyright 2019 DeepMind Technologies Limited. // // 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 // // https://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. #include "spiral/environments/fluid_wrapper/simulator.h" #include <algorithm> #include <numeric> #include <ostream> #include <utility> #include "spiral/environments/fluid_wrapper/brush.h" #include "spiral/environments/fluid_wrapper/utils.h" #include "absl/strings/string_view.h" namespace spiral { namespace fluid { Simulator::Simulator(const Config::Simulator& config) : kNumJacobiIterations(config.num_jacobi_iterations()), kNumFramesToSimulate(config.num_frames_to_simulate()), kSplatPadding(config.splat_padding()), kSpeedPadding(config.speed_padding()) {} void Simulator::Setup(int width, int height, absl::string_view shader_base_dir) { width_ = width; height_ = height; // Create shader programs. ShaderSourceComposer composer(shader_base_dir); program_map_[ProgramId::kSplat] = CreateShaderProgram( composer.Compose("splat.vert"), composer.Compose("splat.frag"), &attrib_loc_map_[ProgramId::kSplat], &uniform_loc_map_[ProgramId::kSplat]); program_map_[ProgramId::kVelocitySplat] = CreateShaderProgram( composer.Compose("splat.vert", "#define VELOCITY \n"), composer.Compose("splat.frag", "#define VELOCITY \n"), &attrib_loc_map_[ProgramId::kVelocitySplat], &uniform_loc_map_[ProgramId::kVelocitySplat]); program_map_[ProgramId::kAdvect] = CreateShaderProgram( composer.Compose("fullscreen.vert"), composer.Compose("advect.frag"), &attrib_loc_map_[ProgramId::kAdvect], &uniform_loc_map_[ProgramId::kAdvect]); program_map_[ProgramId::kDivergence] = CreateShaderProgram( composer.Compose("fullscreen.vert"), composer.Compose("divergence.frag"), &attrib_loc_map_[ProgramId::kDivergence], &uniform_loc_map_[ProgramId::kDivergence]); program_map_[ProgramId::kJacobi] = CreateShaderProgram( composer.Compose("fullscreen.vert"), composer.Compose("jacobi.frag"), &attrib_loc_map_[ProgramId::kJacobi], &uniform_loc_map_[ProgramId::kJacobi]); program_map_[ProgramId::kSubtract] = CreateShaderProgram( composer.Compose("fullscreen.vert"), composer.Compose("subtract.frag"), &attrib_loc_map_[ProgramId::kSubtract], &uniform_loc_map_[ProgramId::kSubtract]); // Create VBOs. CHECK_GL_ERROR(glGenBuffers(1, &quad_vbo_)); CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, quad_vbo_)); CHECK_GL_ERROR(glBufferData(GL_ARRAY_BUFFER, sizeof(kQuadVerts), kQuadVerts, GL_STATIC_DRAW)); CHECK_GL_ERROR(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr)); // Create simulation framebuffer. CHECK_GL_ERROR(glGenFramebuffers(1, &simulation_framebuffer_)); // Create textures. for (auto texture_id : { TextureId::kPaint, TextureId::kPaintTemp, TextureId::kVelocity, TextureId::kVelocityTemp}) { texture_map_[texture_id] = CreateTexture(GL_RGBA32F, GL_RGBA, GL_FLOAT, width_, height_, nullptr, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR); } for (auto texture_id : {TextureId::kDivergence, TextureId::kPressure, TextureId::kPressureTemp}) { texture_map_[texture_id] = CreateTexture(GL_RGBA32F, GL_RGBA, GL_FLOAT, width_, height_, nullptr, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_NEAREST, GL_NEAREST); } Reset(); } void Simulator::Reset() { ClearTextures({ TextureId::kPaint, TextureId::kPaintTemp, TextureId::kVelocity, TextureId::kVelocityTemp, TextureId::kPressure, TextureId::kPressureTemp, TextureId::kDivergence }); splat_areas_.clear(); frame_number_ = 0; } void Simulator::ClearTextures(std::vector<TextureId> texture_ids) { CHECK_GL_ERROR( glBindFramebuffer(GL_FRAMEBUFFER, simulation_framebuffer_)); CHECK_GL_ERROR(glClearColor(0.0, 0.0, 0.0, 1.0)); for (auto texture_id : texture_ids) { GLint texture = texture_map_.at(texture_id); CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0)); CHECK_GL_ERROR(glClear(GL_COLOR_BUFFER_BIT)); } } void Simulator::RunAdvect(Rectangle<float> simulation_area, TextureId velocity_texture, TextureId data_texture, TextureId target_texture, float delta_time, float dissipation) { GLuint program = program_map_[ProgramId::kAdvect]; const auto& uniform_loc_map = uniform_loc_map_[ProgramId::kAdvect]; const auto& attrib_loc_map = attrib_loc_map_[ProgramId::kAdvect]; CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, simulation_framebuffer_)); CHECK_GL_ERROR(glViewport(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glEnable(GL_SCISSOR_TEST)); CHECK_GL_ERROR(glScissor(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glUseProgram(program)); CHECK_GL_ERROR(glUniform1f( uniform_loc_map.at("u_dissipation"), dissipation)); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_resolution"), width_, height_)); SetTextureUniformVariable( uniform_loc_map.at("u_velocityTexture"), 0, texture_map_.at(velocity_texture)); SetTextureUniformVariable( uniform_loc_map.at("u_inputTexture"), 1, texture_map_.at(data_texture)); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_min"), simulation_area.xmin(), simulation_area.ymin())); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_max"), simulation_area.xmax(), simulation_area.ymax())); CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, quad_vbo_)); CHECK_GL_ERROR(glVertexAttribPointer( attrib_loc_map.at("a_position"), 2, GL_FLOAT, false, 0, nullptr)); CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_map_.at(target_texture), 0)); CHECK_GL_ERROR(glUniform1f( uniform_loc_map.at("u_deltaTime"), delta_time)); CHECK_GL_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)); CHECK_GL_ERROR(glDisable(GL_SCISSOR_TEST)); } void Simulator::RunDivergence(Rectangle<float> simulation_area) { GLuint program = program_map_[ProgramId::kDivergence]; const auto& uniform_loc_map = uniform_loc_map_[ProgramId::kDivergence]; const auto& attrib_loc_map = attrib_loc_map_[ProgramId::kDivergence]; CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, simulation_framebuffer_)); CHECK_GL_ERROR(glViewport(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glEnable(GL_SCISSOR_TEST)); CHECK_GL_ERROR(glScissor(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glUseProgram(program)); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_resolution"), width_, height_)); SetTextureUniformVariable( uniform_loc_map.at("u_velocityTexture"), 0, texture_map_.at(TextureId::kVelocity)); CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, quad_vbo_)); CHECK_GL_ERROR(glVertexAttribPointer( attrib_loc_map.at("a_position"), 2, GL_FLOAT, false, 0, nullptr)); CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_map_.at(TextureId::kDivergence), 0)); CHECK_GL_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)); CHECK_GL_ERROR(glDisable(GL_SCISSOR_TEST)); } void Simulator::RunJacobi(Rectangle<float> simulation_area) { GLuint program = program_map_[ProgramId::kJacobi]; const auto& uniform_loc_map = uniform_loc_map_[ProgramId::kJacobi]; const auto& attrib_loc_map = attrib_loc_map_[ProgramId::kJacobi]; CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, simulation_framebuffer_)); CHECK_GL_ERROR(glViewport(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glEnable(GL_SCISSOR_TEST)); CHECK_GL_ERROR(glScissor(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glUseProgram(program)); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_resolution"), width_, height_)); SetTextureUniformVariable( uniform_loc_map.at("u_divergenceTexture"), 1, texture_map_.at(TextureId::kDivergence)); CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, quad_vbo_)); CHECK_GL_ERROR(glVertexAttribPointer( attrib_loc_map.at("a_position"), 2, GL_FLOAT, false, 0, nullptr)); CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_map_.at(TextureId::kPressure), 0)); CHECK_GL_ERROR(glClear(GL_COLOR_BUFFER_BIT)); for (int iteration = 0; iteration < kNumJacobiIterations; ++iteration) { CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_map_.at(TextureId::kPressureTemp), 0)); SetTextureUniformVariable( uniform_loc_map.at("u_pressureTexture"), 1, texture_map_.at(TextureId::kPressure)); CHECK_GL_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)); CHECK_GL_ERROR(glDisable(GL_SCISSOR_TEST)); std::swap(texture_map_.at(TextureId::kPressure), texture_map_.at(TextureId::kPressureTemp)); } } void Simulator::RunSubtract(Rectangle<float> simulation_area) { GLuint program = program_map_[ProgramId::kSubtract]; const auto& uniform_loc_map = uniform_loc_map_[ProgramId::kSubtract]; const auto& attrib_loc_map = attrib_loc_map_[ProgramId::kSubtract]; CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, simulation_framebuffer_)); CHECK_GL_ERROR(glViewport(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glEnable(GL_SCISSOR_TEST)); CHECK_GL_ERROR(glScissor(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glUseProgram(program)); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_resolution"), width_, height_)); SetTextureUniformVariable( uniform_loc_map.at("u_pressureTexture"), 0, texture_map_.at(TextureId::kPressure)); SetTextureUniformVariable( uniform_loc_map.at("u_velocityTexture"), 1, texture_map_.at(TextureId::kVelocity)); CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, quad_vbo_)); CHECK_GL_ERROR(glVertexAttribPointer( attrib_loc_map.at("a_position"), 2, GL_FLOAT, false, 0, nullptr)); CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_map_.at(TextureId::kVelocityTemp), 0)); CHECK_GL_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)); CHECK_GL_ERROR(glDisable(GL_SCISSOR_TEST)); std::swap(texture_map_.at(TextureId::kVelocity), texture_map_.at(TextureId::kVelocityTemp)); } void Simulator::RunSplat(const Brush &brush, Rectangle<float> simulation_area, Rectangle<float> painting_rectangle, float radius, float color[4], float z_threshold) { GLuint program = program_map_[ProgramId::kSplat]; const auto& uniform_loc_map = uniform_loc_map_[ProgramId::kSplat]; const auto& attrib_loc_map = attrib_loc_map_[ProgramId::kSplat]; CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, simulation_framebuffer_)); CHECK_GL_ERROR(glViewport(0, 0, width_, height_)); CHECK_GL_ERROR(glEnable(GL_SCISSOR_TEST)); // Restrict splatting to area that'll be simulated CHECK_GL_ERROR(glScissor(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glEnable(GL_BLEND)); CHECK_GL_ERROR(glBlendEquation(GL_FUNC_ADD)); CHECK_GL_ERROR(glBlendFuncSeparate( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE)); CHECK_GL_ERROR(glUseProgram(program)); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_paintingDimensions"), painting_rectangle.Width(), painting_rectangle.Height())); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_paintingPosition"), painting_rectangle.xmin(), painting_rectangle.ymin())); CHECK_GL_ERROR(glUniform1f( uniform_loc_map.at("u_splatRadius"), radius)); CHECK_GL_ERROR(glUniform4f( uniform_loc_map.at("u_splatColor"), color[0], color[1], color[2], color[3])); CHECK_GL_ERROR(glUniform1f( uniform_loc_map.at("u_zThreshold"), z_threshold)); SetTextureUniformVariable( uniform_loc_map.at("u_positionsTexture"), 0, brush.GetTexture(Brush::TextureId::kPositions)); SetTextureUniformVariable( uniform_loc_map.at("u_previousPositionsTexture"), 1, brush.GetTexture(Brush::TextureId::kPreviousPositions)); CHECK_GL_ERROR(glBindBuffer( GL_ARRAY_BUFFER, brush.GetVbo(Brush::VboId::kSplatCoords))); CHECK_GL_ERROR(glVertexAttribPointer( attrib_loc_map.at("a_splatCoordinates"), 4, GL_FLOAT, false, 0, nullptr)); CHECK_GL_ERROR(glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, brush.GetVbo(Brush::VboId::kSplatIndices))); CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_map_.at(TextureId::kPaint), 0)); CHECK_GL_ERROR(glDrawElements( GL_TRIANGLES, brush.NumSplatIndicesToRender(), GL_UNSIGNED_SHORT, nullptr)); CHECK_GL_ERROR(glDisable(GL_BLEND)); CHECK_GL_ERROR(glDisable(GL_SCISSOR_TEST)); } void Simulator::RunVelocitySplat(const Brush &brush, Rectangle<float> simulation_area, Rectangle<float> painting_rectangle, float radius, float z_threshold, float velocity_scale) { GLuint program = program_map_[ProgramId::kVelocitySplat]; const auto& uniform_loc_map = uniform_loc_map_[ProgramId::kVelocitySplat]; const auto& attrib_loc_map = attrib_loc_map_[ProgramId::kVelocitySplat]; CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, simulation_framebuffer_)); CHECK_GL_ERROR(glViewport(0, 0, width_, height_)); CHECK_GL_ERROR(glEnable(GL_SCISSOR_TEST)); // Restrict splatting to area that'll be simulated CHECK_GL_ERROR(glScissor(simulation_area.xmin(), simulation_area.ymin(), simulation_area.Width(), simulation_area.Height())); CHECK_GL_ERROR(glEnable(GL_BLEND)); CHECK_GL_ERROR(glBlendEquation(GL_FUNC_ADD)); CHECK_GL_ERROR(glBlendFuncSeparate( GL_ONE, GL_ONE, GL_ZERO, GL_ZERO)); CHECK_GL_ERROR(glUseProgram(program)); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_paintingDimensions"), painting_rectangle.Width(), painting_rectangle.Height())); CHECK_GL_ERROR(glUniform2f( uniform_loc_map.at("u_paintingPosition"), painting_rectangle.xmin(), painting_rectangle.ymin())); CHECK_GL_ERROR(glUniform1f( uniform_loc_map.at("u_splatRadius"), radius)); CHECK_GL_ERROR(glUniform1f( uniform_loc_map.at("u_zThreshold"), z_threshold)); CHECK_GL_ERROR(glUniform1f( uniform_loc_map.at("u_velocityScale"), velocity_scale)); SetTextureUniformVariable( uniform_loc_map.at("u_positionsTexture"), 0, brush.GetTexture(Brush::TextureId::kPositions)); SetTextureUniformVariable( uniform_loc_map.at("u_previousPositionsTexture"), 1, brush.GetTexture(Brush::TextureId::kPreviousPositions)); SetTextureUniformVariable( uniform_loc_map.at("u_velocitiesTexture"), 2, brush.GetTexture(Brush::TextureId::kVelocities)); SetTextureUniformVariable( uniform_loc_map.at("u_previousVelocitiesTexture"), 3, brush.GetTexture(Brush::TextureId::kPreviousVelocities)); CHECK_GL_ERROR(glBindBuffer( GL_ARRAY_BUFFER, brush.GetVbo(Brush::VboId::kSplatCoords))); CHECK_GL_ERROR(glVertexAttribPointer( attrib_loc_map.at("a_splatCoordinates"), 4, GL_FLOAT, false, 0, nullptr)); CHECK_GL_ERROR(glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, brush.GetVbo(Brush::VboId::kSplatIndices))); CHECK_GL_ERROR(glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_map_.at(TextureId::kVelocity), 0)); CHECK_GL_ERROR(glDrawElements( GL_TRIANGLES, brush.NumSplatIndicesToRender(), GL_UNSIGNED_SHORT, nullptr)); CHECK_GL_ERROR(glDisable(GL_BLEND)); CHECK_GL_ERROR(glDisable(GL_SCISSOR_TEST)); } Rectangle<float> Simulator::GetSimulationArea() { if (splat_areas_.empty()) { return Rectangle<float>(0, 0, 0, 0); } // Now let's work out the total simulation area we need to simulate. auto it = splat_areas_.begin(); auto simulation_area = (*it).first; ++it; for (; it != splat_areas_.end(); ++it) { simulation_area = simulation_area.Union((*it).first); } simulation_area.Round(); simulation_area = simulation_area.Intersect( Rectangle<float>(0, 0, width_, height_)); return simulation_area; } void Simulator::CleanupSplatAreas() { // Remove all of the splat areas we no longer need to simulate. auto it = splat_areas_.begin(); while (it != splat_areas_.end()) { if (frame_number_ - (*it).second > kNumFramesToSimulate) { it = splat_areas_.erase(it); } else { ++it; } } } void Simulator::Splat(const Brush &brush, Rectangle<float> painting_rectangle, float z_threshold, float splat_color[4], float splat_radius, float velocity_scale) { // The area we need to simulate for this set of splats. int brush_padding = std::ceil(brush.Scale() * kSplatPadding); brush_padding += std::ceil(brush.GetFilteredSpeed() * kSpeedPadding); // We start in canvas space. Rectangle<float> area(brush.x() - brush_padding, brush.y() - brush_padding, brush_padding * 2, brush_padding * 2); // Transform area into simulation space. area.Translate(-painting_rectangle.xmin(), -painting_rectangle.ymin()); area.Scale(width_ / painting_rectangle.Width(), height_ / painting_rectangle.Height()); area.Round(); area = area.Intersect(Rectangle<float>(0, 0, width_, height_)); splat_areas_.push_back(std::make_pair(area, frame_number_)); auto simulation_area = GetSimulationArea(); RunSplat(brush, simulation_area, painting_rectangle, splat_radius, splat_color, z_threshold); RunVelocitySplat(brush, simulation_area, painting_rectangle, splat_radius, z_threshold, velocity_scale); } Simulator::Status Simulator::Simulate() { const float delta_time = 1.0 / 60.0; const float fluidity = 0.8; if (splat_areas_.empty()) { return Status::kSkippedSimulation; } auto simulation_area = GetSimulationArea(); RunDivergence(simulation_area); RunJacobi(simulation_area); RunAdvect( simulation_area, TextureId::kVelocity, TextureId::kPaint, TextureId::kPaintTemp, delta_time, 1.0); std::swap(texture_map_.at(TextureId::kPaint), texture_map_.at(TextureId::kPaintTemp)); RunAdvect( simulation_area, TextureId::kVelocity, TextureId::kVelocity, TextureId::kVelocityTemp, delta_time, fluidity); std::swap(texture_map_.at(TextureId::kVelocity), texture_map_.at(TextureId::kVelocityTemp)); frame_number_++; CleanupSplatAreas(); // If we finished simulating on this step clear all velocity textures. if (splat_areas_.empty()) { ClearTextures({TextureId::kVelocity, TextureId::kVelocityTemp}); } return Status::kFinishedSimulation; } } // namespace fluid } // namespace spiral
#import sys #sys.stdin=open('in','r') r=raw_input n,k,l,r,sall,sk=map(int,r().split()) d1=sk/k m1=sk%k if k!=n: d2=(sall-sk)/(n-k) m2=(sall-sk)%(n-k) else: d2=m2=0 res1 = [] res2 = [] for t in ( (k,d1,m1,res1),(n-k,d2,m2,res2) ): for i in range(t[0]): t[3].append(t[1]) for i in range(t[2]): t[3][i]+=1 R=res1+res2 for x in R: print x,
Tuberculosis screening among healthcare workers in Sicily, Italy. Tuberculosis (TB) is a diffuse communicable disease; and healthcare workers (HCWs) are among the at-risk populations for the disease. This study reports the result of TB surveillance in HCWs operating in three hospitals: one classified as 'low' risk for TB and two as 'medium' risk. A total of 2228 HCWs underwent TB screening using the standard Mantoux technique (also known as the tuberculin sensitivity test ). Interfero- γ release assay (IGRA) was carried out in TST-positive subjects. Results showed an overall positivity of 21% to TST and 2% to IGRA test. TST and IGRA results were statistically associated with HCWs born after 1981. This result is due to university policies that highly recommend TB immunization. Data support the use of IGRA assay in TST-positive HCWs, in order to identify latent TB infection from vaccination.
<reponame>snieguu/remote-device-client<filename>src/main/java/com/bitbar/remotedevice/errors/WrongParameterException.java package com.bitbar.remotedevice.errors; import com.bitbar.remotedevice.cli.CommandLineParameter; public class WrongParameterException extends Exception { public WrongParameterException(CommandLineParameter parameter) { super(String.format("Parameter \"%s\" is wrong!", parameter.getArgument())); } }
<reponame>GregB76/EU4toVic2 #include "MergeBlock.h" #include "ParserHelpers.h" EU4::MergeBlock::MergeBlock(std::istream& theStream) { registerKeyword("master", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString masterStr(theStream); master = masterStr.getString(); }); registerKeyword("slave", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString slaveStr(theStream); slaves.insert(slaveStr.getString()); }); registerKeyword("merge", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString mergeStr(theStream); merge = (mergeStr.getString() == "yes"); }); registerRegex("[a-zA-Z0-9_\\.:]+", commonItems::ignoreItem); parseStream(theStream); clearRegisteredKeywords(); }
def main(argc: int, argv: List[str]): run(create_app, host='0.0.0.0', port=8000)
# coding: utf-8 # Your code here! A, B = map(int, input().split()) add = A + B sub = A - B mul = A * B print(max(add, sub, mul))
def Danilevski(A): all_polynomial = [] n = A.shape[0] back = np.eye(n) similar = A.copy() list_eigenvalues = [] list_eigenvectors = [] charFunc = [] k = n-1 m = n while k > 0: if similar[k, k-1] != 0: similar, _, inverseM = findSimpleA(similar, k) back = back.dot(inverseM) else: non = False for j in range(0, k-1): if similar[k, j] != 0: similar = specialCase1(similar, k , j) back[:, [j, k-1]] = back[:, [k-1, j]] non = True k = k+1 break if not non: for j in range(k, m-1): M = np.eye(m) M[:k, j+1] = -similar[:k, j] inverseM = np.eye(m) inverseM[:k, j+1] = similar[:k, j] similar = M.dot(similar).dot(inverseM) back = back.dot(inverseM) tt= False for j in range(k-1, -1, -1): if similar[j, m-1] != 0: M = np.eye(m) x = M[k:m, :] y = M[k-1, :] M = np.vstack([M[0:k-1, :], x, y]) M1 = M.T similar = M.dot(similar).dot(M1) back = back.dot(M1) k = m; tt = True break if not tt: X = similar[k:, k:] t = X.shape[0] eigenValues = findValue(X) for j in range(len(eigenValues)): print("Vector rieng cua: ", eigenValues[j]) list_eigenvalues.append(eigenValues[j]) y = np.power(eigenValues[j], np.arange(t))[::-1].reshape((t, 1)) v = np.zeros((n, 1)) p = np.zeros((m, 1)) p[k:m] = y p = back.dot(p) v[:m] = p list_eigenvectors.append(v) print(v) m = k similar = similar[:k, :k] back = np.eye(m) k = k - 1 X = similar t = X.shape[0] eigenValues = findValue(X) for j in range(len(eigenValues)): print("Vector rieng cua: ", eigenValues[j]) list_eigenvalues.append(eigenValues[j]) y = np.power(eigenValues[j], np.arange(t))[::-1].reshape((t, 1)) p = np.zeros((m, 1)) v = np.zeros((n, 1)) p[k:m] = y p = back.dot(p) v[:m] = p list_eigenvectors.append(v) print(v) return list_eigenvalues, list_eigenvectors
/** * This class is a container for dictionary values. It allows reading values in cycle. */ private static class Dictionary { private final List<String> iterable; private Iterator<String> iterator; Dictionary(List<String> iterable) { this.iterable = iterable; this.iterator = iterable.iterator(); } /** * Return next value from values collection. * When iterator points to last element of collection, * it is set to the collection first element. */ String nextValue() { if (iterable.isEmpty()) { return null; } else if (!iterator.hasNext()) { iterator = iterable.iterator(); } return iterator.next(); } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * <EMAIL>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Purpose: This file contains declarations which are visible only within * the H5VL package. Source files outside the H5VL package should * include H5VLprivate.h instead. */ #if !(defined H5VL_FRIEND || defined H5VL_MODULE) #error "Do not include this file outside the H5VL package!" #endif #ifndef _H5VLpkg_H #define _H5VLpkg_H /* Get package's private header */ #include "H5VLprivate.h" /* Generic Functions */ /* Other private headers needed by this file */ /**************************/ /* Package Private Macros */ /**************************/ /****************************/ /* Package Private Typedefs */ /****************************/ /*****************************/ /* Package Private Variables */ /*****************************/ /******************************/ /* Package Private Prototypes */ /******************************/ #endif /* _H5VLpkg_H */
Dear Reader, As you can imagine, more people are reading The Jerusalem Post than ever before. Nevertheless, traditional business models are no longer sustainable and high-quality publications, like ours, are being forced to look for new ways to keep going. Unlike many other news organizations, we have not put up a paywall. We want to keep our journalism open and accessible and be able to keep providing you with news and analysis from the frontlines of Israel, the Middle East and the Jewish World. Dozens of students competed to find solutions to Israel’s hasbara (public diplomacy) problems in a hackathon held at Haifa’s Technion-Israel Institute of Technology last week. The 80 participants were presented with the challenge of creating an app to dispel myths about Israel. They were posed with the question: “What will be the next strong hashtag after #bdsfail?” The 44-hour hackathon - named iHack - kicked off Wednesday evening and was held under the auspices of StandWithUs in collaboration with other organizations and companies such as Rafael Advanced Defense Systems, the Student Union and the Entrepreneurship Center of the Technion. Twenty-one of the Technion students involved completed a StandWithUs fellowship for public diplomacy leadership. “We challenged our student Fellows to initiate a project to elevate Israel and they took the ball and ran with it”, said Michael Dickson, Executive Director of StandWithUs. “The identified some of the top young minds in Israeli tech, brought them together for an intensive 44-hour experience where they innovated amazing ideas, using tech to reach people globally about Israel”. Yaakov Hagoel, vice chairman of the World Zionist Organization, who visited the hackathon said that while pro-Israel organizations were initially caught off guard by the birth of the Boycott Divestment and Sanction movement, from the moment the Jewish world began reacting, it began to hurt the movement.“We are all working together and I have no doubt the hackathon will bring serious results,” he stated.A team of mentors were on hand throughout the event, including 20 Rafael employees, and other experts in the fields of software and engineering, political science, marketing and graphic design. Students formed teams to develop products to tackle BDS and to help enhance Israel’s image in the media and international community.Yair Eddie Fraiman, director of public diplomacy at the Strategic Affairs and Public Diplomacy Ministry, said that he primarily came to watch. “We’re in 2016, so it could be that a student has an idea we didn’t think of. The aim of the hackathon is to think outside of the box. We understand that in our world of social networks and technology, an idea that can really help Israel could really come from this.”One team decided to create a “diplomatic Iron Dome.” Ezra (last name withheld), a team member from Rafael, brought his experience of working with military systems and applied it to the “hasbara problem.” The team envisioned anti-Israel expression as the missile, and their app as the Iron Dome that must intercept it. “Instead of a missile, it could be a blog, or negative articles or a speech, and our Iron Dome will comprise of a network of individuals and organizations who can respond,” he told the Post.“We would have pro-Israel activists around the world who are witness to these anti-Israel events and they would report them into the system. That would get fed into a war room with a big plasma TV and a map of world, so we can see where the threats come from, and whether they are serious enough to require an ambassador to respond. A negative Tweet then can be answered on social media, or by a professor that students can reply to. The people who respond are our interceptors.”Another team attempted to enhance tourists’ experiences of Israel via an image-improving version of services such as Airbnb and CouchSurfing.Dima Glinets, an engineering student from the Technion, said the app would create the best possible image of Israel. It would match Israelis with visitors to the country, based on mutual interests such as hiking or other activities. The Israeli would not only host the matching tourist, but would also show them around the country. “We believe the best hasbara tool is to share beautiful moments,” Glinets said.The winning apps will be put to use in StandWithUs's cyber center. Join Jerusalem Post Premium Plus now for just $5 and upgrade your experience with an ads-free website and exclusive content. Click here>>
<gh_stars>1-10 // SPDX-License-Identifier: GPL-2.0 /* * usb-serial driver for Quatech USB 2 devices * * Copyright (C) 2012 <NAME> (<EMAIL>) * * These devices all have only 1 bulk in and 1 bulk out that is shared * for all serial ports. * */ #include <asm/unaligned.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/serial.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include <linux/serial_reg.h> #include <linux/uaccess.h> /* default urb timeout for usb operations */ #define QT2_USB_TIMEOUT USB_CTRL_SET_TIMEOUT #define QT_OPEN_CLOSE_CHANNEL 0xca #define QT_SET_GET_DEVICE 0xc2 #define QT_SET_GET_REGISTER 0xc0 #define QT_GET_SET_PREBUF_TRIG_LVL 0xcc #define QT_SET_ATF 0xcd #define QT_TRANSFER_IN 0xc0 #define QT_HW_FLOW_CONTROL_MASK 0xc5 #define QT_SW_FLOW_CONTROL_MASK 0xc6 #define QT2_BREAK_CONTROL 0xc8 #define QT2_GET_SET_UART 0xc1 #define QT2_FLUSH_DEVICE 0xc4 #define QT2_GET_SET_QMCR 0xe1 #define QT2_QMCR_RS232 0x40 #define QT2_QMCR_RS422 0x10 #define SERIAL_CRTSCTS ((UART_MCR_RTS << 8) | UART_MSR_CTS) #define SERIAL_EVEN_PARITY (UART_LCR_PARITY | UART_LCR_EPAR) /* status bytes for the device */ #define QT2_CONTROL_BYTE 0x1b #define QT2_LINE_STATUS 0x00 /* following 1 byte is line status */ #define QT2_MODEM_STATUS 0x01 /* following 1 byte is modem status */ #define QT2_XMIT_HOLD 0x02 /* following 2 bytes are ?? */ #define QT2_CHANGE_PORT 0x03 /* following 1 byte is port to change to */ #define QT2_REC_FLUSH 0x04 /* no following info */ #define QT2_XMIT_FLUSH 0x05 /* no following info */ #define QT2_CONTROL_ESCAPE 0xff /* pass through previous 2 control bytes */ #define MAX_BAUD_RATE 921600 #define DEFAULT_BAUD_RATE 9600 #define QT2_READ_BUFFER_SIZE 512 /* size of read buffer */ #define QT2_WRITE_BUFFER_SIZE 512 /* size of write buffer */ #define QT2_WRITE_CONTROL_SIZE 5 /* control bytes used for a write */ #define DRIVER_DESC "Quatech 2nd gen USB to Serial Driver" #define USB_VENDOR_ID_QUATECH 0x061d #define QUATECH_SSU2_100 0xC120 /* RS232 single port */ #define QUATECH_DSU2_100 0xC140 /* RS232 dual port */ #define QUATECH_DSU2_400 0xC150 /* RS232/422/485 dual port */ #define QUATECH_QSU2_100 0xC160 /* RS232 four port */ #define QUATECH_QSU2_400 0xC170 /* RS232/422/485 four port */ #define QUATECH_ESU2_100 0xC1A0 /* RS232 eight port */ #define QUATECH_ESU2_400 0xC180 /* RS232/422/485 eight port */ struct qt2_device_detail { int product_id; int num_ports; }; #define QT_DETAILS(prod, ports) \ .product_id = (prod), \ .num_ports = (ports) static const struct qt2_device_detail qt2_device_details[] = { {QT_DETAILS(QUATECH_SSU2_100, 1)}, {QT_DETAILS(QUATECH_DSU2_400, 2)}, {QT_DETAILS(QUATECH_DSU2_100, 2)}, {QT_DETAILS(QUATECH_QSU2_400, 4)}, {QT_DETAILS(QUATECH_QSU2_100, 4)}, {QT_DETAILS(QUATECH_ESU2_400, 8)}, {QT_DETAILS(QUATECH_ESU2_100, 8)}, {QT_DETAILS(0, 0)} /* Terminating entry */ }; static const struct usb_device_id id_table[] = { {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU2_100)}, {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_100)}, {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_400)}, {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_100)}, {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_400)}, {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_100)}, {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_400)}, {} /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, id_table); struct qt2_serial_private { unsigned char current_port; /* current port for incoming data */ struct urb *read_urb; /* shared among all ports */ char *read_buffer; }; struct qt2_port_private { u8 device_port; spinlock_t urb_lock; bool urb_in_use; struct urb *write_urb; char *write_buffer; spinlock_t lock; u8 shadowLSR; u8 shadowMSR; struct usb_serial_port *port; }; static void qt2_update_lsr(struct usb_serial_port *port, unsigned char *ch); static void qt2_update_msr(struct usb_serial_port *port, unsigned char *ch); static void qt2_write_bulk_callback(struct urb *urb); static void qt2_read_bulk_callback(struct urb *urb); static void qt2_release(struct usb_serial *serial) { struct qt2_serial_private *serial_priv; serial_priv = usb_get_serial_data(serial); usb_kill_urb(serial_priv->read_urb); usb_free_urb(serial_priv->read_urb); kfree(serial_priv->read_buffer); kfree(serial_priv); } static inline int calc_baud_divisor(int baudrate) { int divisor, rem; divisor = MAX_BAUD_RATE / baudrate; rem = MAX_BAUD_RATE % baudrate; /* Round to nearest divisor */ if (((rem * 2) >= baudrate) && (baudrate != 110)) divisor++; return divisor; } static inline int qt2_set_port_config(struct usb_device *dev, unsigned char port_number, u16 baudrate, u16 lcr) { int divisor = calc_baud_divisor(baudrate); u16 index = ((u16) (lcr << 8) | (u16) (port_number)); return usb_control_msg(dev, usb_sndctrlpipe(dev, 0), QT2_GET_SET_UART, 0x40, divisor, index, NULL, 0, QT2_USB_TIMEOUT); } static inline int qt2_control_msg(struct usb_device *dev, u8 request, u16 data, u16 index) { return usb_control_msg(dev, usb_sndctrlpipe(dev, 0), request, 0x40, data, index, NULL, 0, QT2_USB_TIMEOUT); } static inline int qt2_setdevice(struct usb_device *dev, u8 *data) { u16 x = ((u16) (data[1] << 8) | (u16) (data[0])); return qt2_control_msg(dev, QT_SET_GET_DEVICE, x, 0); } static inline int qt2_getregister(struct usb_device *dev, u8 uart, u8 reg, u8 *data) { int ret; ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), QT_SET_GET_REGISTER, 0xc0, reg, uart, data, sizeof(*data), QT2_USB_TIMEOUT); if (ret < (int)sizeof(*data)) { if (ret >= 0) ret = -EIO; } return ret; } static inline int qt2_setregister(struct usb_device *dev, u8 uart, u8 reg, u16 data) { u16 value = (data << 8) | reg; return usb_control_msg(dev, usb_sndctrlpipe(dev, 0), QT_SET_GET_REGISTER, 0x40, value, uart, NULL, 0, QT2_USB_TIMEOUT); } static inline int update_mctrl(struct qt2_port_private *port_priv, unsigned int set, unsigned int clear) { struct usb_serial_port *port = port_priv->port; struct usb_device *dev = port->serial->dev; unsigned urb_value; int status; if (((set | clear) & (TIOCM_DTR | TIOCM_RTS)) == 0) { dev_dbg(&port->dev, "update_mctrl - DTR|RTS not being set|cleared\n"); return 0; /* no change */ } clear &= ~set; /* 'set' takes precedence over 'clear' */ urb_value = 0; if (set & TIOCM_DTR) urb_value |= UART_MCR_DTR; if (set & TIOCM_RTS) urb_value |= UART_MCR_RTS; status = qt2_setregister(dev, port_priv->device_port, UART_MCR, urb_value); if (status < 0) dev_err(&port->dev, "update_mctrl - Error from MODEM_CTRL urb: %i\n", status); return status; } static int qt2_calc_num_ports(struct usb_serial *serial, struct usb_serial_endpoints *epds) { struct qt2_device_detail d; int i; for (i = 0; d = qt2_device_details[i], d.product_id != 0; i++) { if (d.product_id == le16_to_cpu(serial->dev->descriptor.idProduct)) return d.num_ports; } /* we didn't recognize the device */ dev_err(&serial->dev->dev, "don't know the number of ports, assuming 1\n"); return 1; } static void qt2_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct usb_device *dev = port->serial->dev; struct qt2_port_private *port_priv; struct ktermios *termios = &tty->termios; u16 baud; unsigned int cflag = termios->c_cflag; u16 new_lcr = 0; int status; port_priv = usb_get_serial_port_data(port); if (cflag & PARENB) { if (cflag & PARODD) new_lcr |= UART_LCR_PARITY; else new_lcr |= SERIAL_EVEN_PARITY; } switch (cflag & CSIZE) { case CS5: new_lcr |= UART_LCR_WLEN5; break; case CS6: new_lcr |= UART_LCR_WLEN6; break; case CS7: new_lcr |= UART_LCR_WLEN7; break; default: case CS8: new_lcr |= UART_LCR_WLEN8; break; } baud = tty_get_baud_rate(tty); if (!baud) baud = 9600; status = qt2_set_port_config(dev, port_priv->device_port, baud, new_lcr); if (status < 0) dev_err(&port->dev, "%s - qt2_set_port_config failed: %i\n", __func__, status); if (cflag & CRTSCTS) status = qt2_control_msg(dev, QT_HW_FLOW_CONTROL_MASK, SERIAL_CRTSCTS, port_priv->device_port); else status = qt2_control_msg(dev, QT_HW_FLOW_CONTROL_MASK, 0, port_priv->device_port); if (status < 0) dev_err(&port->dev, "%s - set HW flow control failed: %i\n", __func__, status); if (I_IXOFF(tty) || I_IXON(tty)) { u16 x = ((u16) (START_CHAR(tty) << 8) | (u16) (STOP_CHAR(tty))); status = qt2_control_msg(dev, QT_SW_FLOW_CONTROL_MASK, x, port_priv->device_port); } else status = qt2_control_msg(dev, QT_SW_FLOW_CONTROL_MASK, 0, port_priv->device_port); if (status < 0) dev_err(&port->dev, "%s - set SW flow control failed: %i\n", __func__, status); } static int qt2_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial; struct qt2_port_private *port_priv; u8 *data; u16 device_port; int status; unsigned long flags; device_port = port->port_number; serial = port->serial; port_priv = usb_get_serial_port_data(port); /* set the port to RS232 mode */ status = qt2_control_msg(serial->dev, QT2_GET_SET_QMCR, QT2_QMCR_RS232, device_port); if (status < 0) { dev_err(&port->dev, "%s failed to set RS232 mode for port %i error %i\n", __func__, device_port, status); return status; } data = kzalloc(2, GFP_KERNEL); if (!data) return -ENOMEM; /* open the port */ status = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0), QT_OPEN_CLOSE_CHANNEL, 0xc0, 0, device_port, data, 2, QT2_USB_TIMEOUT); if (status < 2) { dev_err(&port->dev, "%s - open port failed %i\n", __func__, status); if (status >= 0) status = -EIO; kfree(data); return status; } spin_lock_irqsave(&port_priv->lock, flags); port_priv->shadowLSR = data[0]; port_priv->shadowMSR = data[1]; spin_unlock_irqrestore(&port_priv->lock, flags); kfree(data); /* set to default speed and 8bit word size */ status = qt2_set_port_config(serial->dev, device_port, DEFAULT_BAUD_RATE, UART_LCR_WLEN8); if (status < 0) { dev_err(&port->dev, "%s - initial setup failed (%i)\n", __func__, device_port); return status; } port_priv->device_port = (u8) device_port; if (tty) qt2_set_termios(tty, port, &tty->termios); return 0; } static void qt2_close(struct usb_serial_port *port) { struct usb_serial *serial; struct qt2_port_private *port_priv; int i; serial = port->serial; port_priv = usb_get_serial_port_data(port); usb_kill_urb(port_priv->write_urb); /* flush the port transmit buffer */ i = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0), QT2_FLUSH_DEVICE, 0x40, 1, port_priv->device_port, NULL, 0, QT2_USB_TIMEOUT); if (i < 0) dev_err(&port->dev, "%s - transmit buffer flush failed: %i\n", __func__, i); /* flush the port receive buffer */ i = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0), QT2_FLUSH_DEVICE, 0x40, 0, port_priv->device_port, NULL, 0, QT2_USB_TIMEOUT); if (i < 0) dev_err(&port->dev, "%s - receive buffer flush failed: %i\n", __func__, i); /* close the port */ i = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0), QT_OPEN_CLOSE_CHANNEL, 0x40, 0, port_priv->device_port, NULL, 0, QT2_USB_TIMEOUT); if (i < 0) dev_err(&port->dev, "%s - close port failed %i\n", __func__, i); } static void qt2_disconnect(struct usb_serial *serial) { struct qt2_serial_private *serial_priv = usb_get_serial_data(serial); usb_kill_urb(serial_priv->read_urb); } static int get_serial_info(struct usb_serial_port *port, struct serial_struct __user *retinfo) { struct serial_struct tmp; memset(&tmp, 0, sizeof(tmp)); tmp.line = port->minor; tmp.port = 0; tmp.irq = 0; tmp.xmit_fifo_size = port->bulk_out_size; tmp.baud_base = 9600; tmp.close_delay = 5*HZ; tmp.closing_wait = 30*HZ; if (copy_to_user(retinfo, &tmp, sizeof(*retinfo))) return -EFAULT; return 0; } static int qt2_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct usb_serial_port *port = tty->driver_data; switch (cmd) { case TIOCGSERIAL: return get_serial_info(port, (struct serial_struct __user *)arg); default: break; } return -ENOIOCTLCMD; } static void qt2_process_status(struct usb_serial_port *port, unsigned char *ch) { switch (*ch) { case QT2_LINE_STATUS: qt2_update_lsr(port, ch + 1); break; case QT2_MODEM_STATUS: qt2_update_msr(port, ch + 1); break; } } /* not needed, kept to document functionality */ static void qt2_process_xmit_empty(struct usb_serial_port *port, unsigned char *ch) { int bytes_written; bytes_written = (int)(*ch) + (int)(*(ch + 1) << 4); } /* not needed, kept to document functionality */ static void qt2_process_flush(struct usb_serial_port *port, unsigned char *ch) { return; } static void qt2_process_read_urb(struct urb *urb) { struct usb_serial *serial; struct qt2_serial_private *serial_priv; struct usb_serial_port *port; struct qt2_port_private *port_priv; bool escapeflag; unsigned char *ch; int i; unsigned char newport; int len = urb->actual_length; if (!len) return; ch = urb->transfer_buffer; serial = urb->context; serial_priv = usb_get_serial_data(serial); port = serial->port[serial_priv->current_port]; port_priv = usb_get_serial_port_data(port); for (i = 0; i < urb->actual_length; i++) { ch = (unsigned char *)urb->transfer_buffer + i; if ((i <= (len - 3)) && (*ch == QT2_CONTROL_BYTE) && (*(ch + 1) == QT2_CONTROL_BYTE)) { escapeflag = false; switch (*(ch + 2)) { case QT2_LINE_STATUS: case QT2_MODEM_STATUS: if (i > (len - 4)) { dev_warn(&port->dev, "%s - status message too short\n", __func__); break; } qt2_process_status(port, ch + 2); i += 3; escapeflag = true; break; case QT2_XMIT_HOLD: if (i > (len - 5)) { dev_warn(&port->dev, "%s - xmit_empty message too short\n", __func__); break; } qt2_process_xmit_empty(port, ch + 3); i += 4; escapeflag = true; break; case QT2_CHANGE_PORT: if (i > (len - 4)) { dev_warn(&port->dev, "%s - change_port message too short\n", __func__); break; } tty_flip_buffer_push(&port->port); newport = *(ch + 3); if (newport > serial->num_ports) { dev_err(&port->dev, "%s - port change to invalid port: %i\n", __func__, newport); break; } serial_priv->current_port = newport; port = serial->port[serial_priv->current_port]; port_priv = usb_get_serial_port_data(port); i += 3; escapeflag = true; break; case QT2_REC_FLUSH: case QT2_XMIT_FLUSH: qt2_process_flush(port, ch + 2); i += 2; escapeflag = true; break; case QT2_CONTROL_ESCAPE: tty_insert_flip_string(&port->port, ch, 2); i += 2; escapeflag = true; break; default: dev_warn(&port->dev, "%s - unsupported command %i\n", __func__, *(ch + 2)); break; } if (escapeflag) continue; } tty_insert_flip_char(&port->port, *ch, TTY_NORMAL); } tty_flip_buffer_push(&port->port); } static void qt2_write_bulk_callback(struct urb *urb) { struct usb_serial_port *port; struct qt2_port_private *port_priv; unsigned long flags; port = urb->context; port_priv = usb_get_serial_port_data(port); spin_lock_irqsave(&port_priv->urb_lock, flags); port_priv->urb_in_use = false; usb_serial_port_softint(port); spin_unlock_irqrestore(&port_priv->urb_lock, flags); } static void qt2_read_bulk_callback(struct urb *urb) { struct usb_serial *serial = urb->context; int status; if (urb->status) { dev_warn(&serial->dev->dev, "%s - non-zero urb status: %i\n", __func__, urb->status); return; } qt2_process_read_urb(urb); status = usb_submit_urb(urb, GFP_ATOMIC); if (status != 0) dev_err(&serial->dev->dev, "%s - resubmit read urb failed: %i\n", __func__, status); } static int qt2_setup_urbs(struct usb_serial *serial) { struct usb_serial_port *port0; struct qt2_serial_private *serial_priv; int status; port0 = serial->port[0]; serial_priv = usb_get_serial_data(serial); serial_priv->read_urb = usb_alloc_urb(0, GFP_KERNEL); if (!serial_priv->read_urb) return -ENOMEM; usb_fill_bulk_urb(serial_priv->read_urb, serial->dev, usb_rcvbulkpipe(serial->dev, port0->bulk_in_endpointAddress), serial_priv->read_buffer, QT2_READ_BUFFER_SIZE, qt2_read_bulk_callback, serial); status = usb_submit_urb(serial_priv->read_urb, GFP_KERNEL); if (status != 0) { dev_err(&serial->dev->dev, "%s - submit read urb failed %i\n", __func__, status); usb_free_urb(serial_priv->read_urb); return status; } return 0; } static int qt2_attach(struct usb_serial *serial) { struct qt2_serial_private *serial_priv; int status; /* power on unit */ status = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0), 0xc2, 0x40, 0x8000, 0, NULL, 0, QT2_USB_TIMEOUT); if (status < 0) { dev_err(&serial->dev->dev, "%s - failed to power on unit: %i\n", __func__, status); return status; } serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL); if (!serial_priv) return -ENOMEM; serial_priv->read_buffer = kmalloc(QT2_READ_BUFFER_SIZE, GFP_KERNEL); if (!serial_priv->read_buffer) { status = -ENOMEM; goto err_buf; } usb_set_serial_data(serial, serial_priv); status = qt2_setup_urbs(serial); if (status != 0) goto attach_failed; return 0; attach_failed: kfree(serial_priv->read_buffer); err_buf: kfree(serial_priv); return status; } static int qt2_port_probe(struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct qt2_port_private *port_priv; u8 bEndpointAddress; port_priv = kzalloc(sizeof(*port_priv), GFP_KERNEL); if (!port_priv) return -ENOMEM; spin_lock_init(&port_priv->lock); spin_lock_init(&port_priv->urb_lock); port_priv->port = port; port_priv->write_buffer = kmalloc(QT2_WRITE_BUFFER_SIZE, GFP_KERNEL); if (!port_priv->write_buffer) goto err_buf; port_priv->write_urb = usb_alloc_urb(0, GFP_KERNEL); if (!port_priv->write_urb) goto err_urb; bEndpointAddress = serial->port[0]->bulk_out_endpointAddress; usb_fill_bulk_urb(port_priv->write_urb, serial->dev, usb_sndbulkpipe(serial->dev, bEndpointAddress), port_priv->write_buffer, QT2_WRITE_BUFFER_SIZE, qt2_write_bulk_callback, port); usb_set_serial_port_data(port, port_priv); return 0; err_urb: kfree(port_priv->write_buffer); err_buf: kfree(port_priv); return -ENOMEM; } static int qt2_port_remove(struct usb_serial_port *port) { struct qt2_port_private *port_priv; port_priv = usb_get_serial_port_data(port); usb_free_urb(port_priv->write_urb); kfree(port_priv->write_buffer); kfree(port_priv); return 0; } static int qt2_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct usb_device *dev = port->serial->dev; struct qt2_port_private *port_priv = usb_get_serial_port_data(port); u8 *d; int r; d = kzalloc(2, GFP_KERNEL); if (!d) return -ENOMEM; r = qt2_getregister(dev, port_priv->device_port, UART_MCR, d); if (r < 0) goto mget_out; r = qt2_getregister(dev, port_priv->device_port, UART_MSR, d + 1); if (r < 0) goto mget_out; r = (d[0] & UART_MCR_DTR ? TIOCM_DTR : 0) | (d[0] & UART_MCR_RTS ? TIOCM_RTS : 0) | (d[1] & UART_MSR_CTS ? TIOCM_CTS : 0) | (d[1] & UART_MSR_DCD ? TIOCM_CAR : 0) | (d[1] & UART_MSR_RI ? TIOCM_RI : 0) | (d[1] & UART_MSR_DSR ? TIOCM_DSR : 0); mget_out: kfree(d); return r; } static int qt2_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct qt2_port_private *port_priv; port_priv = usb_get_serial_port_data(tty->driver_data); return update_mctrl(port_priv, set, clear); } static void qt2_break_ctl(struct tty_struct *tty, int break_state) { struct usb_serial_port *port = tty->driver_data; struct qt2_port_private *port_priv; int status; u16 val; port_priv = usb_get_serial_port_data(port); val = (break_state == -1) ? 1 : 0; status = qt2_control_msg(port->serial->dev, QT2_BREAK_CONTROL, val, port_priv->device_port); if (status < 0) dev_warn(&port->dev, "%s - failed to send control message: %i\n", __func__, status); } static void qt2_dtr_rts(struct usb_serial_port *port, int on) { struct usb_device *dev = port->serial->dev; struct qt2_port_private *port_priv = usb_get_serial_port_data(port); /* Disable flow control */ if (!on) { if (qt2_setregister(dev, port_priv->device_port, UART_MCR, 0) < 0) dev_warn(&port->dev, "error from flowcontrol urb\n"); } /* drop RTS and DTR */ if (on) update_mctrl(port_priv, TIOCM_DTR | TIOCM_RTS, 0); else update_mctrl(port_priv, 0, TIOCM_DTR | TIOCM_RTS); } static void qt2_update_msr(struct usb_serial_port *port, unsigned char *ch) { struct qt2_port_private *port_priv; u8 newMSR = (u8) *ch; unsigned long flags; /* May be called from qt2_process_read_urb() for an unbound port. */ port_priv = usb_get_serial_port_data(port); if (!port_priv) return; spin_lock_irqsave(&port_priv->lock, flags); port_priv->shadowMSR = newMSR; spin_unlock_irqrestore(&port_priv->lock, flags); if (newMSR & UART_MSR_ANY_DELTA) { /* update input line counters */ if (newMSR & UART_MSR_DCTS) port->icount.cts++; if (newMSR & UART_MSR_DDSR) port->icount.dsr++; if (newMSR & UART_MSR_DDCD) port->icount.dcd++; if (newMSR & UART_MSR_TERI) port->icount.rng++; wake_up_interruptible(&port->port.delta_msr_wait); } } static void qt2_update_lsr(struct usb_serial_port *port, unsigned char *ch) { struct qt2_port_private *port_priv; struct async_icount *icount; unsigned long flags; u8 newLSR = (u8) *ch; /* May be called from qt2_process_read_urb() for an unbound port. */ port_priv = usb_get_serial_port_data(port); if (!port_priv) return; if (newLSR & UART_LSR_BI) newLSR &= (u8) (UART_LSR_OE | UART_LSR_BI); spin_lock_irqsave(&port_priv->lock, flags); port_priv->shadowLSR = newLSR; spin_unlock_irqrestore(&port_priv->lock, flags); icount = &port->icount; if (newLSR & UART_LSR_BRK_ERROR_BITS) { if (newLSR & UART_LSR_BI) icount->brk++; if (newLSR & UART_LSR_OE) icount->overrun++; if (newLSR & UART_LSR_PE) icount->parity++; if (newLSR & UART_LSR_FE) icount->frame++; } } static int qt2_write_room(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct qt2_port_private *port_priv; unsigned long flags = 0; int r; port_priv = usb_get_serial_port_data(port); spin_lock_irqsave(&port_priv->urb_lock, flags); if (port_priv->urb_in_use) r = 0; else r = QT2_WRITE_BUFFER_SIZE - QT2_WRITE_CONTROL_SIZE; spin_unlock_irqrestore(&port_priv->urb_lock, flags); return r; } static int qt2_write(struct tty_struct *tty, struct usb_serial_port *port, const unsigned char *buf, int count) { struct qt2_port_private *port_priv; struct urb *write_urb; unsigned char *data; unsigned long flags; int status; int bytes_out = 0; port_priv = usb_get_serial_port_data(port); if (port_priv->write_urb == NULL) { dev_err(&port->dev, "%s - no output urb\n", __func__); return 0; } write_urb = port_priv->write_urb; count = min(count, QT2_WRITE_BUFFER_SIZE - QT2_WRITE_CONTROL_SIZE); data = write_urb->transfer_buffer; spin_lock_irqsave(&port_priv->urb_lock, flags); if (port_priv->urb_in_use) { dev_err(&port->dev, "qt2_write - urb is in use\n"); goto write_out; } *data++ = QT2_CONTROL_BYTE; *data++ = QT2_CONTROL_BYTE; *data++ = port_priv->device_port; put_unaligned_le16(count, data); data += 2; memcpy(data, buf, count); write_urb->transfer_buffer_length = count + QT2_WRITE_CONTROL_SIZE; status = usb_submit_urb(write_urb, GFP_ATOMIC); if (status == 0) { port_priv->urb_in_use = true; bytes_out += count; } write_out: spin_unlock_irqrestore(&port_priv->urb_lock, flags); return bytes_out; } static struct usb_serial_driver qt2_device = { .driver = { .owner = THIS_MODULE, .name = "quatech-serial", }, .description = DRIVER_DESC, .id_table = id_table, .open = qt2_open, .close = qt2_close, .write = qt2_write, .write_room = qt2_write_room, .calc_num_ports = qt2_calc_num_ports, .attach = qt2_attach, .release = qt2_release, .disconnect = qt2_disconnect, .port_probe = qt2_port_probe, .port_remove = qt2_port_remove, .dtr_rts = qt2_dtr_rts, .break_ctl = qt2_break_ctl, .tiocmget = qt2_tiocmget, .tiocmset = qt2_tiocmset, .tiocmiwait = usb_serial_generic_tiocmiwait, .get_icount = usb_serial_generic_get_icount, .ioctl = qt2_ioctl, .set_termios = qt2_set_termios, }; static struct usb_serial_driver *const serial_drivers[] = { &qt2_device, NULL }; module_usb_serial_driver(serial_drivers, id_table); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL v2");
/// Write the cache to json file pub fn write(&self, path: impl AsRef<Path>) -> Result<()> { let path = path.as_ref(); let file = fs::File::create(path)?; tracing::trace!("writing cache to json file"); serde_json::to_writer_pretty(file, self)?; tracing::trace!("cache file located: {}", path.display()); Ok(()) }
Two Years of Observations of the Io Plasma Torus by Juno Radio Occultations: Results From Perijoves 1 to 15 The Io plasma torus is the primary source for plasma in Jupiter’s magnetosphere. Observations of fundamental properties of the torus place valuable constraints on how the Io plasma torus behaves. Yet measurements of the density structure of the torus that precisely determine its location, total electron content, and scale height are rare. Here, we report measurements of four profiles of the total electron content through the torus by the Juno spacecraft. These profiles were acquired by radio occultation observations during Juno Perijoves 10, 11, 14, and 15. They complement previously reported profiles from Perijoves 1, 3, 6, and 8, for which an initial ad hoc correction has been verified by improved calibration at the ground station. Fits to each profile determined the location, peak total electron content, and scale height of two torus regions: the cold torus and the torus beyond 5.5 RJ. Measurements show the torus locations depend on longitude, but not time. The peak total electron content values vary with time but do not exhibit any clear dependence on longitude. The scale heights may depend on longitude and/or time. There is no apparent dependence of these properties on the Io phase angle. Future analysis of more observations by the Juno spacecraft will clarify the respective roles of longitude, time, and the Io phase angle in shaping the density structure of the Io plasma torus. Observations at previously sampled longitudes will be particularly valuable, as demonstrated here by Perijoves 8 and 15, which sampled the same longitude 1 year apart.
Seoul has complained to the World Trade Organization (WTO) that Beijing is retaliating against South Korean companies in response to the country deploying a US anti-missile defense system. Read more “The South Korean government appealed to the WTO service council to determine if Chinese measures on South Korean tourism and retail businesses conflicts with WTO regulations,” South Korean Trade Minister Joo Hyung-hwan said on Monday. The complaint isn't regarded as legal action, as it is more a request for the organization to check if China is upholding trade agreements fairly, according to an unnamed trade ministry official, as quoted by Reuters. Seoul claims Beijing has been taking punitive measures against South Korean corporations after the country agreed to deploy the Terminal High Altitude Area Defense (THAAD) system. THAAD is aimed at deterring missile launches from North Korea, according to the officials from South Korea and the US. However, China has raised concerns over the system, as its powerful radar may penetrate into its territory. Beijing also says it will do nothing to ease tension on the Korean peninsula. READ MORE:Chinese exports fall most since 2009 amid fears of US trade war The dispute may have an enormous impact on South Korea's economy as China is the country's biggest trading partner. As a result, China has ended group tours to South Korea, which has already seen a sharp decline in Chinese tourists in its shopping districts. US soldiers charged in S. Korea after $12mn worth of meth found in cereal boxes https://t.co/D3SggMMkTIpic.twitter.com/e5vV63yZUn — RT (@RT_com) March 17, 2017 Beijing has also shut nearly two dozen retail stores belonging to South Korea's Lotte Group and suspended almost all music concerts and shows starring Korean actors or singers. The Chinese authorities deny the restrictions are connected to the THAAD deployment. READ MORE: China opens WTO complaint about US & EU antidumping duties To mitigate the pressure on the country's businesses, Seoul has offered cheap loans and extended deadlines on existing debt. “The Chinese government may not admit they took retaliatory measures against the THAAD decision, but we have to point out the possibility. We are collecting evidence and will also deal with issues that South Korean companies are treated unfairly in China,” the minister stressed.
/* * 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.nifi.processors.standard; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import javax.net.ssl.SSLContext; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.processors.standard.util.TestInvokeHttpCommon; import org.apache.nifi.security.util.ClientAuth; import org.apache.nifi.security.util.KeyStoreUtils; import org.apache.nifi.security.util.SslContextFactory; import org.apache.nifi.security.util.StandardTlsConfiguration; import org.apache.nifi.security.util.TlsConfiguration; import org.apache.nifi.ssl.SSLContextService; import org.apache.nifi.util.TestRunners; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.mockito.Mockito; /** * Executes the same tests as TestInvokeHttp but with one-way SSL enabled. The Jetty server created for these tests * will not require client certificates and the client will not use keystore properties in the SSLContextService. */ public class TestInvokeHttpSSL extends TestInvokeHttpCommon { private static final String HTTP_CONNECT_TIMEOUT = "30 s"; private static final String HTTP_READ_TIMEOUT = "30 s"; protected static TlsConfiguration serverConfiguration; private static SSLContext truststoreSslContext; private static TlsConfiguration truststoreConfiguration; @BeforeClass public static void beforeClass() throws Exception { // generate new keystore and truststore serverConfiguration = KeyStoreUtils.createTlsConfigAndNewKeystoreTruststore(); truststoreConfiguration = new StandardTlsConfiguration( null, null, null, serverConfiguration.getTruststorePath(), serverConfiguration.getTruststorePassword(), serverConfiguration.getTruststoreType() ); final SSLContext serverContext = SslContextFactory.createSslContext(serverConfiguration); configureServer(serverContext, ClientAuth.NONE); truststoreSslContext = SslContextFactory.createSslContext(truststoreConfiguration); } @AfterClass public static void afterClass() throws Exception { if (serverConfiguration != null) { try { if (StringUtils.isNotBlank(serverConfiguration.getKeystorePath())) { Files.deleteIfExists(Paths.get(serverConfiguration.getKeystorePath())); } } catch (IOException e) { throw new IOException("There was an error deleting a keystore: " + e.getMessage(), e); } try { if (StringUtils.isNotBlank(serverConfiguration.getTruststorePath())) { Files.deleteIfExists(Paths.get(serverConfiguration.getTruststorePath())); } } catch (IOException e) { throw new IOException("There was an error deleting a truststore: " + e.getMessage(), e); } } } @Before public void before() throws Exception { final SSLContextService sslContextService = Mockito.mock(SSLContextService.class); final String serviceIdentifier = SSLContextService.class.getName(); Mockito.when(sslContextService.getIdentifier()).thenReturn(serviceIdentifier); Mockito.when(sslContextService.createContext()).thenReturn(getClientSslContext()); Mockito.when(sslContextService.createTlsConfiguration()).thenReturn(getClientConfiguration()); runner = TestRunners.newTestRunner(InvokeHTTP.class); runner.addControllerService(serviceIdentifier, sslContextService); runner.enableControllerService(sslContextService); runner.setProperty(InvokeHTTP.PROP_SSL_CONTEXT_SERVICE, serviceIdentifier); runner.setProperty(InvokeHTTP.PROP_CONNECT_TIMEOUT, HTTP_CONNECT_TIMEOUT); runner.setProperty(InvokeHTTP.PROP_READ_TIMEOUT, HTTP_READ_TIMEOUT); } protected SSLContext getClientSslContext() { return truststoreSslContext; } protected TlsConfiguration getClientConfiguration() { return truststoreConfiguration; } }
def is_connected(self): return ( self._proxy is not None and not self._proxy.is_closed() )
<reponame>yorgyetson/rattletrap module Rattletrap.Decode.AppliedDamageAttribute ( decodeAppliedDamageAttributeBits ) where import Rattletrap.Decode.Common import Rattletrap.Decode.Int32le import Rattletrap.Decode.Vector import Rattletrap.Decode.Word8le import Rattletrap.Type.AppliedDamageAttribute decodeAppliedDamageAttributeBits :: DecodeBits AppliedDamageAttribute decodeAppliedDamageAttributeBits = AppliedDamageAttribute <$> decodeWord8leBits <*> decodeVectorBits <*> decodeInt32leBits <*> decodeInt32leBits
<filename>bloxz-master/src/app/pages/EventsPage/index.ts import EventsPage from './EventsPage' export default EventsPage
<filename>ssh2ws/internal/h_comment.go package internal import ( "strings" "github.com/gin-gonic/gin" "github.com/libragen/felix/model" ) func CommentAll(c *gin.Context) { q := &model.CommentQ{} err := c.ShouldBindQuery(q) if handleError(c, err) { return } data, err := q.SearchAll() if handleError(c, err) { return } json200(c, data) } func CommentCreate(c *gin.Context) { uid, err := mWuserId(c) if handleError(c, err) { return } var mdl model.Comment err = c.ShouldBind(&mdl) if handleError(c, err) { return } mdl.Content = strings.TrimSpace(mdl.Content) if len(mdl.Content) == 0 { jsonError(c, "content can't be empty string") return } mdl.UserId = uid err = mdl.Create() if handleError(c, err) { return } jsonData(c, mdl) } func CommentAction(c *gin.Context) { id, err := parseParamID(c) if handleError(c, err) { return } uid, err := mWuserId(c) if handleError(c, err) { return } action := c.Param("action") err = (&model.Comment{}).Action(id, uid, action) if handleError(c, err) { return } jsonSuccess(c) } func CommentDelete(c *gin.Context) { var mdl model.Comment id, err := parseParamID(c) if handleError(c, err) { return } mdl.Id = id err = mdl.Delete() if handleError(c, err) { return } jsonSuccess(c) }
Russian Trade and Foreign Direct Investment Policy at the Crossroads This paper summarizes the estimates of what Russia will get from World Trade Organization accession and why. A key finding is the estimate that Russia will gain about $53 billion per year in the medium term from World Trade Organization accession and $177 billion per year in the long term, due largely to its own commitments to reform its own business services sectors. The paper summarizes the principal reform commitments that Russia has undertaken as part of its World Trade Organization accession negotiations, and compares them with those of other countries that have acceded to the World Trade Organization. It finds that the Russian commitments represent a liberal offer to the members of the World Trade Organization for admission, but they are typical of other transition countries that have acceded to the World Trade Organization. The authors discuss the outstanding issues in the Russian World Trade Organizaiton accession negotiations, and explain why Russian accession will result in the elimination of the Jackson-Vanik Amendment against Russia. They discuss Russian policies to attract foreign direct investment, including an assessment of the impact of the 2008 law on strategic sectors and the increased role of the state in the economy. Finally, the authors assess the importance of Russian accession to Russia and to the international trading community, and suggestions for most efficiently meeting the government’s diversification objective.
Frequency of Common Neurological Manifestations among Patients Presenting with Human Immunodeficiency Virus Positivity Background: Unsafe injection practices and injection drug use have been linked to multiple HIV outbreaks in Pakistan since 2003.HIV/AIDS has a wide range of clinical manifestations, and it affects a variety of organ systems. It is neuro-invasive, neurotropic and neurovirulent, and can directly induce nervous system diseases due to its preference for the nervous system.Objective: To determine the frequency of common neurological symptoms in patients who have tested positive for the human immunodeficiency virus.Material and Methods: This descriptive cross-sectional study was conducted on 131 patients for 6 months in the Department of Medicine, Lady Reading Hospital, Peshawar (9/7/2019 to 8/1/2020). Routine examinations, CSF cultures, monofilament tests, detailed histories, and ICD-9 criteria inspection were performed on all patients to detect the existence of common neurological symptoms such as TBM, cryptococcal meningitis, peripheral neuropathy, headache, seizures, and dementia. A pre-designed proforma was used to record the data. The data was analyzed us SPSS version 20. Results: The current study showed that 66% of the patients were men and 34% were women with a mean age of 36±10.51 years. Mean duration of the disease was 1±7.33 years. TBM (45%), cryptococcal meningitis (15%), peripheral neuropathy (16%), headache (26%), seizures (28%), and dementia were the most common neurological symptoms (5%).Conclusion: TBM (45%), cryptococcal meningitis (15%), peripheral neuropathy (16%), headache (26%), seizures (28%), and dementia (5%) were the most prevalent neurological symptoms in patients with human immunodeficiency virus positive, according to our findings.Key Words: Neurological manifestations, HIV /AIDS infection.
/** * Shows/Prints a String representation of the Value. */ @Override public void show() { }
def MAS(self, axes, masters=None): debug('GCSCommands.MAS(axes=%r, masters=%r)', axes, masters) axes, masters = getitemsvaluestuple(axes, masters) cmdstr = self.__getcmdstr('MAS', axes, masters) self.__msgs.send(cmdstr)
<gh_stars>0 import sys class DummyModule(object): dummy = None def import_all(): sys.modules["gpu"] = DummyModule sys.modules["runners"] = DummyModule sys.modules["loggers"] = DummyModule sys.modules["global_params"] = DummyModule def unimport_all(): del sys.modules["gpu"] del sys.modules["runners"] del sys.modules["loggers"] del sys.modules["global_params"] del sys.modules["catalearn"]
/* * Check to see if OBP Service is enabled in the application.properties */ public boolean isObpServiceEnabled () { if (ObpService.obpEnabled == null) { ObpService.obpEnabled = Boolean.parseBoolean(environment.getProperty(Constants.APP_OBP_ENABLED)); if (!getConnectionProperties()) { return false; } } return ObpService.obpEnabled; }
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD // // 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. #pragma once #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <stdbool.h> #include "soc/soc.h" #include "soc/sys_timer_reg.h" // All these functions get invoked either from ISR or HAL that linked to IRAM. // Always inline these functions even no gcc optimization is applied. /*******************counter*************************/ __attribute__((always_inline)) static inline void systimer_ll_enable_clock(void) { REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, SYS_TIMER_CLK_EN); } __attribute__((always_inline)) static inline void systimer_ll_enable_counter(uint32_t counter_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << (30 - counter_id)); } __attribute__((always_inline)) static inline void systimer_ll_counter_can_stall_by_cpu(uint32_t counter_id, uint32_t cpu_id, bool can) { if (can) { REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << ((28 - counter_id * 2) - cpu_id)); } else { REG_CLR_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << ((28 - counter_id * 2) - cpu_id)); } } __attribute__((always_inline)) static inline void systimer_ll_counter_snapshot(uint32_t counter_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_UNIT0_OP_REG + 4 * counter_id, 1 << 30); } __attribute__((always_inline)) static inline bool systimer_ll_is_counter_value_valid(uint32_t counter_id) { return REG_GET_BIT(SYS_TIMER_SYSTIMER_UNIT0_OP_REG + 4 * counter_id, 1 << 29); } __attribute__((always_inline)) static inline void systimer_ll_set_counter_value(uint32_t counter_id, uint64_t value) { REG_WRITE(SYS_TIMER_SYSTIMER_UNIT0_LOAD_LO_REG + 8 * counter_id, value & 0xFFFFFFFF); REG_WRITE(SYS_TIMER_SYSTIMER_UNIT0_LOAD_HI_REG, (value >> 32) & 0xFFFFF); } __attribute__((always_inline)) static inline uint32_t systimer_ll_get_counter_value_low(uint32_t counter_id) { return REG_READ(SYS_TIMER_SYSTIMER_UNIT0_VALUE_LO_REG + 8 * counter_id); } __attribute__((always_inline)) static inline uint32_t systimer_ll_get_counter_value_high(uint32_t counter_id) { return REG_READ(SYS_TIMER_SYSTIMER_UNIT0_VALUE_HI_REG + 8 * counter_id); } __attribute__((always_inline)) static inline void systimer_ll_apply_counter_value(uint32_t counter_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_UNIT0_LOAD_REG + 4 * counter_id, SYS_TIMER_TIMER_UNIT0_LOAD); } /*******************alarm*************************/ __attribute__((always_inline)) static inline void systimer_ll_set_alarm_target(uint32_t alarm_id, uint64_t value) { REG_WRITE(SYS_TIMER_SYSTIMER_TARGET0_LO_REG + alarm_id * 8, value & 0xFFFFFFFF); REG_WRITE(SYS_TIMER_SYSTIMER_TARGET0_HI_REG + alarm_id * 8, (value >> 32) & 0xFFFFF); } __attribute__((always_inline)) static inline uint64_t systimer_ll_get_alarm_target(uint32_t alarm_id) { return ((uint64_t) REG_READ(SYS_TIMER_SYSTIMER_TARGET0_HI_REG + alarm_id * 8) << 32) \ | REG_READ(SYS_TIMER_SYSTIMER_TARGET0_LO_REG + alarm_id * 8); } __attribute__((always_inline)) static inline void systimer_ll_connect_alarm_counter(uint32_t alarm_id, uint32_t counter_id) { REG_SET_FIELD(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + 4 * alarm_id, SYS_TIMER_TARGET0_TIMER_UNIT_SEL, counter_id); } __attribute__((always_inline)) static inline void systimer_ll_enable_alarm_oneshot(uint32_t alarm_id) { REG_CLR_BIT(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + alarm_id * 4, SYS_TIMER_TARGET0_PERIOD_MODE); } __attribute__((always_inline)) static inline void systimer_ll_enable_alarm_period(uint32_t alarm_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + alarm_id * 4, SYS_TIMER_TARGET0_PERIOD_MODE); } __attribute__((always_inline)) static inline void systimer_ll_set_alarm_period(uint32_t alarm_id, uint32_t period) { REG_SET_FIELD(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + alarm_id * 4, SYS_TIMER_TARGET0_PERIOD, period); } __attribute__((always_inline)) static inline void systimer_ll_apply_alarm_value(uint32_t alarm_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_COMP0_LOAD_REG + alarm_id * 4, SYS_TIMER_TIMER_COMP0_LOAD); } __attribute__((always_inline)) static inline void systimer_ll_disable_alarm(uint32_t alarm_id) { REG_CLR_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << (24 - alarm_id)); } __attribute__((always_inline)) static inline void systimer_ll_enable_alarm(uint32_t alarm_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << (24 - alarm_id)); } /*******************interrupt*************************/ __attribute__((always_inline)) static inline void systimer_ll_enable_alarm_int(uint32_t alarm_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_INT_ENA_REG, 1 << alarm_id); } __attribute__((always_inline)) static inline void systimer_ll_disable_alarm_int(uint32_t alarm_id) { REG_CLR_BIT(SYS_TIMER_SYSTIMER_INT_ENA_REG, 1 << alarm_id); } __attribute__((always_inline)) static inline bool systimer_ll_is_alarm_int_fired(uint32_t alarm_id) { return REG_GET_BIT(SYS_TIMER_SYSTIMER_INT_RAW_REG, 1 << alarm_id); } __attribute__((always_inline)) static inline void systimer_ll_clear_alarm_int(uint32_t alarm_id) { REG_SET_BIT(SYS_TIMER_SYSTIMER_INT_CLR_REG, 1 << alarm_id); } #ifdef __cplusplus } #endif
<reponame>uos/hatsdf_slam /** * @file bridge_base.h * @author <NAME> * @date 2020-09-29 */ #pragma once #include <string> #include <iostream> #include <ros/node_handle.h> #include <comm/receiver.h> #include <util/process_thread.h> #include <chrono> namespace fastsense::bridge { /** * @brief The BridgeBase class is the base of all communication between Trenz board and an Ubuntu host * * Each class that inherits from BridgeBase implements each a receiver, and a publisher * - The receiver receives data from type T and PORT via zeromq * - The publisher transforms the data received via zeromq into a ROS message of type P and publishes as soon as it becomes available * * @tparam T data type that's sent via zeromq * @tparam P type of ROS publisher * @tparam PORT port that zeromq should listen */ template <typename T, typename P, int PORT> class BridgeBase { private: /// Receiver of data from board comm::Receiver<T> receiver_; /// ros publisher of matching ROS message ros::Publisher pub_; public: /** * @brief Destroy the Bridge Base object */ virtual ~BridgeBase() = default; /** * @brief Perform on bridge "iteration": wait for data, convert it to a ROS message, publish */ virtual void run() = 0; /** * @brief Return received msg * * @return const T& received msg */ inline const T& msg() const { return msg_; } /** * @brief Return publisher * * @return ros::Publisher& reference to publisher */ inline const ros::Publisher& pub() const { return pub_; } protected: /** * @brief Construct a new Bridge Base object * * @param n ROS node handle * @param topic ROS topic that will be published to * @param board_addr board addr that will be listened to by zeromq * @param msg_buffer_size ROS msg buffer size * @param timeout (ms) length of time to wait for message before continuing */ inline BridgeBase(ros::NodeHandle& n, const std::string& topic, const std::string& board_addr, size_t msg_buffer_size = 1000, std::chrono::milliseconds timeout = 100) : receiver_{board_addr, PORT, timeout}, pub_{n.advertise<P>(topic, msg_buffer_size)}, msg_{}, n{n} { } /// msg of type T that is received via zeromq T msg_; /// NodeHandle ros::NodeHandle& n; /** * Receive a message (non blocking) * @return true if message was returned within timeout * @return false if there was no message within timeout period */ virtual bool receive() final { return receiver_.receive(msg_); } /** * @brief Pure virtual convert function: convert T to ROS message */ virtual void convert() = 0; /** * @brief Pure virtual publish function: publish result from convert() */ virtual void publish() = 0; }; }
// RowCount implements Plan RowCount interface. func (p *basePlan) RowCount() float64 { if p.limit == 0 { return p.rowCount } return math.Min(p.rowCount, p.limit) }
/** * Executes a program that adds 2 values in the AS400 using the connector. * @throws Exception */ @Test(groups = {"wso2.esb"}, description = "Check if number addition test works.") public void callAdditionProgramTestCase() throws Exception { SOAPEnvelope soapRequest = sendSOAPRequest(proxyUrl, "invoker.xml"); OMElement xpcmlElement = soapRequest.getBody().getFirstElement(); Assert.assertEquals(xpcmlElement.toString(), "<xpcml version=\"6.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:noNamespaceSchemaLocation='xpcml.xsd'><program name=\"Addition\" " + "path=\"/QSYS.LIB/%LIBL%.LIB/ADDITION.PGM\">" + "<parameterList>" + "<intParm name=\"inputValue1\" passDirection=\"in\">5</intParm>" + "<intParm name=\"inputValue2\" passDirection=\"in\">10</intParm>" + "<intParm name=\"outputValue\" passDirection=\"out\">15<intParm>" + "</parameterList>" + "</program></xpcml>", "Output value does not match."); }
<reponame>zfdang/zSMTH // // ContentEditViewController.h // zSMTH // // Created by <NAME> on 2015-4-12. // Copyright (c) 2015 Zhengfa. All rights reserved. // #import <UIKit/UIKit.h> #import "ExtendedUIViewController.h" typedef enum { ACTION_NEW_POST = 0, ACTION_REPLY_POST, ACTION_NEW_MAIL, ACTION_REPLY_MAIL, ACTION_REPLY_POST_TO_MAIL } ActionType; @interface ContentEditViewController : ExtendedUIViewController @property (strong, nonatomic) NSString *engName; @property (strong, nonatomic) NSString *recipient; @property (strong, nonatomic) NSArray *mAttachments; @property (weak, nonatomic) IBOutlet UITextField *txtSubject; @property (weak, nonatomic) IBOutlet UITextField *txtAttach; @property (weak, nonatomic) IBOutlet UITextView *txtContent; @property (weak, nonatomic) IBOutlet UILabel *txtSummary; @property (weak, nonatomic) IBOutlet UITextField *txtAction; @property (weak, nonatomic) IBOutlet UIButton *btAttachment; @property (nonatomic) ActionType actionType; - (IBAction)editAttachments:(id)sender; - (IBAction)cancel:(id)sender; - (IBAction)submit:(id)sender; - (void) setOrigPostInfo:(long)postID subject:(NSString*)origSubject author:(NSString*) author content:(NSString*)origContent; - (void) setOrigMailInfo:(int)position recipient:(NSString*)recipient subject:(NSString*)origSubject content:(NSString*)origContent; @end
<gh_stars>1-10 #ifndef LOC_CALLER_HXX_ #define LOC_CALLER_HXX_ #include <opengm/opengm.hxx> #include <opengm/inference/loc.hxx> #include "inference_caller_base.hxx" #include "../argument/argument.hxx" namespace opengm { namespace interface { template <class IO, class GM, class ACC> class LOCCaller : public InferenceCallerBase<IO, GM, ACC> { protected: using InferenceCallerBase<IO, GM, ACC>::addArgument; using InferenceCallerBase<IO, GM, ACC>::io_; using InferenceCallerBase<IO, GM, ACC>::infer; virtual void runImpl(GM& model, StringArgument<>& outputfile, const bool verbose); typedef LOC<GM, ACC> L_O_C; typedef typename L_O_C::VerboseVisitorType VerboseVisitorType; typedef typename L_O_C::EmptyVisitorType EmptyVisitorType; typedef typename L_O_C::TimingVisitorType TimingVisitorType; typename L_O_C::Parameter locParameter_; public: const static std::string name_; LOCCaller(IO& ioIn); }; template <class IO, class GM, class ACC> inline LOCCaller<IO, GM, ACC>::LOCCaller(IO& ioIn) : InferenceCallerBase<IO, GM, ACC>(name_, "detailed description of LOC caller...", ioIn) { addArgument(DoubleArgument<>(locParameter_.phi_, "", "phi", "phi", locParameter_.phi_)); addArgument(Size_TArgument<>(locParameter_.maxRadius_, "", "maxr", "maximum radius", locParameter_.maxRadius_)); addArgument(Size_TArgument<>(locParameter_.maxIterations_, "", "maxIt", "Maximum number of iterations.", locParameter_.maxIterations_)); addArgument(VectorArgument<std::vector<typename L_O_C::LabelType> >(locParameter_.startPoint_, "x0", "startingpoint", "location of the file containing the values for the starting point", false)); } template <class IO, class GM, class ACC> inline void LOCCaller<IO, GM, ACC>::runImpl(GM& model, StringArgument<>& outputfile, const bool verbose) { std::cout << "running LOC caller" << std::endl; this-> template infer<L_O_C, TimingVisitorType, typename L_O_C::Parameter>(model, outputfile, verbose, locParameter_); /* L_O_C loc(model, locParameter_); std::vector<size_t> states; std::cout << "Inferring!" << std::endl; if(!(loc.infer() == NORMAL)) { std::string error("LOC did not solve the problem."); io_.errorStream() << error << std::endl; throw RuntimeError(error); } std::cout << "writing states in vector!" << std::endl; if(!(loc.arg(states) == NORMAL)) { std::string error("LOC could not return optimal argument."); io_.errorStream() << error << std::endl; throw RuntimeError(error); } io_.read(outputfile); io_.storeVector(outputfile.getValue(), states);*/ } template <class IO, class GM, class ACC> const std::string LOCCaller<IO, GM, ACC>::name_ = "LOC"; } // namespace interface } // namespace opengm #endif /* LOC_CALLER_HXX_ */
def post_analyze(analyze_id, part_number, workspace): LOG.info('Post Analyze Step') file_path = os.path.join(workspace, analyze_id) source_file_without_extension = 'source_' + str(part_number) analyze_dir_path = os.path.join(file_path, source_file_without_extension) output_dir_path = os.path.join(analyze_dir_path, 'output') analyze_output_zip_file_path = os.path.join(file_path, 'output.zip') with zipfile.ZipFile(analyze_output_zip_file_path, 'a') as output: for root, dirs, files in os.walk(output_dir_path): for file in files: output.write(os.path.join(root, file)) REDIS_DATABASE.hincrby(analyze_id, 'completed_parts', 1) parts = REDIS_DATABASE.hget(analyze_id, 'parts').decode('utf-8') completed_parts = REDIS_DATABASE.hget( analyze_id, 'completed_parts').decode('utf-8') if parts == completed_parts: REDIS_DATABASE.hset(analyze_id, 'state', AnalyzeStatus.ANALYZE_COMPLETED.name) LOG.info('Analyze %s is completed.', analyze_id)
package diaceutics.selenium.pageobject.forms; import diaceutics.selenium.pageobject.BaseForm; import org.openqa.selenium.By; public class UserEditIdentityForm extends BaseForm { public UserEditIdentityForm() { super(By.xpath("//h2[.='Identity']"), "Identity"); } }
// ViewInertiaScroller.Listener implementation for image movement and scaling @Override public boolean move(float xd, float yd) { float nextX = centerX + xd / scale; centerX = Math.min(Math.max(0, nextX), imageW); float nextY = centerY + yd / scale; centerY = Math.min(Math.max(0, nextY), imageH); invalidate(); annotations.invalidate(); return (0 <= nextX && nextX <= imageW && 0 <= nextY && nextY <= imageH); }
<gh_stars>1-10 CMD_READ_MEM = 0x00 CMD_WRITE_MEM = 0x01 CMD_PROGRAM_FLASH = 0x10 CMD_ERASE_FLASH = 0x11 CMD_ENTER_DEBUG = 0x80 CMD_EXIT_DEBUG = 0x81 CMD_REVISION = 0xFE REQUEST_SYNC_BYTE = 0x55 RESPONSE_SYNC_BYTE = 0xAA
string = raw_input() s = "01235689" s2 = [4, 44, 444, 7, 77, 47, 477, 474, 74] flag = True for x in s2: if int(string) % x == 0: print "YES" exit(0) for x in string: if x in s: print "NO" exit() print "YES" input()
/** * @file * @brief HAL UDP API * @internal * * @copyright (C) 2020 <NAME>. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, * INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. MELEXIS N.V. SHALL NOT IN ANY CIRCUMSTANCES, * BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * * @endinternal * * @defgroup spi_hal_api_udp_abs SPI UDP abstraction layer interface * @ingroup spi_driver * * @details This component provides a common API interface for UDP control configuration, reagardless the platform used. * For more information refer to platform-specific component. This API assumes working with the continuous mode component. */ #ifndef SPI_DRV_HAL_UDP_H #define SPI_DRV_HAL_UDP_H /** @{*/ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include "cont_mode_lib.h" /** UDP destination port for socket's packets */ #define DEST_PORT 8541 /** Provides the API for UDP's callback function used to transfer the data via UDP * @param[in] chipData the pointer used to transfer the data from the driver into the callback function * * @note This function is overloaded by the UDP-component's implementation */ ContModeCbRet_t spiDriver_UdpCallback(spiDriver_ChipData_t* chipData); /** Provides initialization functions called from continuous mode initialization * * @param[in] dest_port Destination port for the UDP-packets. If this parameter is 0, default value ::DEST_PORT is used. * @return callback's result of an operation, whether the flow should be continued. * * @note This function is overloaded by the UDP-component's implementation */ void spiDriver_InitUdpCallback(uint16_t dest_port); #ifdef __cplusplus } #endif /** @}*/ #endif /* SPI_DRV_HAL_UDP_H */
/** * Generate a name based on a file position */ public class PointerNameGenerator { private static final int START_VALUE = 90; private static final int INCREMENT = 1; private transient int position; private final transient Map<Long, String> contents = new HashMap<>(); /** * Create a new {@link PointerNameGenerator}, starting at the {@value #START_VALUE} value. */ PointerNameGenerator() { this(START_VALUE); } /** * Create a new {@link PointerNameGenerator}, with names starting at the given value. * @param startValue the starting values for names. */ public PointerNameGenerator(final int startValue) { this.position = startValue; } /** * Creates the next name * @return */ private String createName() { int nameID = position; position += INCREMENT; return "#" + nameID; } /** * Get the name associated with a file position * @param position * @return */ public String get(final long position) { if(contents.containsKey(position)) { return contents.get(position); } String name = createName(); contents.put(position, name); return name; } }
#include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "DataFormats/Common/interface/View.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/HepMCCandidate/interface/GenParticleFwd.h" #include "DataFormats/JetReco/interface/GenJet.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "PhysicsTools/JetMCUtils/interface/JetMCTag.h" #include "DataFormats/TauReco/interface/PFTau.h" #include "DataFormats/Math/interface/deltaR.h" #include "CommonTools/Utils/interface/PtComparator.h" #include <vector> #include <iostream> class GenVisTauProducer : public edm::global::EDProducer<> { public: GenVisTauProducer(const edm::ParameterSet& params) : src_(consumes<reco::GenJetCollection>(params.getParameter<edm::InputTag>("src"))), srcGenParticles_(consumes<reco::GenParticleCollection>(params.getParameter<edm::InputTag>("srcGenParticles"))), pTComparator_() { produces<reco::GenParticleCollection>(); } ~GenVisTauProducer() override {} void produce(edm::StreamID id, edm::Event& evt, const edm::EventSetup& es) const override { edm::Handle<reco::GenJetCollection> genTauJets; evt.getByToken(src_, genTauJets); edm::Handle<reco::GenParticleCollection> genParticles; evt.getByToken(srcGenParticles_, genParticles); size_t numGenParticles = genParticles->size(); auto genVisTaus = std::make_unique<reco::GenParticleCollection>(); for (const auto& genTauJet : *genTauJets) { std::string decayMode_string = JetMCTagUtils::genTauDecayMode(genTauJet); // CV: store hadronic tau decays only if (decayMode_string == "electron" || decayMode_string == "muon") continue; int decayMode = reco::PFTau::kNull; if (decayMode_string == "oneProng0Pi0") decayMode = reco::PFTau::kOneProng0PiZero; else if (decayMode_string == "oneProng1Pi0") decayMode = reco::PFTau::kOneProng1PiZero; else if (decayMode_string == "oneProng2Pi0") decayMode = reco::PFTau::kOneProng2PiZero; else if (decayMode_string == "threeProng0Pi0") decayMode = reco::PFTau::kThreeProng0PiZero; else if (decayMode_string == "threeProng1Pi0") decayMode = reco::PFTau::kThreeProng1PiZero; else decayMode = reco::PFTau::kRareDecayMode; int pdgId = (genTauJet.charge() > 0) ? -15 : +15; // CV: store decayMode in status flag of GenParticle object reco::GenParticle genVisTau(genTauJet.charge(), genTauJet.p4(), genTauJet.vertex(), pdgId, decayMode, true); // CV: find tau lepton "mother" particle for (size_t idxGenParticle = 0; idxGenParticle < numGenParticles; ++idxGenParticle) { const reco::GenParticle& genTau = (*genParticles)[idxGenParticle]; if (abs(genTau.pdgId()) == 15 && genTau.status() == 2) { reco::Candidate::LorentzVector daughterVisP4; for (const reco::GenParticleRef& daughter : genTau.daughterRefVector()) { int abs_pdgId = abs(daughter->pdgId()); // CV: skip neutrinos if (abs_pdgId == 12 || abs_pdgId == 14 || abs_pdgId == 16) continue; daughterVisP4 += daughter->p4(); } double dR2 = deltaR2(daughterVisP4, genVisTau); if (dR2 < 1.e-4) { genVisTau.addMother(reco::GenParticleRef(genParticles, idxGenParticle)); break; } } } genVisTaus->push_back(genVisTau); } std::sort(genVisTaus->begin(), genVisTaus->end(), pTComparator_); evt.put(std::move(genVisTaus)); } static void fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("src")->setComment("collection of visible gen taus (as reco::GenJetCollection)"); desc.add<edm::InputTag>("srcGenParticles")->setComment("collections of gen particles"); descriptions.add("genVisTaus", desc); } private: const edm::EDGetTokenT<reco::GenJetCollection> src_; const edm::EDGetTokenT<reco::GenParticleCollection> srcGenParticles_; const GreaterByPt<reco::GenParticle> pTComparator_; }; #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(GenVisTauProducer);
Tottenham are set to approach Inter Milan over Marcelo Brozovic after he was put up for sale, according to TransferMarketWeb. The website claims that the central midfield kingpin is definitely on Spurs’ shopping list and they should be able to get him for a fee between £11-£12million. TransferMarketWeb report that Brozovic is now more affordable than when Tottenham were previously interested, and that Spurs are expected to make a move soon. Brozovic has made 16 appearances across all competitions for Inter Milan this season, scoring three goals and grabbing an assist. Despite being up for sale, the midfielder is contracted to the Italian giants until 2021, having signed a contract extension in 2016. Good move for Tottenham? The midfielder is versatile and can be utilised anywhere in midfield, which would provide Spurs with fantastic cover for injuries. Injuries have been a burden to Tottenham this season, and Mauricio Pochettino has certainly learnt that he needs a bigger squad available to him in order to compete in several competitions. Brozovic is an ideal signing to Spurs’ squad, not just because of his versatility, but also because he has some Champions League experience from time at Dinamo Zagreb. This Is Futbol rating: 8/10 Likely to happen? With the midfielder being put up for sale by Inter Milan for a bargain price considering his talents, this could definitely happen. Tottenham have consistently been linked with the midfielder throughout the years and with him now available at a reasonable price it removes any stumbling block that was stopping a deal from happening. This Is Futbol rating: 7/10
// Add adds the value of the passed datum to the sum. func (a *intSumAggregate) Add(datum Datum) { if datum == DNull { return } t := int64(*datum.(*DInt)) if t != 0 { if !a.large && ((t < 0 && a.intSum < math.MinInt64-t) || (t > 0 && a.intSum > math.MaxInt64-t)) { a.large = true a.decSum.SetUnscaled(a.intSum) } if a.large { a.tmpDec.SetUnscaled(t) a.decSum.Add(&a.decSum.Dec, &a.tmpDec) } else { a.intSum += t } } a.seenNonNull = true }
<reponame>rgxcp/JavaBelajar public class Welcome { public static void main(String[] args) { System.out.println("SELAMAT <NAME> DI KELAS 3KA17"); } }
A comparison of two anesthesia methods for the surgical removal of maxillary third molars: PSA nerve block technique vs. local infiltration technique Objectives: The purpose of this study was to compare the effect of PSA block injection with infiltration technique regarding local anesthesia for surgical extraction of upper third molar. Material and Methods: A prospective, intra individual, single-blind randomized controlled trial was designed to study the severity of pain during injection and after surgical extraction of the bilaterally and symmetrically similar upper third molar in a total of 53 patients, in addition to evaluating the need to repeat the injection and requirement of post operative anti-inflammatory tablets. Result: Although the average pain score for all studied times in PSA side was lower than the average pain score in infiltration technique, repeated statistical measures demonstrated that no significant pain reduction occurred in the two techniques. Conclusion: The both tested methods have the same statistic equivalence for the surgical extraction of maxillary third molars. Key words:Surgical extraction, maxillary third molars, PSA block, infiltration. Introduction Surgical extraction of impacted teeth can be either uneventful and uncomplicated, or difficult, with considerable postoperative pain. (1) Maxillary third molars are frequently amenable to removal surgically under local anesthesia (2) .Fear of a dental injection and postoperative pain can prevent patients from seeking dental care and often this fear is related to the feeling of needle pe-netration and pain during the injection (3). Local anesthesia plays an essential role in making dental treatment comfortable .Also it has been called the most important drug in dentistry. Conversely, local anesthetic injections are seen by many patients as stressful and a reason for avoiding dental treatment (4). A range of local anesthetic drugs have been used in dentistry among which lidocaine is the most popular e13 J Clin Exp Dent. 2014;6(1):e12-6. Two anesthesia methods for the surgical removal of maxillary third molars (5). The common techniques for providing anesthesia in maxillary molars include posterior superior alveolar (PSA) nerve block and infiltration anesthesia (6). The majority of the recently published articles evaluate the anesthetic efficacy of the PSA nerve block and maxillary infiltrations either in inflamed pulps or in the normal tooth extraction (6)(7)(8). To the knowledge of the author, there is no published data evaluated and compared in terms of the severity of pain during injection and after the surgical extraction of upper third molar, and the need to repeat the injection and requirement of antiinflammatory tablets. (10). In all the cases there is more than 2 mm of bone between the impacted maxillary 3rd molar and the maxillary sinus. -Procedures Each of the 53 patients was scheduled to undergo bilaterally and symmetrically identical upper third molar surgical extraction (and thus presenting similar surgical extraction difficulty).The two extractions were performed in two separate sessions approximately 4 weeks apart to allow for total recovery from the first one. In each patient, the choice of which anesthetic techniques were going to be administered, the PSA block technique and on the contra lateral the infiltration technique, was made randomly. The palatal injection was combined to both techniques. A topical anesthetic gel 5% lidocaine (Xylonor Gel, Septodent, U.K.) was placed with a cotton tip applicator. After reaching the target area, aspiration was performed several times during the administration of the injection using standard dental aspirating syringe (KlS, Martin, Germany) fitted with a 25-gauge, long, 0.40×35mm needle (Sterinject, Dentsply, France). The technique of the PSA block was identical to Malamed's text (11). In the infiltration technique, after two minutes of buccal infiltration, a palatal infiltration was administered. A 1.8 mL of 2% lidocaine hydrochloride with 1:80,000 adrenaline solution (Lingospan special, Septodent, France) was deposited at a rate of 1 mL/min. A second or third injection was given to the patient who has experienced an additional pain. After 5 minutes of the injection of a determined dose of local anesthesia, the surgical procedure was performed. The surgical procedure was similar in all cases and was performed by the same surgeon using a standardized technique under local anesthesia without any kind of sedation (oral, nasal or venous); full envelop mucoperiosteal flaps were elevated prior to the removal of the third molars. Alveolotomy was carried out using a bur under a concomitant continuous spray of sterile saline solution; the flaps are sutured with a 4-0 silk suture. After surgery, all of the patients received an oral nonsteroidal anti-inflammatory drug (600 milligrams of Ibuprofen every 4-6 hours for four days) and topical chlorhexidine digluconate for seven days .The suture material was removed after one week. All surgical details were noted in a pre-made questionnaire -Pain Measurement Preoperative pain assessed by a single blind professional operator was different from the surgeon who performed the surgery, repeating each record three times on each case: during the injection, at the end of operation and after 15 minutes from the end of operation, using a 170mm Heft-Parker visual analog scale (VAS; Fig. 1). Before being administered local anesthetic agent, each patient was given a thorough explanation of the VAS which was divided into 4 categories: no pain corresponded to 0 mm; mild pain was defined as greater than 0 mm and less than or equal to 54 mm and included the descriptors of faint, weak, and mild pain; moderate pain was defined as greater than 54 mm and less than 114 mm; severe pain was defined as equal to or greater than 114 mm and included the descriptors of strong, intense, and maximum possible. There is no strong or intense pain recorded at the end of operation. -Statistical Analysis Statistics was performed using the SPSS for Windows (version 13.0, SPSS Inc, Chicago, IL) statistical software package. The pain VAS scores were analyzed by analysis of variance (ANOVA) for repeated measures. X2 were used for significance of age, sex and operation time on the severity of pain .Probability less than 0.05 was considered statistically significant. Results In a total of 53 patients participated in this study, there was no significant correlation between age and sex with the intensity of pain. The average duration of the surgical procedure starting from the flap reflection to the end of suturing on the PSA side, was 7.83± (4.18) minutes (range, 3-11 minutes); while on the infiltration side, it was 8.47± (4.38) minutes (range, 4-11 minutes), the difference was statistically significant F=21.701 (P<0.01) with intensity of pain. Evaluations at injection showed a 1 (1.8%) positive aspiration with PSA block and without any positive aspiration with infiltration technique. Although the average pain score for all studied times in PSA side, was lower than the average pain score in infiltration technique, repeated-measures ANOVA demonstrated no significant difference in pain reduction between the two techniques (P > 0.05, Table 1, Fig. 2). We did not note any significant differences between the PSA side and the infiltrations side in terms of needing for a second or third injection, P=0.096 but little increase in the frequency of repeating injection on the infiltration side was observed. The protocol of study also involved assessing NSAID intake in the first three hours. The mean consumption of ibuprofen in number of tablets is noted in Fig. 4. The difference was statistically significant between two te-chniques at 1, 2 and 3hour intervals post-operatively F= 5.480. Significance =0.020 (p<0.05, Fig. 3).the number of ibuprofen consumption was less in PSA group this because of long duration effect of this technique. Discussion The improvements in agents and techniques for local anesthesia improve the patients' perceptions, comfort and acceptance during dental treatment. The pain control is an important factor for reducing the fear and anxiety associated with dental procedures (12) for that the choice of local anesthetic techniques may influence the amount of discomfort produced during intraoral injection in order to propose an easy and safe method to anesthetize the dentition and surrounding hard and soft tissues during management of surgical extraction (13). Maxillary infiltration anesthesia is a common method to anesthetize maxillary teeth (14). Also the PSA nerve block has been advocated to anesthetize the first, second, and third molar teeth (11). In the current study, the success of maxillary PSA block and infiltration technique have been evaluated using the VAS while in the previous studies (15-17) they tried to use the electric pulp tester. According to the findings of the present comparative study, it can be concluded that there was no difference in the pain experienced by patient using either PSA nerve block technique or infiltrations technique,in surgical extraction of maxillary third molars during the injection or in the post surgical periods (Table 1, Fig. 2). This came in line with the Padhye et al. study (7) as well as the Aggarwal et al's study (8).But in the present study, analyzed parameters were related to third molar surgical extraction while the previous mentioned two studies related to conventional normal tooth extraction (7) and irreversible pulpitis (8). The strengths of this study were the consistency of only one surgeon and intra individual evaluation. There was no significant difference (P > .05) between the two sides Table 1. Pain intensity in two sides at different times. In conclusion, the statistical analysis of the study results has confirmed clinical equivalence for the surgical extraction of maxillary third molars with PSA nerve block and infiltration technique with the mean advantages of PSA that Minimum number of necessary injections but the risk of a potential complication also must be considered whenever the PSA block is used. There were positive blood aspirations during the PSA in the observation of Pfeil et al. (6), but our resulting data show that the results of this study are that there is positive percentage of 1.8 for PSA and without any positive aspiration in the filtration side. This finding was recorded by others (7,11) in addition to the same finding of non significant differences between the PSA side and the infiltrations side in terms of needing for a second or third injection (Fig. 3). Preventive strategies for postoperative management of pain and inflammation are based on the known ability of NSAIDs to block the arachidonic acid cascade but concurrent use of NSAIDs should be avoided when possible because of the risk of producing gastrointestinal tract hemorrhage (18). In this study the mean consumption of ibuprofen tablet was highly correlated with PSA block (Fig. 4) because of long duration effect of this technique. And this finding was opposite to the result of Padhye et al. (7). PSA block was used to overcome the variation in the anatomy of the roots and nerve pathways or even in the presence of infection (19). Some adverse events have been reported with the PSA block including transient diplopia, mydriasis, double vision, and hematomas (20). Hematoma is usually produced by inserting the needle too far posteriorly into the pterygoid plexus of veins. (14) With good technique, hematomas should not be a problem with the PSA nerve block (6).
package sections import ( "github.com/FlagField/FlagField-Server/internal/app/setup/hooks" "reflect" ) type Section struct { Name, Description string Items []*Item Before, After hooks.HookFunc } func (s *Section) Item(_key, _description string, _type reflect.Kind, _before, _after hooks.HookFunc) *Item { item := &Item{ Key: _key, Description: _description, Type: _type, Before: _before, After: _after, } s.Items = append(s.Items, item) return item }
from sportsreference.nba.boxscore import Boxscore from sportsreference.nba.schedule import Schedule from sportsreference.nba.teams import Teams import pandas as pd teams = Teams() indexes = [] for team in teams: games = team.schedule for game in games: indexes.append(game.boxscore_index) scores = pd.DataFrame() for index in indexes: score = Boxscore(index) df = score.dataframe scores = scores.append(df)
// Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // 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 manager import ( "context" resourcesv1alpha1 "github.com/gardener/gardener-resource-manager/api/resources/v1alpha1" mockclient "github.com/gardener/gardener-resource-manager/pkg/mock/controller-runtime/client" . "github.com/gardener/gardener-resource-manager/pkg/test" "github.com/golang/mock/gomock" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/pointer" "sigs.k8s.io/controller-runtime/pkg/client" ) var _ = Describe("Resource Manager", func() { var ( ctrl *gomock.Controller c *mockclient.MockClient ) BeforeEach(func() { ctrl = gomock.NewController(GinkgoT()) c = mockclient.NewMockClient(ctrl) }) AfterEach(func() { ctrl.Finish() }) Describe("Secrets", func() { ctx := context.TODO() It("should correctly create a managed secret", func() { var ( secretName = "foo" secretNamespace = "bar" secretLabels = map[string]string{ "boo": "goo", } secretAnnotations = map[string]string{ "a": "b", } secretData = map[string][]byte{ "foo": []byte("bar"), } secretMeta = metav1.ObjectMeta{ Name: secretName, Namespace: secretNamespace, Annotations: secretAnnotations, Labels: secretLabels, } expectedSecret = &corev1.Secret{ ObjectMeta: secretMeta, Data: secretData, } ) managedSecret := NewSecret(c). WithNamespacedName(secretNamespace, secretName). WithKeyValues(secretData). WithLabels(secretLabels). WithAnnotations(secretAnnotations) Expect(managedSecret.secret).To(Equal(expectedSecret)) c.EXPECT().Get(ctx, client.ObjectKey{Namespace: secretNamespace, Name: secretName}, gomock.AssignableToTypeOf(&corev1.Secret{})).DoAndReturn(func(_ context.Context, _ client.ObjectKey, secret *corev1.Secret) error { return apierrors.NewNotFound(corev1.Resource("secrets"), secretName) }) expectedSecret.Type = corev1.SecretTypeOpaque c.EXPECT().Create(ctx, gomock.AssignableToTypeOf(&corev1.Secret{})).DoAndReturn(func(_ context.Context, secret *corev1.Secret, _ ...client.CreateOption) error { Expect(secret).To(BeSemanticallyEqualTo(expectedSecret)) return nil }) err := managedSecret.Reconcile(ctx) Expect(err).NotTo(HaveOccurred()) }) It("should correctly create a managed resource", func() { var ( managedResourceName = "foo" managedResourceNamespace = "bar" managedResourceLabels = map[string]string{ "boo": "goo", } managedResourceAnnotations = map[string]string{ "a": "b", } managedResourceMeta = metav1.ObjectMeta{ Name: managedResourceName, Namespace: managedResourceNamespace, Labels: managedResourceLabels, Annotations: managedResourceAnnotations, } resourceClass = "shoot" secretRefs = []corev1.LocalObjectReference{ {Name: "test1"}, {Name: "test2"}, {Name: "test3"}, } injectedLabels = map[string]string{ "shoot.gardener.cloud/no-cleanup": "true", } forceOverwriteAnnotations = true forceOverwriteLabels = true keepObjects = true deletePersistentVolumeClaims = true expectedManagedResource = &resourcesv1alpha1.ManagedResource{ ObjectMeta: managedResourceMeta, Spec: resourcesv1alpha1.ManagedResourceSpec{ SecretRefs: secretRefs, InjectLabels: injectedLabels, Class: pointer.StringPtr(resourceClass), ForceOverwriteAnnotations: pointer.BoolPtr(forceOverwriteAnnotations), ForceOverwriteLabels: pointer.BoolPtr(forceOverwriteLabels), KeepObjects: pointer.BoolPtr(keepObjects), DeletePersistentVolumeClaims: pointer.BoolPtr(deletePersistentVolumeClaims), }, } ) managedResource := NewManagedResource(c). WithNamespacedName(managedResourceNamespace, managedResourceName). WithLabels(managedResourceLabels). WithAnnotations(managedResourceAnnotations). WithClass(resourceClass). WithSecretRef(secretRefs[0].Name). WithSecretRefs(secretRefs[1:]). WithInjectedLabels(injectedLabels). ForceOverwriteAnnotations(forceOverwriteAnnotations). ForceOverwriteLabels(forceOverwriteLabels). KeepObjects(keepObjects). DeletePersistentVolumeClaims(deletePersistentVolumeClaims) Expect(managedResource.resource).To(Equal(expectedManagedResource)) c.EXPECT().Get(ctx, client.ObjectKey{Namespace: managedResourceNamespace, Name: managedResourceName}, gomock.AssignableToTypeOf(&resourcesv1alpha1.ManagedResource{})).DoAndReturn(func(_ context.Context, _ client.ObjectKey, ms *resourcesv1alpha1.ManagedResource) error { return apierrors.NewNotFound(corev1.Resource("managedresources"), managedResourceName) }) c.EXPECT().Create(ctx, gomock.AssignableToTypeOf(&resourcesv1alpha1.ManagedResource{})).DoAndReturn(func(_ context.Context, mr *resourcesv1alpha1.ManagedResource, _ ...client.CreateOption) error { Expect(mr).To(BeSemanticallyEqualTo(expectedManagedResource)) return nil }) err := managedResource.Reconcile(ctx) Expect(err).NotTo(HaveOccurred()) }) }) })
def example(): seam_counts = [10, 50] image = io.imread('lena.jpg') carver = SeamCarver(image) for count in seam_counts: carver.find_seams(count) save_image('lena_{}_seams.png'.format(count), carver.color()) save_image('lena_{}_shrunk.png'.format(count), carver.shrink())
A Lancaster County judge won't block a lawsuit filed for three same-sex couples challenging a Nebraska policy that bars them and all unmarried couples from serving as foster parents.Lincoln Journal Star says the state had sought dismissal of the case, saying the plaintiffs had no standing and had failed to state a claim.But Judge John Colborn said in a ruling issued last week that there was no evidence presented as to whether the policy could survive judicial scrutiny, so he allowed the case to go forward.The lawsuit filed for the couples last August by the Nebraska and national American Civil Liberties Union argues that the policy discriminates against would-be foster parents based on their sexual orientation. A Lancaster County judge won't block a lawsuit filed for three same-sex couples challenging a Nebraska policy that bars them and all unmarried couples from serving as foster parents. Lincoln Journal Star says the state had sought dismissal of the case, saying the plaintiffs had no standing and had failed to state a claim. Advertisement But Judge John Colborn said in a ruling issued last week that there was no evidence presented as to whether the policy could survive judicial scrutiny, so he allowed the case to go forward. The lawsuit filed for the couples last August by the Nebraska and national American Civil Liberties Union argues that the policy discriminates against would-be foster parents based on their sexual orientation. AlertMe
//Closing the class Combo class A { //implements ActionListener { Object [] index; JFrame jf; JPanel jp; JLabel label1, label2; A() { jf = new JFrame("JScrollBar"); jp = new JPanel(); label1 = new JLabel("Displaying a picture ",JLabel.CENTER); ImageIcon image = new ImageIcon("C:/Users/lili5/Downloads/Capture.PNG"); JLabel label = new JLabel(image, JLabel.CENTER); jp = new JPanel(new BorderLayout()); jp.add( label, BorderLayout.CENTER ); JScrollBar scrollB1 = new JScrollBar(JScrollBar.HORIZONTAL, 10, 40, 0, 100); JScrollBar scrollB2 = new JScrollBar(JScrollBar.VERTICAL, 10, 60, 0, 100); jf.add(label1,BorderLayout.NORTH); jf.add(jp,BorderLayout.CENTER); jf.add(scrollB2,BorderLayout.EAST); jf.add(scrollB1,BorderLayout.SOUTH); jf.setSize(350,270); jf.setVisible(true); } }
<gh_stars>10-100 /*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2010 <NAME> * * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include "codeclib.h" #include "adpcm_seek.h" #include "support_formats.h" /* * Dialogic OKI ADPCM * * References * [1] Dialogic Corporation, Dialogic ADPCM Algorithm, 1988 * [2] MultimediaWiki, Dialogic IMA ADPCM, URL:http://wiki.multimedia.cx/index.php?title=Dialogic_IMA_ADPCM * [3] sox source code, src/adpcms.c * [4] Tetsuya Isaki, NetBSD:/sys/dev/audio.c, http://www.tri-tree.gr.jp/~isaki/NetBSD/src/sys/dev/ic/msm6258.c.html */ static const uint16_t step_table[] ICONST_ATTR = { 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, }; static const int index_table[] ICONST_ATTR = { -1, -1, -1, -1, 2, 4, 6, 8 }; static struct adpcm_data cur_data; static int blocksperchunk; static struct pcm_format *fmt; static bool set_format(struct pcm_format *format) { uint32_t max_chunk_count; fmt = format; if (fmt->bitspersample != 4) { DEBUGF("CODEC_ERROR: dialogic oki adpcm must be 4 bitspersample: %d\n", fmt->bitspersample); return false; } if (fmt->channels != 1) { DEBUGF("CODEC_ERROR: dialogic oki adpcm must be monaural\n"); return false; } /* blockalign = 2 samples */ fmt->blockalign = 1; fmt->samplesperblock = 2; /* chunksize = about 1/32[sec] data */ blocksperchunk = ci->id3->frequency >> 6; fmt->chunksize = blocksperchunk * fmt->blockalign; max_chunk_count = (uint64_t)ci->id3->length * ci->id3->frequency / (2000LL * fmt->chunksize); /* initialize seek table */ init_seek_table(max_chunk_count); /* add first data */ add_adpcm_data(&cur_data); return true; } static int16_t create_pcmdata(uint8_t nibble) { int16_t delta; int16_t index = cur_data.step[0]; int16_t step = step_table[index]; delta = (step >> 3); if (nibble & 4) delta += step; if (nibble & 2) delta += (step >> 1); if (nibble & 1) delta += (step >> 2); if (nibble & 0x08) cur_data.pcmdata[0] -= delta; else cur_data.pcmdata[0] += delta; CLIP(cur_data.pcmdata[0], -2048, 2047); index += index_table[nibble & 0x07]; CLIP(index, 0, 48); cur_data.step[0] = index; return cur_data.pcmdata[0]; } static int decode(const uint8_t *inbuf, size_t inbufsize, int32_t *outbuf, int *outbufcount) { size_t nsamples = 0; while (inbufsize) { *outbuf++ = create_pcmdata(*inbuf >> 4) << (PCM_OUTPUT_DEPTH - 12); *outbuf++ = create_pcmdata(*inbuf ) << (PCM_OUTPUT_DEPTH - 12); nsamples += 2; inbuf++; inbufsize--; } *outbufcount = nsamples; add_adpcm_data(&cur_data); return CODEC_OK; } static int decode_for_seek(const uint8_t *inbuf, size_t inbufsize) { while (inbufsize) { create_pcmdata(*inbuf >> 4); create_pcmdata(*inbuf ); inbuf++; inbufsize--; } add_adpcm_data(&cur_data); return CODEC_OK; } static struct pcm_pos *get_seek_pos(uint32_t seek_val, int seek_mode, uint8_t *(*read_buffer)(size_t *realsize)) { static struct pcm_pos newpos; uint32_t seek_count = (seek_mode == PCM_SEEK_TIME)? ((uint64_t)seek_val * ci->id3->frequency / 1000LL) / (blocksperchunk * fmt->samplesperblock) : seek_val / (unsigned long)fmt->chunksize; uint32_t new_count = seek(seek_count, &cur_data, read_buffer, &decode_for_seek); newpos.pos = new_count * fmt->chunksize; newpos.samples = new_count * blocksperchunk * fmt->samplesperblock; return &newpos; } static const struct pcm_codec codec = { set_format, get_seek_pos, decode, }; const struct pcm_codec *get_dialogic_oki_adpcm_codec(void) { /* * initialize first pcm data, step index * because the dialogic oki adpcm is always monaural, * pcmdata[1], step[1] do not use. */ cur_data.pcmdata[0] = 0; cur_data.step[0] = 0; return &codec; }