text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // WhiteKeys.cpp // modularSynth // // Created by Ryan Challinor on 3/7/13. // // #include "WhiteKeys.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" WhiteKeys::WhiteKeys() { } void WhiteKeys::DrawModule() { if (Minimized() || IsVisible() == false) return; } void WhiteKeys::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void WhiteKeys::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } int octave = pitch / TheScale->GetPitchesPerOctave(); int degree = -1; switch (pitch % TheScale->GetPitchesPerOctave()) { default: case 0: degree = 0; break; case 2: degree = 1; break; case 4: degree = 2; break; case 5: degree = 3; break; case 7: degree = 4; break; case 9: degree = 5; break; case 11: degree = 6; break; } if (degree != -1) { pitch = TheScale->GetPitchFromTone(degree); pitch += octave * TheScale->GetPitchesPerOctave(); PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } } void WhiteKeys::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void WhiteKeys::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/WhiteKeys.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
517
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // FFT.cpp // modularSynth // // Created by Ryan Challinor on 1/27/13. // // #include "FFT.h" #include <cstring> // Constructor for FFT routine FFT::FFT(int nfft) { mNfft = nfft; mNumfreqs = nfft / 2 + 1; mFft_data = (float*)calloc(nfft, sizeof(float)); } // Destructor for FFT routine FFT::~FFT() { free(mFft_data); } // Perform forward FFT of real data // Accepts: // input - pointer to an array of (real) input values, size nfft // output_re - pointer to an array of the real part of the output, // size nfft/2 + 1 // output_im - pointer to an array of the imaginary part of the output, // size nfft/2 + 1 void FFT::Forward(float* input, float* output_re, float* output_im) { int hnfft = mNfft / 2; for (int ti = 0; ti < mNfft; ti++) { mFft_data[ti] = input[ti]; } mayer_realfft(mNfft, mFft_data); output_im[0] = 0; for (int ti = 0; ti < hnfft; ti++) { output_re[ti] = mFft_data[ti]; output_im[ti] = mFft_data[mNfft - 1 - ti]; } output_re[hnfft] = mFft_data[hnfft]; output_im[hnfft] = 0; } // Perform inverse FFT, returning real data // Accepts: // input_re - pointer to an array of the real part of the output, // size nfft/2 + 1 // input_im - pointer to an array of the imaginary part of the output, // size nfft/2 + 1 // output - pointer to an array of (real) input values, size nfft void FFT::Inverse(float* input_re, float* input_im, float* output) { int hnfft; hnfft = mNfft / 2; for (int ti = 0; ti < hnfft; ti++) { mFft_data[ti] = input_re[ti]; mFft_data[mNfft - 1 - ti] = input_im[ti]; } mFft_data[hnfft] = input_re[hnfft]; mayer_realifft(mNfft, mFft_data); for (int ti = 0; ti < mNfft; ti++) { output[ti] = mFft_data[ti]; } } /* This is the FFT routine taken from PureData, a great piece of software by Miller S. Puckette. path_to_url~msp/software.html */ /* ** FFT and FHT routines ** ** mayer_fht(fz,n); ** Does a hartley transform of "n" points in the array "fz". ** mayer_fft(n,real,imag) ** Does a fourier transform of "n" points of the "real" and ** "imag" arrays. ** mayer_ifft(n,real,imag) ** Does an inverse fourier transform of "n" points of the "real" ** and "imag" arrays. ** mayer_realfft(n,real) ** Does a real-valued fourier transform of "n" points of the ** "real" array. The real part of the transform ends ** up in the first half of the array and the imaginary part of the ** transform ends up in the second half of the array. ** mayer_realifft(n,real) ** The inverse of the realfft() routine above. ** ** ** NOTE: This routine uses at least 2 patented algorithms, and may be ** under the restrictions of a bunch of different organizations. ** Although I wrote it completely myself, it is kind of a derivative ** of a routine I once authored and released under the GPL, so it ** may fall under the free software foundation's restrictions; ** it was worked on as a Stanford Univ project, so they claim ** some rights to it; it was further optimized at work here, so ** I think this company claims parts of it. The patents are ** held by R. Bracewell (the FHT algorithm) and O. Buneman (the ** trig generator), both at Stanford Univ. ** If it were up to me, I'd say go do whatever you want with it; ** but it would be polite to give credit to the following people ** if you use this anywhere: ** Euler - probable inventor of the fourier transform. ** Gauss - probable inventor of the FFT. ** Hartley - probable inventor of the hartley transform. ** Buneman - for a really cool trig generator ** Mayer(me) - for authoring this particular version and ** including all the optimizations in one package. ** Thanks, ** Ron Mayer; mayer@acuson.com ** */ /* This is a slightly modified version of Mayer's contribution; write * msp@ucsd.edu for the original code. Kudos to Mayer for a fine piece * of work. -msp */ #define REAL float #define GOOD_TRIG #ifdef GOOD_TRIG #else #define FAST_TRIG #endif #if defined(GOOD_TRIG) #define FHT_SWAP(a, b, t) \ { \ (t) = (a); \ (a) = (b); \ (b) = (t); \ } #define TRIG_VARS \ int t_lam = 0; #define TRIG_INIT(k, c, s) \ { \ int i; \ for (i = 2; i <= k; i++) \ { \ coswrk[i] = costab[i]; \ sinwrk[i] = sintab[i]; \ } \ t_lam = 0; \ c = 1; \ s = 0; \ } #define TRIG_NEXT(k, c, s) \ { \ int i, j; \ (t_lam)++; \ for (i = 0; !((1 << i) & t_lam); i++) \ ; \ i = k - i; \ s = sinwrk[i]; \ c = coswrk[i]; \ if (i > 1) \ { \ for (j = k - i + 2; (1 << j) & t_lam; j++) \ ; \ j = k - j; \ sinwrk[i] = halsec[i] * (sinwrk[i - 1] + sinwrk[j]); \ coswrk[i] = halsec[i] * (coswrk[i - 1] + coswrk[j]); \ } \ } #define TRIG_RESET(k, c, s) #endif #if defined(FAST_TRIG) #define TRIG_VARS \ REAL t_c, t_s; #define TRIG_INIT(k, c, s) \ { \ t_c = costab[k]; \ t_s = sintab[k]; \ c = 1; \ s = 0; \ } #define TRIG_NEXT(k, c, s) \ { \ REAL t = c; \ c = t * t_c - s * t_s; \ s = t * t_s + s * t_c; \ } #define TRIG_RESET(k, c, s) #endif static REAL halsec[20] = { 0, 0, .54119610014619698439972320536638942006107206337801, .50979557910415916894193980398784391368261849190893, .50241928618815570551167011928012092247859337193963, .50060299823519630134550410676638239611758632599591, .50015063602065098821477101271097658495974913010340, .50003765191554772296778139077905492847503165398345, .50000941253588775676512870469186533538523133757983, .50000235310628608051401267171204408939326297376426, .50000058827484117879868526730916804925780637276181, .50000014706860214875463798283871198206179118093251, .50000003676714377807315864400643020315103490883972, .50000000919178552207366560348853455333939112569380, .50000000229794635411562887767906868558991922348920, .50000000057448658687873302235147272458812263401372 }; static REAL costab[20] = { .00000000000000000000000000000000000000000000000000, .70710678118654752440084436210484903928483593768847, .92387953251128675612818318939678828682241662586364, .98078528040323044912618223613423903697393373089333, .99518472667219688624483695310947992157547486872985, .99879545620517239271477160475910069444320361470461, .99969881869620422011576564966617219685006108125772, .99992470183914454092164649119638322435060646880221, .99998117528260114265699043772856771617391725094433, .99999529380957617151158012570011989955298763362218, .99999882345170190992902571017152601904826792288976, .99999970586288221916022821773876567711626389934930, .99999992646571785114473148070738785694820115568892, .99999998161642929380834691540290971450507605124278, .99999999540410731289097193313960614895889430318945, .99999999885102682756267330779455410840053741619428 }; static REAL sintab[20] = { 1.0000000000000000000000000000000000000000000000000, .70710678118654752440084436210484903928483593768846, .38268343236508977172845998403039886676134456248561, .19509032201612826784828486847702224092769161775195, .09801714032956060199419556388864184586113667316749, .04906767432741801425495497694268265831474536302574, .02454122852291228803173452945928292506546611923944, .01227153828571992607940826195100321214037231959176, .00613588464915447535964023459037258091705788631738, .00306795676296597627014536549091984251894461021344, .00153398018628476561230369715026407907995486457522, .00076699031874270452693856835794857664314091945205, .00038349518757139558907246168118138126339502603495, .00019174759731070330743990956198900093346887403385, .00009587379909597734587051721097647635118706561284, .00004793689960306688454900399049465887274686668768 }; static REAL coswrk[20] = { .00000000000000000000000000000000000000000000000000, .70710678118654752440084436210484903928483593768847, .92387953251128675612818318939678828682241662586364, .98078528040323044912618223613423903697393373089333, .99518472667219688624483695310947992157547486872985, .99879545620517239271477160475910069444320361470461, .99969881869620422011576564966617219685006108125772, .99992470183914454092164649119638322435060646880221, .99998117528260114265699043772856771617391725094433, .99999529380957617151158012570011989955298763362218, .99999882345170190992902571017152601904826792288976, .99999970586288221916022821773876567711626389934930, .99999992646571785114473148070738785694820115568892, .99999998161642929380834691540290971450507605124278, .99999999540410731289097193313960614895889430318945, .99999999885102682756267330779455410840053741619428 }; static REAL sinwrk[20] = { 1.0000000000000000000000000000000000000000000000000, .70710678118654752440084436210484903928483593768846, .38268343236508977172845998403039886676134456248561, .19509032201612826784828486847702224092769161775195, .09801714032956060199419556388864184586113667316749, .04906767432741801425495497694268265831474536302574, .02454122852291228803173452945928292506546611923944, .01227153828571992607940826195100321214037231959176, .00613588464915447535964023459037258091705788631738, .00306795676296597627014536549091984251894461021344, .00153398018628476561230369715026407907995486457522, .00076699031874270452693856835794857664314091945205, .00038349518757139558907246168118138126339502603495, .00019174759731070330743990956198900093346887403385, .00009587379909597734587051721097647635118706561284, .00004793689960306688454900399049465887274686668768 }; #define SQRT2_2 0.70710678118654752440084436210484 #define SQRT2 2 * 0.70710678118654752440084436210484 void mayer_fht(REAL* fz, int n) { /* REAL a,b; REAL c1,s1,s2,c2,s3,c3,s4,c4; REAL f0,g0,f1,g1,f2,g2,f3,g3; */ int k, k1, k2, k3, k4, kx; REAL *fi, *fn, *gi; TRIG_VARS; for (k1 = 1, k2 = 0; k1 < n; k1++) { REAL aa; for (k = n >> 1; (!((k2 ^= k) & k)); k >>= 1) ; if (k1 > k2) { aa = fz[k1]; fz[k1] = fz[k2]; fz[k2] = aa; } } for (k = 0; (1 << k) < n; k++) ; k &= 1; if (k == 0) { for (fi = fz, fn = fz + n; fi < fn; fi += 4) { REAL f0, f1, f2, f3; f1 = fi[0] - fi[1]; f0 = fi[0] + fi[1]; f3 = fi[2] - fi[3]; f2 = fi[2] + fi[3]; fi[2] = (f0 - f2); fi[0] = (f0 + f2); fi[3] = (f1 - f3); fi[1] = (f1 + f3); } } else { for (fi = fz, fn = fz + n, gi = fi + 1; fi < fn; fi += 8, gi += 8) { REAL bs1, bc1, bs2, bc2, bs3, bc3, bs4, bc4, bg0, bf0, bf1, bg1, bf2, bg2, bf3, bg3; bc1 = fi[0] - gi[0]; bs1 = fi[0] + gi[0]; bc2 = fi[2] - gi[2]; bs2 = fi[2] + gi[2]; bc3 = fi[4] - gi[4]; bs3 = fi[4] + gi[4]; bc4 = fi[6] - gi[6]; bs4 = fi[6] + gi[6]; bf1 = (bs1 - bs2); bf0 = (bs1 + bs2); bg1 = (bc1 - bc2); bg0 = (bc1 + bc2); bf3 = (bs3 - bs4); bf2 = (bs3 + bs4); bg3 = SQRT2 * bc4; bg2 = SQRT2 * bc3; fi[4] = bf0 - bf2; fi[0] = bf0 + bf2; fi[6] = bf1 - bf3; fi[2] = bf1 + bf3; gi[4] = bg0 - bg2; gi[0] = bg0 + bg2; gi[6] = bg1 - bg3; gi[2] = bg1 + bg3; } } if (n < 16) return; do { REAL s1, c1; int ii; k += 2; k1 = 1 << k; k2 = k1 << 1; k4 = k2 << 1; k3 = k2 + k1; kx = k1 >> 1; fi = fz; gi = fi + kx; fn = fz + n; do { REAL g0, f0, f1, g1, f2, g2, f3, g3; f1 = fi[0] - fi[k1]; f0 = fi[0] + fi[k1]; f3 = fi[k2] - fi[k3]; f2 = fi[k2] + fi[k3]; fi[k2] = f0 - f2; fi[0] = f0 + f2; fi[k3] = f1 - f3; fi[k1] = f1 + f3; g1 = gi[0] - gi[k1]; g0 = gi[0] + gi[k1]; g3 = SQRT2 * gi[k3]; g2 = SQRT2 * gi[k2]; gi[k2] = g0 - g2; gi[0] = g0 + g2; gi[k3] = g1 - g3; gi[k1] = g1 + g3; gi += k4; fi += k4; } while (fi < fn); TRIG_INIT(k, c1, s1); for (ii = 1; ii < kx; ii++) { REAL c2, s2; TRIG_NEXT(k, c1, s1); c2 = c1 * c1 - s1 * s1; s2 = 2 * (c1 * s1); fn = fz + n; fi = fz + ii; gi = fz + k1 - ii; do { REAL a, b, g0, f0, f1, g1, f2, g2, f3, g3; b = s2 * fi[k1] - c2 * gi[k1]; a = c2 * fi[k1] + s2 * gi[k1]; f1 = fi[0] - a; f0 = fi[0] + a; g1 = gi[0] - b; g0 = gi[0] + b; b = s2 * fi[k3] - c2 * gi[k3]; a = c2 * fi[k3] + s2 * gi[k3]; f3 = fi[k2] - a; f2 = fi[k2] + a; g3 = gi[k2] - b; g2 = gi[k2] + b; b = s1 * f2 - c1 * g3; a = c1 * f2 + s1 * g3; fi[k2] = f0 - a; fi[0] = f0 + a; gi[k3] = g1 - b; gi[k1] = g1 + b; b = c1 * g2 - s1 * f3; a = s1 * g2 + c1 * f3; gi[k2] = g0 - a; gi[0] = g0 + a; fi[k3] = f1 - b; fi[k1] = f1 + b; gi += k4; fi += k4; } while (fi < fn); } TRIG_RESET(k, c1, s1); } while (k4 < n); } void mayer_fft(int n, REAL* real, REAL* imag) { REAL a, b, c, d; REAL q, r, s, t; int i, j, k; for (i = 1, j = n - 1, k = n / 2; i < k; i++, j--) { a = real[i]; b = real[j]; q = a + b; r = a - b; c = imag[i]; d = imag[j]; s = c + d; t = c - d; real[i] = (q + t) * .5; real[j] = (q - t) * .5; imag[i] = (s - r) * .5; imag[j] = (s + r) * .5; } mayer_fht(real, n); mayer_fht(imag, n); } void mayer_ifft(int n, REAL* real, REAL* imag) { REAL a, b, c, d; REAL q, r, s, t; int i, j, k; mayer_fht(real, n); mayer_fht(imag, n); for (i = 1, j = n - 1, k = n / 2; i < k; i++, j--) { a = real[i]; b = real[j]; q = a + b; r = a - b; c = imag[i]; d = imag[j]; s = c + d; t = c - d; imag[i] = (s + r) * 0.5; imag[j] = (s - r) * 0.5; real[i] = (q - t) * 0.5; real[j] = (q + t) * 0.5; } } void mayer_realfft(int n, REAL* real) { REAL a, b; int i, j, k; mayer_fht(real, n); for (i = 1, j = n - 1, k = n / 2; i < k; i++, j--) { a = real[i]; b = real[j]; real[j] = (a - b) * 0.5; real[i] = (a + b) * 0.5; } } void mayer_realifft(int n, REAL* real) { REAL a, b; int i, j, k; for (i = 1, j = n - 1, k = n / 2; i < k; i++, j--) { a = real[i]; b = real[j]; real[j] = (a - b); real[i] = (a + b); } mayer_fht(real, n); } void FFTData::Clear() { std::memset(mRealValues, 0, mFreqDomainSize * sizeof(float)); std::memset(mImaginaryValues, 0, mFreqDomainSize * sizeof(float)); std::memset(mTimeDomain, 0, mWindowSize * sizeof(float)); } ```
/content/code_sandbox/Source/FFT.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,806
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Pumper.h // modularSynth // // Created by Ryan Challinor on 3/16/13. // // #pragma once #include <iostream> #include "IAudioEffect.h" #include "Checkbox.h" #include "Slider.h" #include "DropdownList.h" #include "LFO.h" class Pumper : public IAudioEffect, public IDropdownListener, public IFloatSliderListener { public: Pumper(); virtual ~Pumper(); static IAudioEffect* Create() { return new Pumper(); } void CreateUIControls() override; //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } float GetEffectAmount() override; std::string GetType() override { return "pumper"; } void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override {} void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 1; } bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = mWidth; h = mHeight; } double GetIntervalPos(double time); void SyncToAdsr(); FloatSlider* mAmountSlider{ nullptr }; FloatSlider* mLengthSlider{ nullptr }; FloatSlider* mCurveSlider{ nullptr }; FloatSlider* mAttackSlider{ nullptr }; ::ADSR mAdsr; NoteInterval mInterval{ NoteInterval::kInterval_4n }; DropdownList* mIntervalSelector{ nullptr }; float mLastValue{ 0 }; float mAmount{ 0 }; float mLength{ 0 }; float mAttack{ 0 }; float mWidth{ 200 }; float mHeight{ 20 }; }; ```
/content/code_sandbox/Source/Pumper.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
569
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ControlTactileFeedback.h // modularSynth // // Created by Ryan Challinor on 1/9/14. // // #pragma once #include <iostream> #include "IAudioSource.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "Slider.h" class ControlTactileFeedback : public IAudioSource, public IDrawableModule, public IFloatSliderListener { public: ControlTactileFeedback(); ~ControlTactileFeedback(); static IDrawableModule* Create() { return new ControlTactileFeedback(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void CheckboxUpdated(Checkbox* checkbox, double time) override {} //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 80; height = 60; } float mPhase{ 0 }; float mPhaseInc{ 0 }; float mVolume{ .5 }; FloatSlider* mVolumeSlider{ nullptr }; }; ```
/content/code_sandbox/Source/ControlTactileFeedback.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
459
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // GroupControl.cpp // Bespoke // // Created by Ryan Challinor on 2/7/16. // // #include "GroupControl.h" #include "ModularSynth.h" #include "PatchCableSource.h" GroupControl::GroupControl() { } GroupControl::~GroupControl() { } void GroupControl::CreateUIControls() { IDrawableModule::CreateUIControls(); mGroupCheckbox = new Checkbox(this, "group enabled", 3, 3, &mGroupEnabled); } void GroupControl::DrawModule() { if (Minimized() || IsVisible() == false) return; for (int i = 0; i < mControlCables.size(); ++i) { mControlCables[i]->SetManualPosition(10 + i * 12, 25); } mGroupCheckbox->Draw(); } void GroupControl::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { for (int i = 0; i < mControlCables.size(); ++i) { if (mControlCables[i] == cableSource) { if (i == mControlCables.size() - 1) { if (cableSource->GetTarget()) { PatchCableSource* cable = new PatchCableSource(this, kConnectionType_Modulator); AddPatchCableSource(cable); mControlCables.push_back(cable); } } else if (cableSource->GetTarget() == nullptr && fromUserClick) { RemoveFromVector(cableSource, mControlCables); } break; } } } void GroupControl::CheckboxUpdated(Checkbox* checkbox, double time) { for (auto& mControlCable : mControlCables) { IUIControl* uicontrol = nullptr; for (auto& cable : mControlCable->GetPatchCables()) { if (cable->GetTarget()) { uicontrol = dynamic_cast<IUIControl*>(cable->GetTarget()); if (uicontrol) uicontrol->SetValue(mGroupEnabled ? 1 : 0, time); } } } } namespace { const float extraW = 20; } void GroupControl::GetModuleDimensions(float& width, float& height) { width = mGroupCheckbox->GetRect().width + extraW; height = 38; } void GroupControl::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["uicontrols"].resize((unsigned int)mControlCables.size() - 1); for (int i = 0; i < mControlCables.size() - 1; ++i) { std::string controlName = ""; if (mControlCables[i]->GetTarget()) controlName = mControlCables[i]->GetTarget()->Path(); moduleInfo["uicontrols"][i] = controlName; } } void GroupControl::LoadLayout(const ofxJSONElement& moduleInfo) { const Json::Value& controls = moduleInfo["uicontrols"]; for (int i = 0; i < controls.size(); ++i) { try { std::string controlPath = controls[i].asString(); IUIControl* control = nullptr; if (!controlPath.empty()) control = TheSynth->FindUIControl(controlPath); PatchCableSource* cable = new PatchCableSource(this, kConnectionType_Modulator); AddPatchCableSource(cable); cable->SetTarget(control); mControlCables.push_back(cable); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } //add extra cable PatchCableSource* cable = new PatchCableSource(this, kConnectionType_Modulator); AddPatchCableSource(cable); mControlCables.push_back(cable); SetUpFromSaveData(); } void GroupControl::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/GroupControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
998
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== IAudioReceiver.cpp Created: 15 Oct 2017 10:23:15pm Author: Ryan Challinor ============================================================================== */ #include "IAudioReceiver.h" void IAudioReceiver::SyncInputBuffer() { if (GetInputMode() == kInputMode_Mono && GetBuffer()->NumActiveChannels() > 1) { //sum to mono for (int i = 1; i < GetBuffer()->NumActiveChannels(); ++i) Add(GetBuffer()->GetChannel(0), GetBuffer()->GetChannel(i), GetBuffer()->BufferSize()); //Mult(GetBuffer()->GetChannel(0), 1.0f / GetBuffer()->NumActiveChannels(), GetBuffer()->BufferSize()); GetBuffer()->SetNumActiveChannels(1); } } ```
/content/code_sandbox/Source/IAudioReceiver.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
270
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // RadioButton.cpp // modularSynth // // Created by Ryan Challinor on 12/5/12. // // #include "RadioButton.h" #include "IDrawableModule.h" #include "SynthGlobals.h" #include "FileStream.h" #include "DropdownList.h" const int radioSpacing = 15; //static int RadioButton::GetSpacing() { return radioSpacing; } RadioButton::RadioButton(IRadioButtonListener* owner, const char* name, int x, int y, int* var, RadioDirection direction /*= kRadioVertical*/) : mVar(var) , mOwner(owner) , mDirection(direction) { assert(owner); SetName(name); SetPosition(x, y); SetParent(dynamic_cast<IClickable*>(owner)); (dynamic_cast<IDrawableModule*>(owner))->AddUIControl(this); } RadioButton::RadioButton(IRadioButtonListener* owner, const char* name, IUIControl* anchor, AnchorDirection anchorDirection, int* var, RadioDirection direction /*= kRadioVertical*/) : RadioButton(owner, name, -1, -1, var, direction) { PositionTo(anchor, anchorDirection); } RadioButton::~RadioButton() { } void RadioButton::AddLabel(const char* label, int value) { RadioButtonElement element; element.mLabel = label; element.mValue = value; mElements.push_back(element); UpdateDimensions(); CalcSliderVal(); } void RadioButton::SetLabel(const char* label, int value) { for (int i = 0; i < mElements.size(); ++i) { if (mElements[i].mValue == value) mElements[i].mLabel = label; } UpdateDimensions(); } void RadioButton::RemoveLabel(int value) { for (auto iter = mElements.begin(); iter != mElements.end(); ++iter) { if (iter->mValue == value) { mElements.erase(iter); break; } } UpdateDimensions(); } void RadioButton::UpdateDimensions() { if (mDirection == kRadioVertical) { for (int i = 0; i < mElements.size(); ++i) { int width = GetStringWidth(mElements[i].mLabel) + 5; if (width > mWidth) mWidth = width; } mHeight = radioSpacing * (int)mElements.size(); mElementWidth = mWidth; } else { for (int i = 0; i < mElements.size(); ++i) { int width = GetStringWidth(mElements[i].mLabel) + 5; if (width > mElementWidth) mElementWidth = width; } mWidth = mElementWidth * (int)mElements.size(); mHeight = radioSpacing; } if (mForcedWidth != -1) mWidth = mForcedWidth; } void RadioButton::Clear() { mElements.clear(); mWidth = 40; mHeight = 15; if (mForcedWidth != -1) mWidth = mForcedWidth; } void RadioButton::Poll() { if (*mVar != mLastSetValue) CalcSliderVal(); } void RadioButton::Render() { ofPushStyle(); DrawBeacon(mX + mWidth / 2, mY + mHeight / 2); float w, h; GetDimensions(w, h); ofFill(); ofSetColor(0, 0, 0, gModuleDrawAlpha * .5f); ofRect(mX + 1, mY + 1, mWidth, mHeight); ofPushMatrix(); ofClipWindow(mX, mY, mWidth, mHeight, true); for (int i = 0; i < mElements.size(); ++i) { ofColor color, textColor; IUIControl::GetColors(color, textColor); bool active = false; if (mVar) { if (mMultiSelect) active = (1 << mElements[i].mValue) & *mVar; else active = mElements[i].mValue == *mVar; } if (active) { float color_h, color_s, color_b; color.getHsb(color_h, color_s, color_b); color.setHsb(42, color_s, color_b); textColor.set(255, 255, 0, gModuleDrawAlpha); } ofFill(); if (active) color.setBrightness(ofLerp(color.getBrightness(), 255, .3f)); ofSetColor(color); float x, y; if (mDirection == kRadioVertical) { x = mX; y = mY + i * radioSpacing; ofRect(x, y, w, radioSpacing); } else { x = mX + mElementWidth * i; y = mY; ofRect(x, y, mElementWidth, radioSpacing); } ofNoFill(); ofSetColor(textColor); //ofRect(mX,mY+i*radioSpacing,w,15); DrawTextNormal(mElements[i].mLabel, x + 2, y + 12); } ofPopMatrix(); ofPopStyle(); DrawHover(mX, mY, w, h); } bool RadioButton::MouseMoved(float x, float y) { CheckHover(x, y); return false; } void RadioButton::OnClicked(float x, float y, bool right) { if (right) return; if (mDirection == kRadioVertical) SetIndex(y / radioSpacing, NextBufferTime(false)); else //kRadioHorizontal SetIndex(int(x / mElementWidth), NextBufferTime(false)); } ofVec2f RadioButton::GetOptionPosition(int optionIndex) { float x, y; GetPosition(x, y, false); if (mDirection == kRadioVertical) return ofVec2f(x + mWidth, y + float(mHeight) / GetNumValues() * (optionIndex + .5f)); else //kRadioHorizontal return ofVec2f(x + float(mWidth) / GetNumValues() * (optionIndex + .5f), y + mHeight); } void RadioButton::SetIndex(int i, double time) { if (mElements.empty()) return; i = ofClamp(i, 0, mElements.size() - 1); int oldVal = *mVar; if (mMultiSelect) *mVar ^= 1 << mElements[i].mValue; else *mVar = mElements[i].mValue; if (oldVal != *mVar) { CalcSliderVal(); mOwner->RadioButtonUpdated(this, oldVal, time); gControlTactileFeedback = 1; } } void RadioButton::SetFromMidiCC(float slider, double time, bool setViaModulator) { slider = ofClamp(slider, 0, 1); SetIndex(int(slider * mElements.size()), time); mSliderVal = slider; mLastSetValue = *mVar; } float RadioButton::GetValueForMidiCC(float slider) const { if (mElements.empty()) return 0; int index = int(slider * mElements.size()); index = ofClamp(index, 0, mElements.size() - 1); return mElements[index].mValue; } void RadioButton::SetValue(float value, double time, bool forceUpdate /*= false*/) { if (mMultiSelect) value = *mVar ^ (1 << (int)value); SetValueDirect(value, time, forceUpdate); } void RadioButton::SetValueDirect(float value, double time) { SetValueDirect(value, time, false); } void RadioButton::SetValueDirect(float value, double time, bool forceUpdate) { int oldVal = *mVar; *mVar = (int)value; if (oldVal != *mVar) { CalcSliderVal(); mOwner->RadioButtonUpdated(this, oldVal, time); gControlTactileFeedback = 1; } } float RadioButton::GetValue() const { return *mVar; } float RadioButton::GetMidiValue() const { if (mMultiSelect) return GetValue(); return mSliderVal; } std::string RadioButton::GetDisplayValue(float val) const { if (mMultiSelect) return "multiselect"; int curIndex = -1; for (int i = 0; i < mElements.size(); ++i) { if (mElements[i].mValue == val) curIndex = i; } if (curIndex >= 0 && curIndex < mElements.size()) return mElements[curIndex].mLabel; else return "-----"; } void RadioButton::Increment(float amount) { if (mMultiSelect) return; int current = 0; for (int i = 0; i < mElements.size(); ++i) { if (mElements[i].mValue == *mVar) { current = i; break; } } SetIndex(current + (int)amount, NextBufferTime(false)); } EnumMap RadioButton::GetEnumMap() { EnumMap ret; for (int i = 0; i < mElements.size(); ++i) ret[mElements[i].mLabel] = mElements[i].mValue; return ret; } void RadioButton::CopyContentsTo(DropdownList* list) const { list->Clear(); for (auto& element : mElements) list->AddLabel(element.mLabel, element.mValue); } void RadioButton::CalcSliderVal() { int current = -1; for (int i = 0; i < mElements.size(); ++i) { if (mElements[i].mValue == *mVar) { current = i; break; } } if (current != -1) mSliderVal = ofMap(current, 0, mElements.size(), 0, 1); else mSliderVal = -1; mLastSetValue = *mVar; } namespace { const int kSaveStateRev = 0; } void RadioButton::SaveState(FileStreamOut& out) { out << kSaveStateRev; out << (float)*mVar; } void RadioButton::LoadState(FileStreamIn& in, bool shouldSetValue) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); float var; in >> var; if (shouldSetValue) SetValueDirect(var, gTime); } ```
/content/code_sandbox/Source/RadioButton.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,429
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== NotePanRandom.cpp Created: 22 Feb 2020 10:39:25pm Author: Ryan Challinor ============================================================================== */ #include "NotePanRandom.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "UIControlMacros.h" NotePanRandom::NotePanRandom() { for (int i = 0; i < kPanHistoryDisplaySize; ++i) mPanHistoryDisplay[i].time = -9999; } void NotePanRandom::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mSpreadSlider, "spread", &mSpread, 0, 1); FLOATSLIDER(mCenterSlider, "center", &mCenter, -1, 1); ENDUIBLOCK(mWidth, mHeight); } void NotePanRandom::DrawModule() { if (Minimized() || IsVisible() == false) return; mSpreadSlider->Draw(); mCenterSlider->Draw(); for (int i = 0; i < kPanHistoryDisplaySize; ++i) { if (gTime - mPanHistoryDisplay[i].time > 0 && gTime - mPanHistoryDisplay[i].time < 200) { ofRectangle sliderRect = mCenterSlider->GetRect(true); float t = mPanHistoryDisplay[i].pan / 2 + .5f; ofPushStyle(); ofSetColor(0, 255, 0, 255 * (1 - (gTime - mPanHistoryDisplay[i].time) / 200)); ofFill(); ofLine(sliderRect.x + t * sliderRect.width, sliderRect.y, sliderRect.x + t * sliderRect.width, sliderRect.y + sliderRect.height); ofPopStyle(); } } } void NotePanRandom::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && velocity > 0) { ComputeSliders(0); modulation.pan = ofClamp(mCenter + ofRandom(-mSpread, mSpread), -1, 1); mPanHistoryDisplay[mPanHistoryDisplayIndex].time = time; mPanHistoryDisplay[mPanHistoryDisplayIndex].pan = modulation.pan; mPanHistoryDisplayIndex = (mPanHistoryDisplayIndex + 1) % kPanHistoryDisplaySize; } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void NotePanRandom::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NotePanRandom::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NotePanRandom.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
713
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteToMs.h // Bespoke // // Created by Ryan Challinor on 12/17/15. // // #pragma once #include "IDrawableModule.h" #include "INoteReceiver.h" #include "IModulator.h" class PatchCableSource; class NoteToMs : public IDrawableModule, public INoteReceiver, public IModulator { public: NoteToMs(); virtual ~NoteToMs(); static IDrawableModule* Create() { return new NoteToMs(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void SendCC(int control, int value, int voiceIdx = -1) override {} //IModulator float Value(int samplesIn = 0) override; bool Active() const override { return mEnabled; } bool CanAdjustRange() const override { return false; } //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 110; height = 0; } float mPitch{ 0 }; ModulationChain* mPitchBend{ nullptr }; }; ```
/content/code_sandbox/Source/NoteToMs.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
515
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ChannelBuffer.h Created: 10 Oct 2017 8:53:51pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "SynthGlobals.h" #include "FileStream.h" class ChannelBuffer { public: ChannelBuffer(int bufferSize); ChannelBuffer(float* data, int bufferSize); //intended as a temporary holder for passing raw data to methods that want a ChannelBuffer ~ChannelBuffer(); float* GetChannel(int channel); void Clear() const; void SetMaxAllowedChannels(int channels); void SetNumActiveChannels(int channels) { mActiveChannels = MIN(mNumChannels, channels); } int NumActiveChannels() const { return mActiveChannels; } int RecentNumActiveChannels() const { return mRecentActiveChannels; } int NumTotalChannels() const { return mNumChannels; } int BufferSize() const { return mBufferSize; } void CopyFrom(ChannelBuffer* src, int length = -1, int startOffset = 0); void SetChannelPointer(float* data, int channel, bool deleteOldData); void Reset() { Clear(); mRecentActiveChannels = mActiveChannels; SetNumActiveChannels(1); } void Resize(int bufferSize); enum class LoadMode { kSetBufferSize, kRequireExactBufferSize, kAnyBufferSize }; void Save(FileStreamOut& out, int writeLength); void Load(FileStreamIn& in, int& readLength, LoadMode loadMode); static const int kMaxNumChannels = 2; private: void Setup(int bufferSize); int mActiveChannels{ 1 }; int mNumChannels{ 1 }; int mBufferSize{ 0 }; float** mBuffers; int mRecentActiveChannels{ 1 }; bool mOwnsBuffers{ true }; }; ```
/content/code_sandbox/Source/ChannelBuffer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
500
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ControllingSong.cpp // Bespoke // // Created by Ryan Challinor on 3/29/14. // // #include "ControllingSong.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "Transport.h" #include "Scale.h" #include "FollowingSong.h" #include "IAudioReceiver.h" ControllingSong::ControllingSong() { } void ControllingSong::CreateUIControls() { IDrawableModule::CreateUIControls(); mVolumeSlider = new FloatSlider(this, "vol", 150, 20, 100, 15, &mVolume, 0, 1); mNextSongButton = new ClickButton(this, "next", 350, 4); mSongSelector = new DropdownList(this, "song", 150, 4, &mCurrentSongIndex); mTestBeatOffsetSlider = new IntSlider(this, "test offset", 400, 4, 100, 15, &mTestBeatOffset, -10, 10); mPlayCheckbox = new Checkbox(this, "play", 4, 15, &mPlay); mShuffleCheckbox = new Checkbox(this, "shuffle", 80, 15, &mShuffle); mPhraseBackButton = new ClickButton(this, " [ ", 350, 20); mPhraseForwardButton = new ClickButton(this, " ] ", 390, 20); mSpeedSlider = new FloatSlider(this, "speed", 450, 20, 100, 15, &mSpeed, 0, 5); mMuteCheckbox = new Checkbox(this, "mute", 250, 4, &mMute); } ControllingSong::~ControllingSong() { } void ControllingSong::Init() { IDrawableModule::Init(); for (int i = 0; i < mSongList["songs"].size(); ++i) { mShuffleList.push_back(i); std::string title = mSongList["songs"][i]["name"].asString(); if (mSongList["songs"][i]["keyroot"].asString() == "X") title = "X " + title; mSongSelector->AddLabel(title.c_str(), i); } std::shuffle(begin(mShuffleList), end(mShuffleList), std::mt19937(std::random_device()())); } void ControllingSong::Poll() { if (mNeedNewSong && gTime > 750) { int nextSong; if (mShuffle) { nextSong = mShuffleList[mShuffleIndex++]; if (mShuffleIndex == mSongList["songs"].size()) { mShuffleIndex = 0; std::shuffle(begin(mShuffleList), end(mShuffleList), std::mt19937(std::random_device()())); } } else { nextSong = mCurrentSongIndex + 1; if (nextSong == mSongList["songs"].size()) nextSong = 0; } LoadSong(nextSong); mNeedNewSong = false; } } void ControllingSong::LoadSong(int index) { mLoadingSong = true; mLoadSongMutex.lock(); mCurrentSongIndex = index; mMidiReader.Read(ofToDataPath(mSongList["songs"][index]["midi"].asString()).c_str()); for (int i = 0; i < mSongList["songs"][index]["wavs"].size(); ++i) { if (i == 0) { mSample.Read(ofToDataPath(mSongList["songs"][index]["wavs"][i].asString()).c_str()); mSample.SetPlayPosition(0); } else { int followIdx = i - 1; if (followIdx < mFollowSongs.size()) mFollowSongs[followIdx]->LoadSample(ofToDataPath(mSongList["songs"][index]["wavs"][i].asString()).c_str()); } } std::string keyroot = mSongList["songs"][index]["keyroot"].asString(); if (keyroot != "X" && keyroot != "") { TheScale->SetRoot(PitchFromNoteName(keyroot)); TheScale->SetScaleType(mSongList["songs"][index]["keytype"].asString()); } mMidiReader.SetBeatOffset(mSongList["songs"][index]["beatoffset"].asInt()); mSongStartTime = gTime; mLoadSongMutex.unlock(); mLoadingSong = false; } void ControllingSong::Process(double time) { PROFILER(ControllingSong); IAudioReceiver* target = GetTarget(); if (!mEnabled || target == nullptr) return; ComputeSliders(0); int bufferSize = target->GetBuffer()->BufferSize(); float* out = target->GetBuffer()->GetChannel(0); assert(bufferSize == gBufferSize); float volSq = mVolume * mVolume * .5f; mSample.SetRate(mSpeed); for (int i = 0; i < mFollowSongs.size(); ++i) { mFollowSongs[i]->SetPlaybackInfo(mPlay, mSample.GetPlayPosition(), mSpeed, mVolume); } if (!mLoadingSong && mPlay) { mLoadSongMutex.lock(); double ms = mSample.GetPlayPosition() / mSample.GetSampleRateRatio() / double(gSampleRate) * 1000.0; if (ms >= 0) { TheTransport->SetTempo(MIN(200, mMidiReader.GetTempo(ms)) * mSpeed); int measure; float measurePos; mMidiReader.GetMeasurePos(ms, measure, measurePos); TheTransport->SetMeasureTime(measure + measurePos); } gWorkChannelBuffer.SetNumActiveChannels(1); if (mSample.ConsumeData(time, &gWorkChannelBuffer, bufferSize, true)) { for (int i = 0; i < bufferSize; ++i) { float sample = gWorkChannelBuffer.GetChannel(0)[i] * volSq; if (mMute) sample = 0; out[i] += sample; GetVizBuffer()->Write(sample, 0); } } else { //mNeedNewSong = true; GetVizBuffer()->WriteChunk(gZeroBuffer, bufferSize, 0); } mLoadSongMutex.unlock(); } else { GetVizBuffer()->WriteChunk(gZeroBuffer, bufferSize, 0); } } void ControllingSong::DrawModule() { if (Minimized() || IsVisible() == false) return; mNextSongButton->Draw(); mSongSelector->Draw(); mTestBeatOffsetSlider->Draw(); mPlayCheckbox->Draw(); mShuffleCheckbox->Draw(); mPhraseForwardButton->Draw(); mPhraseBackButton->Draw(); mSpeedSlider->Draw(); mMuteCheckbox->Draw(); mVolumeSlider->Draw(); if (mCurrentSongIndex != -1) { ofPushMatrix(); ofTranslate(10, 50); if (mCurrentSongIndex != -1) DrawTextNormal(mSongList["songs"][mCurrentSongIndex]["name"].asString(), 0, -10); DrawAudioBuffer(540, 100, mSample.Data(), 0, mSample.LengthInSamples() / mSample.GetSampleRateRatio(), mSample.GetPlayPosition()); ofPopMatrix(); } ofPushStyle(); float w, h; GetDimensions(w, h); ofFill(); ofSetColor(255, 255, 255, 50); float beatWidth = w / 4; ofRect(int(TheTransport->GetMeasurePos(gTime) * 4) * beatWidth, 0, beatWidth, h); ofPopStyle(); } void ControllingSong::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mSongSelector) { LoadSong(mCurrentSongIndex); } } void ControllingSong::ButtonClicked(ClickButton* button, double time) { if (button == mNextSongButton) mNeedNewSong = true; if (button == mPhraseForwardButton || button == mPhraseBackButton) { int position = mSample.GetPlayPosition(); int jumpAmount = TheTransport->GetDuration(kInterval_4) / gInvSampleRateMs * mSample.GetSampleRateRatio(); if (button == mPhraseBackButton) jumpAmount *= -1; int newPosition = position + jumpAmount; if (newPosition < 0) newPosition = 0; mSample.SetPlayPosition(newPosition); } } void ControllingSong::CheckboxUpdated(Checkbox* checkbox, double time) { } void ControllingSong::RadioButtonUpdated(RadioButton* list, int oldVal, double time) { } void ControllingSong::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mTestBeatOffsetSlider) { mMidiReader.SetBeatOffset(mTestBeatOffset); } } void ControllingSong::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void ControllingSong::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("songs", moduleInfo); const Json::Value& follows = moduleInfo["followsongs"]; for (int i = 0; i < follows.size(); ++i) { std::string follow = follows[i].asString(); FollowingSong* followSong = dynamic_cast<FollowingSong*>(TheSynth->FindModule(follow)); if (followSong) mFollowSongs.push_back(followSong); } SetUpFromSaveData(); } void ControllingSong::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mSongList.open(ofToDataPath(mModuleSaveData.GetString("songs"))); } void ControllingSong::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["followsongs"].resize((unsigned int)mFollowSongs.size()); for (int i = 0; i < mFollowSongs.size(); ++i) { IDrawableModule* module = dynamic_cast<IDrawableModule*>(mFollowSongs[i]); moduleInfo["followsongs"][i] = module->Name(); } } ```
/content/code_sandbox/Source/ControllingSong.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,401
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ValueStream.h Created: 25 Oct 2020 7:09:05pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "Transport.h" #include "Slider.h" #include <array> class PatchCableSource; class ValueStream : public IDrawableModule, public IAudioPoller, public IFloatSliderListener { public: ValueStream(); ~ValueStream(); static IDrawableModule* Create() { return new ValueStream(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; IUIControl* GetUIControl() const { return mUIControl; } void OnTransportAdvanced(float amount) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} //IDrawableModule void Init() override; void Poll() override; bool IsResizable() const override { return true; } void Resize(float w, float h) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void LoadLayout(const ofxJSONElement& moduleInfo) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 1; } //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; IUIControl* mUIControl{ nullptr }; FloatSlider* mFloatSlider{ nullptr }; PatchCableSource* mControlCable{ nullptr }; float mWidth{ 200 }; float mHeight{ 120 }; float mSpeed{ 1 }; FloatSlider* mSpeedSlider{ nullptr }; std::array<float, 100000> mValues{}; int mValueDisplayPointer{ 0 }; }; ```
/content/code_sandbox/Source/ValueStream.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
607
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // EventCanvas.h // Bespoke // // Created by Ryan Challinor on 12/28/15. // // #pragma once #include "Transport.h" #include "Checkbox.h" #include "Canvas.h" #include "Slider.h" #include "ClickButton.h" #include "DropdownList.h" #include "TextEntry.h" class CanvasControls; class PatchCableSource; class CanvasScrollbar; class EventCanvas : public IDrawableModule, public ICanvasListener, public IFloatSliderListener, public IAudioPoller, public IIntSliderListener, public IButtonListener, public IDropdownListener, public ITextEntryListener { public: EventCanvas(); ~EventCanvas(); static IDrawableModule* Create() { return new EventCanvas(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; IUIControl* GetUIControlForRow(int row); ofColor GetRowColor(int row) const; void SetEnabled(bool enabled) override { mEnabled = enabled; } bool IsResizable() const override { return true; } void Resize(float w, float h) override; void OnTransportAdvanced(float amount) override; void CanvasUpdated(Canvas* canvas) override; void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; std::vector<IUIControl*> ControlsToIgnoreInSaveState() const override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void ButtonClicked(ClickButton* button, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void TextEntryComplete(TextEntry* entry) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 0; } bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void UpdateNumColumns(); void SyncControlCablesToCanvas(); double GetTriggerTime(double lookaheadTime, double lookaheadPos, float eventPos); Canvas* mCanvas{ nullptr }; CanvasControls* mCanvasControls{ nullptr }; CanvasScrollbar* mCanvasScrollbarHorizontal{ nullptr }; float mScrollPartial{ 0 }; TextEntry* mNumMeasuresEntry{ nullptr }; int mNumMeasures{ 1 }; ClickButton* mQuantizeButton{ nullptr }; NoteInterval mInterval{ NoteInterval::kInterval_16n }; DropdownList* mIntervalSelector{ nullptr }; float mPosition{ 0 }; std::vector<PatchCableSource*> mControlCables{}; std::vector<ofColor> mRowColors{}; bool mRecord{ false }; Checkbox* mRecordCheckbox{ nullptr }; double mPreviousPosition{ 0 }; struct ControlConnection { IUIControl* mUIControl{ nullptr }; float mLastValue{ 0 }; }; const int kMaxEventRows = 256; std::vector<ControlConnection> mRowConnections; }; ```
/content/code_sandbox/Source/EventCanvas.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
893
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== LooperGranulator.cpp Created: 13 Mar 2021 1:55:54pm Author: Ryan Challinor ============================================================================== */ #include "LooperGranulator.h" #include "ModularSynth.h" #include "Slider.h" #include "PatchCableSource.h" #include "Looper.h" #include "FillSaveDropdown.h" #include "UIControlMacros.h" LooperGranulator::LooperGranulator() { } LooperGranulator::~LooperGranulator() { } void LooperGranulator::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK(3, 3, 120); CHECKBOX(mOnCheckbox, "on", &mOn); FLOATSLIDER(mGranOverlap, "overlap", &mGranulator.mGrainOverlap, .5f, MAX_GRAINS); FLOATSLIDER(mGranSpeed, "speed", &mGranulator.mSpeed, -3, 3); FLOATSLIDER(mGranLengthMs, "len ms", &mGranulator.mGrainLengthMs, 1, 1000); FLOATSLIDER(mPosSlider, "loop pos", &mDummyPos, 0, 1); CHECKBOX(mFreezeCheckbox, "freeze", &mFreeze); FLOATSLIDER(mGranPosRandomize, "pos rand", &mGranulator.mPosRandomizeMs, 0, 200); FLOATSLIDER(mGranSpeedRandomize, "speed rand", &mGranulator.mSpeedRandomize, 0, .3f); FLOATSLIDER(mGranSpacingRandomize, "spacing rand", &mGranulator.mSpacingRandomize, 0, 1); CHECKBOX(mGranOctaveCheckbox, "octaves", &mGranulator.mOctaves); FLOATSLIDER(mGranWidthSlider, "width", &mGranulator.mWidth, 0, 1); ENDUIBLOCK(mWidth, mHeight); mLooperCable = new PatchCableSource(this, kConnectionType_Special); //mLooperCable->SetManualPosition(99, 10); mLooperCable->AddTypeFilter("looper"); AddPatchCableSource(mLooperCable); mGranPosRandomize->SetMode(FloatSlider::kSquare); mGranLengthMs->SetMode(FloatSlider::kSquare); } void LooperGranulator::DrawModule() { if (Minimized() || IsVisible() == false) return; if (mLooper != nullptr) mPosSlider->SetExtents(0, mLooper->GetLoopLength()); mOnCheckbox->Draw(); mGranOverlap->Draw(); mGranSpeed->Draw(); mGranLengthMs->Draw(); mPosSlider->Draw(); mFreezeCheckbox->Draw(); mGranPosRandomize->Draw(); mGranSpeedRandomize->Draw(); mGranSpacingRandomize->Draw(); mGranOctaveCheckbox->Draw(); mGranWidthSlider->Draw(); } void LooperGranulator::DrawOverlay(ofRectangle bufferRect, int loopLength) { if (mOn) mGranulator.Draw(bufferRect.x, bufferRect.y, bufferRect.width, bufferRect.height, 0, loopLength, loopLength); } void LooperGranulator::ProcessFrame(double time, float bufferOffset, float* output) { if (mLooper != nullptr) { int bufferLength; auto* buffer = mLooper->GetLoopBuffer(bufferLength); mGranulator.ProcessFrame(time, buffer, bufferLength, bufferOffset, output); } } void LooperGranulator::OnCommit() { mOn = false; mFreeze = false; if (mPosSlider->GetLFO()) mPosSlider->GetLFO()->SetLFOEnabled(false); } void LooperGranulator::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { if (cableSource == mLooperCable) { mLooper = dynamic_cast<Looper*>(mLooperCable->GetTarget()); if (mLooper != nullptr) { mLooper->SetGranulator(this); mPosSlider->SetVar(mLooper->GetLoopPosVar()); } } } void LooperGranulator::ButtonClicked(ClickButton* button, double time) { } void LooperGranulator::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void LooperGranulator::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void LooperGranulator::SaveLayout(ofxJSONElement& moduleInfo) { std::string targetPath = ""; if (mLooperCable->GetTarget()) targetPath = mLooperCable->GetTarget()->Path(); moduleInfo["looper"] = targetPath; } void LooperGranulator::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("looper", moduleInfo, "", FillDropdown<Looper*>); SetUpFromSaveData(); } void LooperGranulator::SetUpFromSaveData() { mLooperCable->SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("looper"), false)); } ```
/content/code_sandbox/Source/LooperGranulator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,235
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== TransposeFrom.h Created: 14 Jul 2021 7:47:48pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "DropdownList.h" #include "Scale.h" class TransposeFrom : public NoteEffectBase, public IDrawableModule, public IDropdownListener, public IScaleListener { public: TransposeFrom(); virtual ~TransposeFrom(); static IDrawableModule* Create() { return new TransposeFrom(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; //IScaleListener void OnScaleChanged() override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: struct NoteInfo { bool mOn{ false }; int mVelocity{ 0 }; int mVoiceIdx{ -1 }; int mOutputPitch{ 0 }; }; //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } int GetTransposeAmount() const; void OnRootChanged(double time); float mWidth{ 200 }; float mHeight{ 20 }; int mRoot{ 0 }; DropdownList* mRootSelector{ nullptr }; std::array<NoteInfo, 128> mInputNotes{}; Checkbox* mRetriggerCheckbox{ nullptr }; bool mRetrigger{ false }; }; ```
/content/code_sandbox/Source/TransposeFrom.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
589
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // FloatSliderLFOControl.cpp // modularSynth // // Created by Ryan Challinor on 2/22/13. // // #include "FloatSliderLFOControl.h" #include "Slider.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "UIControlMacros.h" FloatSliderLFOControl::FloatSliderLFOControl() { mLFOSettings.mInterval = kInterval_1n; mLFOSettings.mOscType = kOsc_Sin; mLFOSettings.mLFOOffset = 0; mLFOSettings.mBias = .5f; mLFOSettings.mSpread = 0; mLFOSettings.mSoften = 0; mLFOSettings.mShuffle = 0; mLFOSettings.mFreeRate = 1; mLFO.SetPeriod(mLFOSettings.mInterval); } void FloatSliderLFOControl::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); CHECKBOX(mEnableLFOCheckbox, "enable", &mEnabled); UIBLOCK_SHIFTRIGHT(); BUTTON(mPinButton, "pin"); UIBLOCK_NEWLINE(); UIBLOCK_SHIFTY(40); DROPDOWN(mIntervalSelector, "interval", reinterpret_cast<int*>(&mLFOSettings.mInterval), 47); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mOscSelector, "osc", reinterpret_cast<int*>(&mLFOSettings.mOscType), 47); UIBLOCK_NEWLINE(); FLOATSLIDER(mOffsetSlider, "offset", &mLFOSettings.mLFOOffset, 0, 1); UIBLOCK_SHIFTUP(); FLOATSLIDER(mFreeRateSlider, "free rate", &mLFOSettings.mFreeRate, 0, 20); FLOATSLIDER(mMinSlider, "low", &mDummyMin, 0, 1); FLOATSLIDER(mMaxSlider, "high", &mDummyMax, 0, 1); FLOATSLIDER(mSpreadSlider, "spread", &mLFOSettings.mSpread, 0, 1); FLOATSLIDER(mBiasSlider, "bias", &mLFOSettings.mBias, 0, 1); FLOATSLIDER(mLengthSlider, "length", &mLFOSettings.mLength, 0, 1); FLOATSLIDER(mShuffleSlider, "shuffle", &mLFOSettings.mShuffle, 0, 1); FLOATSLIDER(mSoftenSlider, "soften", &mLFOSettings.mSoften, 0, 1); CHECKBOX(mLowResModeCheckbox, "lite cpu", &mLFOSettings.mLowResMode); ENDUIBLOCK(mWidth, mHeight); mIntervalSelector->AddLabel("free", kInterval_Free); mIntervalSelector->AddLabel("64", kInterval_64); mIntervalSelector->AddLabel("32", kInterval_32); mIntervalSelector->AddLabel("16", kInterval_16); mIntervalSelector->AddLabel("8", kInterval_8); mIntervalSelector->AddLabel("4", kInterval_4); mIntervalSelector->AddLabel("3", kInterval_3); mIntervalSelector->AddLabel("2", kInterval_2); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("2nt", kInterval_2nt); mIntervalSelector->AddLabel("4nd", kInterval_4nd); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("8nd", kInterval_8nd); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("16nd", kInterval_16nd); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("32n", kInterval_32n); mIntervalSelector->AddLabel("32nt", kInterval_32nt); mIntervalSelector->AddLabel("64n", kInterval_64n); mOscSelector->AddLabel("sin", kOsc_Sin); mOscSelector->AddLabel("saw", kOsc_Saw); mOscSelector->AddLabel("-saw", kOsc_NegSaw); mOscSelector->AddLabel("squ", kOsc_Square); mOscSelector->AddLabel("tri", kOsc_Tri); mOscSelector->AddLabel("s&h", kOsc_Random); mOscSelector->AddLabel("drunk", kOsc_Drunk); mOscSelector->AddLabel("perlin", kOsc_Perlin); mOscSelector->PositionTo(mIntervalSelector, kAnchor_Right); mFreeRateSlider->SetMode(FloatSlider::kBezier); mFreeRateSlider->SetBezierControl(1); UpdateVisibleControls(); } FloatSliderLFOControl::~FloatSliderLFOControl() = default; void FloatSliderLFOControl::DrawModule() { /*if (!mPinned) { float w, h; GetDimensions(w, h); ofPushStyle(); ofSetColor(0, 0, 0); ofFill(); ofSetLineWidth(.5f); ofRect(0, 0, w, h); ofNoFill(); ofSetColor(255, 255, 255); ofRect(0, 0, w, h); ofPopStyle(); }*/ if (Minimized()) return; mEnableLFOCheckbox->Draw(); mIntervalSelector->Draw(); mOscSelector->Draw(); mOffsetSlider->Draw(); mBiasSlider->Draw(); mFreeRateSlider->Draw(); mMinSlider->Draw(); mMaxSlider->Draw(); mSpreadSlider->Draw(); mSoftenSlider->Draw(); mShuffleSlider->Draw(); mLengthSlider->Draw(); mLowResModeCheckbox->Draw(); if (!mPinned) mPinButton->Draw(); int x = 5; int y = 20; int height = 35; int width = 90; ofSetColor(100, 100, .8f * gModuleDrawAlpha); ofSetLineWidth(.5f); ofRect(x, y, width, height, 0); ofSetColor(245, 58, 0, gModuleDrawAlpha); ofSetLineWidth(1); ofBeginShape(); for (float i = 0; i < width; i += (.25f / gDrawScale)) { float phase = i / width; if (mLFO.GetOsc()->GetShuffle() > 0) phase *= 2; if (mLFO.GetOsc()->GetType() != kOsc_Perlin) phase += 1 - mLFOSettings.mLFOOffset; float value = GetLFOValue(0, mLFO.TransformPhase(phase)); ofVertex(i + x, ofMap(value, GetTargetMax(), GetTargetMin(), 0, height) + y); } ofEndShape(false); float currentPhase = mLFO.CalculatePhase(0, false); float squeeze; if (mLFO.GetOsc()->GetShuffle() == 0) { squeeze = 1; currentPhase -= (int)currentPhase; } else { squeeze = 2; } if (mLFO.GetOsc()->GetType() == kOsc_Perlin) currentPhase = 0; float displayPhase = currentPhase; displayPhase -= 1 - mLFOSettings.mLFOOffset; if (displayPhase < 0) displayPhase += squeeze; ofCircle(displayPhase / squeeze * width + x, ofMap(GetLFOValue(0, mLFO.TransformPhase(currentPhase)), GetTargetMax(), GetTargetMin(), 0, height) + y, 2); } bool FloatSliderLFOControl::DrawToPush2Screen() { FloatSlider* slider = GetOwner(); if (slider) { ofRectangle rect(30, -12, 100, 11); ofSetColor(100, 100, 100); ofRect(rect); float screenPos = rect.x + 1 + (rect.width - 2) * slider->ValToPos(slider->GetValue(), true); float lfomax = ofClamp(GetMax(), slider->GetMin(), slider->GetMax()); float screenPosMax = rect.x + 1 + (rect.width - 2) * slider->ValToPos(lfomax, true); float lfomin = ofClamp(GetMin(), slider->GetMin(), slider->GetMax()); float screenPosMin = rect.x + 1 + (rect.width - 2) * slider->ValToPos(lfomin, true); ofPushStyle(); ofSetColor(0, 200, 0); ofFill(); if (fabs(screenPos - screenPosMin) > 1) ofRect(screenPosMin, rect.y, screenPos - screenPosMin, rect.height, 1); //lfo bar ofPopStyle(); ofPushStyle(); ofSetColor(0, 255, 0); ofSetLineWidth(2); ofLine(screenPosMin, rect.y + 1, screenPosMin, rect.getMaxY() - 1); //min bar ofLine(screenPosMax, rect.y + 1, screenPosMax, rect.getMaxY() - 1); //max bar ofPopStyle(); } return false; } void FloatSliderLFOControl::SetLFOEnabled(bool enabled) { if (enabled && !mEnabled && !TheSynth->IsLoadingState()) //if turning on { if (GetSliderTarget()) { GetMin() = GetSliderTarget()->GetValue(); GetMax() = GetSliderTarget()->GetValue(); } } mEnabled = enabled; } void FloatSliderLFOControl::SetOwner(FloatSlider* owner) { if (GetSliderTarget() == owner) return; if (GetSliderTarget() != nullptr) { GetSliderTarget()->SetLFO(nullptr); } if (owner != nullptr) owner->SetLFO(this); mTargets[0].mSliderTarget = owner; mTargets[0].mUIControlTarget = owner; if (GetSliderTarget() != nullptr) InitializeRange(GetSliderTarget()->GetValue(), GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax(), GetSliderTarget()->GetMode()); } void FloatSliderLFOControl::RandomizeSettings() { switch (gRandom() % 8) { case 0: mLFOSettings.mInterval = kInterval_2; break; case 1: mLFOSettings.mInterval = kInterval_1n; break; case 2: mLFOSettings.mInterval = kInterval_2n; break; case 3: mLFOSettings.mInterval = kInterval_4n; break; case 4: mLFOSettings.mInterval = kInterval_4nt; break; case 5: mLFOSettings.mInterval = kInterval_8n; break; case 6: mLFOSettings.mInterval = kInterval_8nt; break; case 7: default: mLFOSettings.mInterval = kInterval_Free; mLFOSettings.mFreeRate = ofRandom(.1f, 20); break; } UpdateFromSettings(); UpdateVisibleControls(); } void FloatSliderLFOControl::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { if (mTargetCable == nullptr) return; if (GetSliderTarget() != mTargetCable->GetTarget() || mTargetCable->GetTarget() == nullptr) SetOwner(dynamic_cast<FloatSlider*>(mTargetCable->GetTarget())); OnModulatorRepatch(); } void FloatSliderLFOControl::Load(LFOSettings settings) { mLFOSettings = settings; UpdateFromSettings(); mEnabled = true; } float FloatSliderLFOControl::Value(int samplesIn /*= 0*/) { ComputeSliders(samplesIn); return GetLFOValue(samplesIn); } float FloatSliderLFOControl::GetLFOValue(int samplesIn /*= 0*/, float forcePhase /*= -1*/) { float val = mLFO.Value(samplesIn, forcePhase); if (mLFOSettings.mSpread > 0) val = val * (1 - mLFOSettings.mSpread) + (-cosf(val * FPI) + 1) * .5f * mLFOSettings.mSpread; return ofClamp(Interp(val, GetMin(), GetMax()), GetTargetMin(), GetTargetMax()); } float FloatSliderLFOControl::GetTargetMin() const { if (GetSliderTarget() != nullptr) return GetSliderTarget()->GetMin(); else if (mMinSlider != nullptr) return mMinSlider->GetMin(); return 0; } float FloatSliderLFOControl::GetTargetMax() const { if (GetSliderTarget() != nullptr) return GetSliderTarget()->GetMax(); else if (mMaxSlider != nullptr) return mMaxSlider->GetMax(); return 1; } void FloatSliderLFOControl::UpdateFromSettings() { mLFO.SetPeriod(mLFOSettings.mInterval); mLFO.SetType(mLFOSettings.mOscType); mLFO.SetOffset(mLFOSettings.mLFOOffset); mLFO.SetPulseWidth(1 - mLFOSettings.mBias); mLFO.GetOsc()->SetSoften(mLFOSettings.mSoften); mLFO.GetOsc()->SetShuffle(mLFOSettings.mShuffle); mLFO.SetFreeRate(mLFOSettings.mFreeRate); } void FloatSliderLFOControl::UpdateVisibleControls() { bool isPerlin = mLFO.GetOsc()->GetType() == kOsc_Perlin; bool isDrunk = mLFO.GetOsc()->GetType() == kOsc_Drunk; bool isRandom = mLFO.GetOsc()->GetType() == kOsc_Random; bool showFreeRate = mLFOSettings.mInterval == kInterval_Free || isPerlin; mOffsetSlider->SetShowing(!showFreeRate && !isDrunk && !isRandom); mFreeRateSlider->SetShowing(showFreeRate); mIntervalSelector->SetShowing(!isPerlin); mShuffleSlider->SetShowing(!isPerlin && !isDrunk && !isRandom); mSoftenSlider->SetShowing(mLFO.GetOsc()->GetType() == kOsc_Saw || mLFO.GetOsc()->GetType() == kOsc_Square || mLFO.GetOsc()->GetType() == kOsc_NegSaw || isRandom); mSpreadSlider->SetShowing(mLFO.GetOsc()->GetType() != kOsc_Square); mLengthSlider->SetShowing(!isPerlin && !isDrunk && !isRandom); } void FloatSliderLFOControl::SetRate(NoteInterval rate) { mLFOSettings.mInterval = rate; mLFO.SetPeriod(mLFOSettings.mInterval); } void FloatSliderLFOControl::DoSpecialDelete() { mEnabled = false; mPinned = false; } void FloatSliderLFOControl::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { } void FloatSliderLFOControl::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { if (mLFOSettings.mInterval == kInterval_Free) { NoteInterval oldInterval = (NoteInterval)oldVal; mLFOSettings.mFreeRate = 1000 / TheTransport->GetDuration(oldInterval); mLFO.SetFreeRate(mLFOSettings.mFreeRate); } mLFO.SetPeriod(mLFOSettings.mInterval); UpdateVisibleControls(); } if (list == mOscSelector) { mLFO.SetType(mLFOSettings.mOscType); UpdateVisibleControls(); if (mLFOSettings.mOscType == kOsc_Random) { mLFOSettings.mShuffle = 0; mLFO.GetOsc()->SetShuffle(0); } if (mLFOSettings.mOscType == kOsc_Perlin) { mLFOSettings.mShuffle = 0; mLFOSettings.mLFOOffset = 0; mLFOSettings.mLength = 1; mLFO.SetLength(1); mLFO.GetOsc()->SetShuffle(0); mLFO.SetOffset(0); } } } void FloatSliderLFOControl::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mOffsetSlider) mLFO.SetOffset(mLFOSettings.mLFOOffset); if (slider == mBiasSlider) mLFO.SetPulseWidth(1 - mLFOSettings.mBias); if (slider == mSoftenSlider) mLFO.GetOsc()->SetSoften(mLFOSettings.mSoften); if (slider == mShuffleSlider) mLFO.GetOsc()->SetShuffle(mLFOSettings.mShuffle); if (slider == mFreeRateSlider) mLFO.SetFreeRate(mLFOSettings.mFreeRate); if (slider == mLengthSlider) mLFO.SetLength(mLFOSettings.mLength); } void FloatSliderLFOControl::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { mEnabled = !mEnabled; SetLFOEnabled(!mEnabled); //make sure it sets as a toggle } } void FloatSliderLFOControl::ButtonClicked(ClickButton* button, double time) { if (button == mPinButton) { if (!mPinned) { mPinned = true; TheSynth->AddDynamicModule(this); TheSynth->PopModalFocusItem(); SetName(GetUniqueName("lfo", TheSynth->GetModuleNames<FloatSliderLFOControl*>()).c_str()); if (mTargetCable == nullptr) { mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); mTargetCable->SetTarget(GetSliderTarget()); } } } } void FloatSliderLFOControl::SaveLayout(ofxJSONElement& moduleInfo) { } void FloatSliderLFOControl::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); // Since `mPinned` is set after `IDrawableModule::LoadBasics` we need to manually set minimized // after setting `mPinned` which is used to check if this module has a titlebar. SetMinimized(moduleInfo["start_minimized"].asBool(), false); } void FloatSliderLFOControl::SetUpFromSaveData() { mPinned = true; //only pinned sliders get saved UpdateFromSettings(); UpdateVisibleControls(); if (mTargetCable == nullptr) { mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } } FloatSliderLFOControl* LFOPool::sLFOPool[LFO_POOL_SIZE]; int LFOPool::sNextLFOIndex = 0; bool LFOPool::sInitialized = false; void LFOPool::Init() { for (int i = 0; i < LFO_POOL_SIZE; ++i) { sLFOPool[i] = new FloatSliderLFOControl(); sLFOPool[i]->CreateUIControls(); sLFOPool[i]->Init(); sLFOPool[i]->SetTypeName("lfo", kModuleCategory_Modulator); sLFOPool[i]->SetLFOEnabled(false); } sInitialized = true; } void LFOPool::Shutdown() { if (sInitialized) { for (int i = 0; i < LFO_POOL_SIZE; ++i) sLFOPool[i]->Delete(); sInitialized = false; } } FloatSliderLFOControl* LFOPool::GetLFO(FloatSlider* owner) { int index = sNextLFOIndex; for (int i = 0; i < LFO_POOL_SIZE; ++i) //search for the next one that isn't enabled, but only one loop around { if (!sLFOPool[index]->IsEnabled() && !sLFOPool[index]->IsPinned()) break; //found a disabled one index = (index + 1) % LFO_POOL_SIZE; } sNextLFOIndex = (index + 1) % LFO_POOL_SIZE; if (sLFOPool[index]->GetOwner()) sLFOPool[index]->GetOwner()->SetLFO(nullptr); //revoke LFO sLFOPool[index]->RandomizeSettings(); sLFOPool[index]->SetOwner(owner); return sLFOPool[index]; } namespace { const int kSaveStateRev = 5; const int kFixNonRevvedData = 999; } void LFOSettings::SaveState(FileStreamOut& out) const { out << kFixNonRevvedData; out << kSaveStateRev; out << (int)mInterval; out << (int)mOscType; out << mLFOOffset; out << mBias; out << mSpread; out << mSoften; out << mShuffle; out << mFreeRate; out << mLength; out << mLowResMode; } void LFOSettings::LoadState(FileStreamIn& in) { int rev = 0; int temp; in >> temp; if (temp == kFixNonRevvedData) //hack to fix data that I didn't revision { in >> rev; LoadStateValidate(rev <= kSaveStateRev); in >> temp; } mInterval = (NoteInterval)temp; in >> temp; mOscType = (OscillatorType)temp; in >> mLFOOffset; in >> mBias; if (rev >= 1) in >> mSpread; if (rev >= 2) { in >> mSoften; in >> mShuffle; } if (rev >= 3) in >> mFreeRate; if (rev >= 4) in >> mLength; if (rev >= 5) in >> mLowResMode; } ```
/content/code_sandbox/Source/FloatSliderLFOControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,206
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // FillSaveDropdown.h // Bespoke // // Created by Ryan Challinor on 2/23/15. // // #pragma once #include "ModularSynth.h" #include "DropdownList.h" template <class T> void FillDropdown(DropdownList* list) { assert(list); std::vector<std::string> modules = TheSynth->GetModuleNames<T>(); list->AddLabel("", -1); for (int i = 0; i < modules.size(); ++i) list->AddLabel(modules[i].c_str(), i); } ```
/content/code_sandbox/Source/FillSaveDropdown.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
222
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // JumpBlender.cpp // modularSynth // // Created by Ryan Challinor on 11/1/13. // // #include "JumpBlender.h" #include "SynthGlobals.h" #include "Profiler.h" JumpBlender::JumpBlender() { } void JumpBlender::CaptureForJump(int pos, const float* sampleSource, int sourceLength, int samplesIn) { assert(pos < sourceLength); mBlending = true; mBlendSample = 0; if (pos + JUMP_BLEND_SAMPLES <= sourceLength) { BufferCopy((float*)mSamples, sampleSource + pos, JUMP_BLEND_SAMPLES); } else { int samplesLeft = sourceLength - pos; BufferCopy(mSamples, sampleSource + pos, samplesLeft); BufferCopy(mSamples + samplesLeft, sampleSource, (JUMP_BLEND_SAMPLES - samplesLeft)); } double time = gTime + samplesIn * gInvSampleRateMs; mRamp.Start(time, 1, 0, time + JUMP_BLEND_SAMPLES * gInvSampleRateMs); } float JumpBlender::Process(float sample, int samplesIn) { if (mBlendSample == JUMP_BLEND_SAMPLES) mBlending = false; if (!mBlending) return sample; float rampVal = mRamp.Value(gTime + samplesIn * gInvSampleRateMs); return sample * (1 - rampVal) + mSamples[mBlendSample++] * rampVal; } ```
/content/code_sandbox/Source/JumpBlender.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
422
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // VSTScanner.h // Bespoke // // Created by Ryan Challinor on 10/16/21. // // #pragma once #include "WindowCloseListener.h" #include "juce_audio_processors/juce_audio_processors.h" constexpr const char* kScanProcessUID = "bespokesynth"; constexpr const char* kScanModeKey = "pluginScanMode"; class CustomPluginScanner : public juce::KnownPluginList::CustomScanner, private juce::ChangeListener { public: CustomPluginScanner(); ~CustomPluginScanner() override; bool findPluginTypesFor(juce::AudioPluginFormat& format, juce::OwnedArray<juce::PluginDescription>& result, const juce::String& fileOrIdentifier) override; void scanFinished() override { superprocess = nullptr; } private: class Superprocess : public juce::ChildProcessCoordinator { public: explicit Superprocess(CustomPluginScanner& o); private: void handleMessageFromWorker(const juce::MemoryBlock& mb) override; void handleConnectionLost() override; CustomPluginScanner& owner; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(Superprocess) }; void changeListenerCallback(juce::ChangeBroadcaster*) override; std::unique_ptr<Superprocess> superprocess; std::mutex mutex; std::condition_variable condvar; std::unique_ptr<juce::XmlElement> pluginDescription; bool gotResponse = false; bool connectionLost = false; std::atomic<bool> scanWithExternalProcess{ true }; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CustomPluginScanner) }; //============================================================================== class CustomPluginListComponent : public juce::PluginListComponent { public: CustomPluginListComponent(juce::AudioPluginFormatManager& manager, juce::KnownPluginList& listToRepresent, const juce::File& pedal, juce::PropertiesFile* props, bool async); void OnResize(); private: juce::Label validationModeLabel{ {}, "Scan mode" }; juce::ComboBox validationModeBox; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CustomPluginListComponent) }; class PluginListWindow : public juce::DocumentWindow { public: PluginListWindow(juce::AudioPluginFormatManager& pluginFormatManager, WindowCloseListener* listener); ~PluginListWindow() override; void resized() override; void closeButtonPressed() override; private: WindowCloseListener* mListener; CustomPluginListComponent* mComponent; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginListWindow) }; class PluginScannerSubprocess : private juce::ChildProcessWorker, private juce::AsyncUpdater { public: PluginScannerSubprocess(); using juce::ChildProcessWorker::initialiseFromCommandLine; private: void handleMessageFromCoordinator(const juce::MemoryBlock& mb) override; void handleConnectionLost() override; // It's important to run the plugin scan on the main thread! void handleAsyncUpdate() override; juce::AudioPluginFormatManager formatManager; std::mutex mutex; std::queue<juce::MemoryBlock> pendingBlocks; }; ```
/content/code_sandbox/Source/VSTScanner.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
791
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== AudioSend.cpp Created: 22 Oct 2017 1:23:40pm Author: Ryan Challinor ============================================================================== */ #include "AudioSend.h" #include "ModularSynth.h" #include "Profiler.h" #include "PatchCableSource.h" #include "Checkbox.h" AudioSend::AudioSend() : IAudioProcessor(gBufferSize) , mVizBuffer2(VIZ_BUFFER_SECONDS * gSampleRate) { } void AudioSend::CreateUIControls() { IDrawableModule::CreateUIControls(); mAmountSlider = new FloatSlider(this, "amount", 3, 3, 80, 15, &mAmount, 0, 1, 2); mCrossfadeCheckbox = new Checkbox(this, "crossfade", mAmountSlider, kAnchor_Below, &mCrossfade); float w, h; GetDimensions(w, h); GetPatchCableSource()->SetManualPosition(w / 2 - 15, h + 3); GetPatchCableSource()->SetManualSide(PatchCableSource::Side::kBottom); mPatchCableSource2 = new PatchCableSource(this, kConnectionType_Audio); mPatchCableSource2->SetManualPosition(w / 2 + 15, h + 3); mPatchCableSource2->SetOverrideVizBuffer(&mVizBuffer2); mPatchCableSource2->SetManualSide(PatchCableSource::Side::kBottom); AddPatchCableSource(mPatchCableSource2); } AudioSend::~AudioSend() { } void AudioSend::Process(double time) { PROFILER(AudioSend); IAudioReceiver* target0 = GetTarget(0); IAudioReceiver* target1 = GetTarget(1); if (target0 == nullptr && target1 == nullptr) return; SyncBuffers(); if (!mEnabled) { if (target0) for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(target0->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch); } GetBuffer()->Reset(); return; } ComputeSliders(0); mVizBuffer2.SetNumChannels(GetBuffer()->NumActiveChannels()); float* amountBuffer = gWorkBuffer; float* dryAmountBuffer = gWorkBuffer + gBufferSize; for (int i = 0; i < gBufferSize; ++i) { ComputeSliders(i); amountBuffer[i] = mAmount; dryAmountBuffer[i] = 1 - mAmount; } if (target0) { gWorkChannelBuffer.CopyFrom(GetBuffer(), GetBuffer()->BufferSize()); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { ChannelBuffer* out = target0->GetBuffer(); if (mCrossfade) Mult(gWorkChannelBuffer.GetChannel(ch), dryAmountBuffer, GetBuffer()->BufferSize()); Add(out->GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(gWorkChannelBuffer.GetChannel(ch), GetBuffer()->BufferSize(), ch); } } if (target1) { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { ChannelBuffer* out2 = target1->GetBuffer(); Mult(GetBuffer()->GetChannel(ch), amountBuffer, GetBuffer()->BufferSize()); Add(out2->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); mVizBuffer2.WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch); } } GetBuffer()->Reset(); } void AudioSend::DrawModule() { if (Minimized() || IsVisible() == false) return; mAmountSlider->Draw(); mCrossfadeCheckbox->Draw(); } void AudioSend::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void AudioSend::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("target2", moduleInfo); SetUpFromSaveData(); } void AudioSend::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); IClickable* target2 = TheSynth->FindModule(mModuleSaveData.GetString("target2")); if (target2) mPatchCableSource2->AddPatchCable(target2); } ```
/content/code_sandbox/Source/AudioSend.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,129
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Curve.h // Bespoke // // Created by Ryan Challinor on 3/5/16. // // #pragma once #include "OpenFrameworksPort.h" #include "IClickable.h" class FileStreamOut; class FileStreamIn; struct CurvePoint { public: CurvePoint() {} CurvePoint(float time, float value) : mTime(time) , mValue(value) {} float mTime{ 0 }; float mValue{ 0 }; }; class Curve : public IClickable { public: Curve(float defaultValue); void AddPoint(CurvePoint point); void AddPointAtEnd(CurvePoint point); //only use this if you are sure that there are no points already added at an earlier time float Evaluate(float time, bool holdEndForLoop = false); void Render() override; void SetExtents(float start, float end) { mStart = start; mEnd = end; } void SetColor(ofColor color) { mColor = color; } void GetDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void SetDimensions(float width, float height) { mWidth = width; mHeight = height; } void Clear(); int GetNumPoints() const { return mNumCurvePoints; } CurvePoint* GetPoint(int index); void SaveState(FileStreamOut& out); void LoadState(FileStreamIn& in); protected: void OnClicked(float x, float y, bool right) override; bool MouseMoved(float x, float y) override; bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override; private: bool IsAtCapacity() { return mNumCurvePoints >= (int)mPoints.size(); } int FindIndexForTime(float time); std::array<CurvePoint, 5000> mPoints; int mNumCurvePoints{ 0 }; float mWidth{ 200 }; float mHeight{ 20 }; float mStart{ 0 }; float mEnd{ 1 }; ofColor mColor{ ofColor::white }; int mLastEvalIndex{ 0 }; float mDefaultValue{ 0 }; }; ```
/content/code_sandbox/Source/Curve.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
600
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ModulatorSubtract.h Created: 9 Dec 2019 10:11:32pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "Slider.h" #include "IModulator.h" class PatchCableSource; class ModulatorSubtract : public IDrawableModule, public IFloatSliderListener, public IModulator { public: ModulatorSubtract(); virtual ~ModulatorSubtract(); static IDrawableModule* Create() { return new ModulatorSubtract(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; //IModulator float Value(int samplesIn = 0) override; bool Active() const override { return mEnabled; } bool CanAdjustRange() const override { return false; } FloatSlider* GetTarget() { return GetSliderTarget(); } //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 106; h = 17 * 2 + 4; } float mValue1{ 0 }; float mValue2{ 0 }; FloatSlider* mValue1Slider{ nullptr }; FloatSlider* mValue2Slider{ nullptr }; }; ```
/content/code_sandbox/Source/ModulatorSubtract.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
532
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteSinger.h // modularSynth // // Created by Ryan Challinor on 5/23/13. // // #pragma once #include <iostream> #include "IAudioReceiver.h" #include "INoteSource.h" #include "Slider.h" #include "IDrawableModule.h" #include "RadioButton.h" #include "ClickButton.h" #include "Transport.h" #include "BiquadFilter.h" #include "PeakTracker.h" #include "Scale.h" #define NOTESINGER_MAX_BUCKETS 40 class NoteSinger : public IAudioReceiver, public INoteSource, public IIntSliderListener, public IFloatSliderListener, public IDrawableModule, public IRadioButtonListener, public IButtonListener, public IAudioPoller, public IScaleListener { public: NoteSinger(); ~NoteSinger(); static IDrawableModule* Create() { return new NoteSinger(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; //IAudioReceiver InputMode GetInputMode() override { return kInputMode_Mono; } //IAudioPoller void OnTransportAdvanced(float amount) override; //IScaleListener void OnScaleChanged() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void CheckboxUpdated(Checkbox* checkbox, double time) override; //IIntSliderListener void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {} //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} //IRadioButtonListener void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override {} //IButtonListener void ButtonClicked(ClickButton* button, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 100; height = 50; } int GetPitchForBucket(int bucket); int mOctave{ 0 }; IntSlider* mOctaveSlider{ nullptr }; int mPitch{ 0 }; float* mWorkBuffer{ nullptr }; int mNumBuckets{ 28 }; BiquadFilter mBands[NOTESINGER_MAX_BUCKETS]; PeakTracker mPeaks[NOTESINGER_MAX_BUCKETS]; }; ```
/content/code_sandbox/Source/NoteSinger.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
698
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== SamplePlayer.cpp Created: 19 Oct 2017 10:10:15pm Author: Ryan Challinor ============================================================================== */ #include "SamplePlayer.h" #include "IAudioReceiver.h" #include "Sample.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "PatchCableSource.h" #include "Scale.h" #include "UIControlMacros.h" #include "UserPrefs.h" #include "juce_gui_basics/juce_gui_basics.h" #include "juce_audio_formats/juce_audio_formats.h" using namespace juce; namespace { const int kRecordingChunkSize = 48000 * 5; const int kMinRecordingChunks = 2; }; SamplePlayer::SamplePlayer() : IAudioProcessor(gBufferSize) , mNoteInputBuffer(this) { mYoutubeSearch[0] = 0; } void SamplePlayer::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mVolumeSlider, "volume", &mVolume, 0, 2); UIBLOCK_SHIFTRIGHT(); FLOATSLIDER(mSpeedSlider, "speed", &mSpeed, -2, 2); UIBLOCK_SHIFTRIGHT(); BUTTON(mTrimToZoomButton, "trim"); UIBLOCK_SHIFTRIGHT(); BUTTON(mDownloadYoutubeButton, "youtube"); UIBLOCK_NEWLINE(); TEXTENTRY(mDownloadYoutubeSearch, "yt:", 30, mYoutubeSearch); UIBLOCK_NEWLINE(); mDownloadYoutubeSearch->DrawLabel(true); mDownloadYoutubeSearch->SetRequireEnter(true); BUTTON_STYLE(mPlayButton, "play", ButtonDisplayStyle::kPlay); UIBLOCK_SHIFTRIGHT(); BUTTON_STYLE(mPauseButton, "pause", ButtonDisplayStyle::kPause); UIBLOCK_SHIFTRIGHT(); BUTTON_STYLE(mStopButton, "stop", ButtonDisplayStyle::kStop); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mLoopCheckbox, "loop", &mLoop); UIBLOCK_SHIFTRIGHT(); UIBLOCK_SHIFTX(30); BUTTON(mLoadFileButton, "load"); UIBLOCK_SHIFTRIGHT(); BUTTON(mSaveFileButton, "save"); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mRecordCheckbox, "record", &mRecord); UIBLOCK_NEWCOLUMN(); FLOATSLIDER_DIGITS(mCuePointStartSlider, "cue start", &mSampleCuePoints[0].startSeconds, 0, 100, 3); FLOATSLIDER_DIGITS(mCuePointLengthSlider, "cue len", &mSampleCuePoints[0].lengthSeconds, 0, 100, 3); FLOATSLIDER(mCuePointSpeedSlider, "cue speed", &mSampleCuePoints[0].speed, 0, 2); UIBLOCK_NEWCOLUMN(); DROPDOWN(mCuePointSelector, "cuepoint", &mActiveCuePointIndex, 40); BUTTON(mPlayCurrentCuePointButton, "play cue"); CHECKBOX(mCuePointStopCheckbox, "cue stop", &mSampleCuePoints[0].stopOnNoteOff); UIBLOCK_NEWCOLUMN(); CHECKBOX(mSelectPlayedCuePointCheckbox, "select played", &mSelectPlayedCuePoint); CHECKBOX(mSetCuePointCheckbox, "click sets cue", &mSetCuePoint); BUTTON(mAutoSlice4, "4"); UIBLOCK_SHIFTRIGHT(); BUTTON(mAutoSlice8, "8"); UIBLOCK_SHIFTRIGHT(); BUTTON(mAutoSlice16, "16"); UIBLOCK_SHIFTRIGHT(); BUTTON(mAutoSlice32, "32"); UIBLOCK_SHIFTX(-45); UIBLOCK_NEWCOLUMN(); CHECKBOX(mShowGridCheckbox, "show grid", &mShowGrid); CHECKBOX(mRecordingAppendModeCheckbox, "append to rec", &mRecordingAppendMode) CHECKBOX(mRecordAsClipsCheckbox, "record as clips", &mRecordAsClips); ENDUIBLOCK0(); UIBLOCK(0, 65); for (size_t i = 0; i < mSearchResultButtons.size(); ++i) { BUTTON(mSearchResultButtons[i], ("searchresult" + ofToString(i)).c_str()); mSearchResultButtons[i]->SetShowing(false); } ENDUIBLOCK0(); mPlayHoveredClipButton = new ClickButton(this, "playhovered", -1, -1, ButtonDisplayStyle::kPlay); mGrabHoveredClipButton = new ClickButton(this, "grabhovered", -1, -1, ButtonDisplayStyle::kGrabSample); mPlayHoveredClipButton->SetShowing(false); mGrabHoveredClipButton->SetShowing(false); for (int i = 0; i < (int)mSampleCuePoints.size(); ++i) mCuePointSelector->AddLabel(ofToString(i).c_str(), i); AddChild(&mRecordGate); mRecordGate.SetPosition(mRecordAsClipsCheckbox->GetRect().getMaxX() + 3, -1); mRecordGate.SetEnabled(mRecordAsClips); mRecordGate.SetAttack(1); mRecordGate.SetRelease(100); mRecordGate.SetName("gate"); mRecordGate.CreateUIControls(); } SamplePlayer::~SamplePlayer() { if (mOwnsSample) delete mSample; for (size_t i = 0; i < mRecordChunks.size(); ++i) delete mRecordChunks[i]; } void SamplePlayer::Init() { IDrawableModule::Init(); if (OSCReceiver::connect(12345)) OSCReceiver::addListener(this); } void SamplePlayer::Poll() { IDrawableModule::Poll(); const juce::String& clipboard = TheSynth->GetTextFromClipboard(); if (clipboard.contains("youtube")) { juce::String clipId = clipboard.substring(clipboard.indexOf("v=") + 2, clipboard.length()); mYoutubeId = clipId.toStdString(); mDownloadYoutubeButton->SetShowing(true); } else if (clipboard.contains("youtu.be")) { std::vector<std::string> tokens = ofSplitString(clipboard.toStdString(), "/"); if (tokens.size() > 0) { mYoutubeId = tokens[tokens.size() - 1]; mDownloadYoutubeButton->SetShowing(true); } } else { mYoutubeId = ""; mDownloadYoutubeButton->SetShowing(false); } if (mRunningProcess != nullptr) { if (mModuleSaveData.GetBool("show_youtube_process_output")) { char buffer[512]; auto num = mRunningProcess->readProcessOutput(buffer, sizeof(buffer)); if (num > 0) { MemoryOutputStream result; result.write(buffer, (size_t)num); ofLog() << result.toString(); } } if (mRunningProcessType == RunningProcessType::SearchYoutube) { std::string tempPath = ofToDataPath("youtube_temp"); auto dir = juce::File(tempPath); if (dir.exists()) { Array<juce::File> results; dir.findChildFiles(results, juce::File::findFiles, false, "*.info.json"); if (results.size() != mYoutubeSearchResults.size()) { for (auto& result : results) { std::string file = result.getFileName().toStdString(); ofStringReplace(file, ".info.json", ""); std::vector<std::string> tokens = ofSplitString(file, "#"); if (tokens.size() >= 3) { std::string lengthStr = tokens[tokens.size() - 3]; std::string id = tokens[tokens.size() - 2]; std::string channel = tokens[tokens.size() - 1]; bool found = false; for (auto& existing : mYoutubeSearchResults) { if (existing.youtubeId == id) found = true; } if (!found) { YoutubeSearchResult resultToAdd; std::string name = ""; for (size_t i = 0; i < tokens.size() - 3; ++i) name += tokens[i]; resultToAdd.name = name; resultToAdd.channel = channel; resultToAdd.lengthSeconds = ofToFloat(lengthStr); resultToAdd.youtubeId = id; mYoutubeSearchResults.push_back(resultToAdd); } } } } } } if (!mRunningProcess->isRunning()) { ofLog() << mRunningProcess->readAllProcessOutput(); delete mRunningProcess; mRunningProcess = nullptr; if (mOnRunningProcessComplete != nullptr) mOnRunningProcessComplete(); } } if (mRecentPlayedCuePoint != -1) { int index = mRecentPlayedCuePoint; mRecentPlayedCuePoint = -1; if (index >= 0 && index < (int)mSampleCuePoints.size()) { mActiveCuePointIndex = index; UpdateActiveCuePoint(); } } if (mDoRecording) { int chunkIndex = mRecordingLength / kRecordingChunkSize; if (chunkIndex >= (int)mRecordChunks.size() - 1) { mRecordChunks.push_back(new ChannelBuffer(kRecordingChunkSize)); mRecordChunks[mRecordChunks.size() - 1]->GetChannel(0); //set up buffer } } } void SamplePlayer::Process(double time) { PROFILER(SamplePlayer); IAudioReceiver* target = GetTarget(); //recording input gate processing bool gateWasOpen = false; bool gateIsOpen = false; if (mRecordAsClips) { gateWasOpen = mRecordGate.IsGateOpen(); mRecordGate.ProcessAudio(time, GetBuffer()); gateIsOpen = mRecordGate.IsGateOpen(); } if (mDoRecording) { bool acceptInput = true; if (mRecordAsClips) { acceptInput = gateIsOpen; if (gateIsOpen && !gateWasOpen) { if (mRecordAsClipsCueIndex < (int)mSampleCuePoints.size()) { SetCuePoint(mRecordAsClipsCueIndex, float(mRecordingLength) / gSampleRate, 0, 1); } } if (!gateIsOpen && gateWasOpen) { if (mRecordAsClipsCueIndex < (int)mSampleCuePoints.size()) mSampleCuePoints[mRecordAsClipsCueIndex].lengthSeconds = (float(mRecordingLength) / gSampleRate) - mSampleCuePoints[mRecordAsClipsCueIndex].startSeconds; mRecordingLength += 200; //add silence gap ++mRecordAsClipsCueIndex; } } if (acceptInput) { for (int i = 0; i < GetBuffer()->BufferSize(); ++i) { int chunkIndex = mRecordingLength / kRecordingChunkSize; int chunkPos = mRecordingLength % kRecordingChunkSize; mRecordChunks[chunkIndex]->SetNumActiveChannels(GetBuffer()->NumActiveChannels()); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) mRecordChunks[chunkIndex]->GetChannel(ch)[chunkPos] = GetBuffer()->GetChannel(ch)[i]; ++mRecordingLength; } } } if (mEnabled && target != nullptr && mSample != nullptr) { mNoteInputBuffer.Process(time); ComputeSliders(0); SyncBuffers(mSample->NumChannels()); int bufferSize = target->GetBuffer()->BufferSize(); assert(bufferSize == gBufferSize); float volSq = mVolume * mVolume; const float kBlendSpeed = 1; if (mOscWheelGrabbed) { mPlaySpeed = ofLerp(mPlaySpeed, mOscWheelSpeed, kBlendSpeed); mPlaySpeed = ofClamp(mPlaySpeed, -5, 5); } else { mPlaySpeed = ofLerp(mPlaySpeed, mSpeed * mCuePointSpeed, kBlendSpeed); } mSample->SetRate(mPlaySpeed); gWorkChannelBuffer.SetNumActiveChannels(mSample->NumChannels()); if (mPlay) { if (mSample->ConsumeData(time, &gWorkChannelBuffer, bufferSize, true)) { for (int ch = 0; ch < gWorkChannelBuffer.NumActiveChannels(); ++ch) { for (int i = 0; i < bufferSize; ++i) gWorkChannelBuffer.GetChannel(ch)[i] *= volSq * mAdsr.Value(time + i * gInvSampleRateMs); } } else { gWorkChannelBuffer.Clear(); mPlay = false; mSample->SetPlayPosition(0); mAdsr.Stop(time); } } else { gWorkChannelBuffer.Clear(); } for (int ch = 0; ch < gWorkChannelBuffer.NumActiveChannels(); ++ch) { for (int i = 0; i < bufferSize; ++i) gWorkChannelBuffer.GetChannel(ch)[i] = mSwitchAndRamp.Process(ch, gWorkChannelBuffer.GetChannel(ch)[i]); Add(target->GetBuffer()->GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), bufferSize); GetVizBuffer()->WriteChunk(gWorkChannelBuffer.GetChannel(ch), bufferSize, ch); } } GetBuffer()->Reset(); } void SamplePlayer::PlayNote(double time, int pitch, int velocity, int voiceIdx /*= -1*/, ModulationParameters modulation /*= ModulationParameters()*/) { if (!mEnabled) return; if (mSelectPlayedCuePoint) mRecentPlayedCuePoint = pitch; if (!NoteInputBuffer::IsTimeWithinFrame(time) && GetTarget() && mSample) { mNoteInputBuffer.QueueNote(time, pitch, velocity, voiceIdx, modulation); return; } if (velocity > 0 && mSample != nullptr) PlayCuePoint(time, pitch, velocity, modulation.pitchBend ? exp2(modulation.pitchBend->GetValue(0)) : 1, (modulation.modWheel ? modulation.modWheel->GetValue(0) : ModulationParameters::kDefaultModWheel) - ModulationParameters::kDefaultModWheel); if (velocity == 0 && mStopOnNoteOff) { mAdsr.Stop(time); } } void SamplePlayer::OnPulse(double time, float velocity, int flags) { if (mSample != nullptr) PlayCuePoint(time, -1, velocity * 127, 1, 0); } void SamplePlayer::PlayCuePoint(double time, int index, int velocity, float speedMult, float startOffsetSeconds) { if (mSample != nullptr) { float startSeconds, lengthSeconds, speed; GetPlayInfoForPitch(index, startSeconds, lengthSeconds, speed, mStopOnNoteOff); mSample->SetPlayPosition((startSeconds + startOffsetSeconds) * gSampleRate * mSample->GetSampleRateRatio()); mCuePointSpeed = speed * speedMult; mPlay = true; mAdsr.Clear(); mAdsr.Start(time, velocity / 127.0f); if (lengthSeconds > 0) mAdsr.Stop(time + lengthSeconds * 1000 / speed); mSwitchAndRamp.StartSwitch(); } } void SamplePlayer::DropdownClicked(DropdownList* list) { } void SamplePlayer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mCuePointSelector) UpdateActiveCuePoint(); } void SamplePlayer::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { } void SamplePlayer::UpdateActiveCuePoint() { if (mActiveCuePointIndex >= 0 && mActiveCuePointIndex < (int)mSampleCuePoints.size()) { mCuePointStartSlider->SetVar(&mSampleCuePoints[mActiveCuePointIndex].startSeconds); mCuePointLengthSlider->SetVar(&mSampleCuePoints[mActiveCuePointIndex].lengthSeconds); mCuePointSpeedSlider->SetVar(&mSampleCuePoints[mActiveCuePointIndex].speed); mCuePointStopCheckbox->SetVar(&mSampleCuePoints[mActiveCuePointIndex].stopOnNoteOff); } } void SamplePlayer::AutoSlice(int slices) { float sliceLengthSeconds = GetLengthInSeconds() / slices; for (int i = 0; i < (int)mSampleCuePoints.size(); ++i) { if (i < slices) { mSampleCuePoints[i].startSeconds = sliceLengthSeconds * i; mSampleCuePoints[i].lengthSeconds = sliceLengthSeconds; mSampleCuePoints[i].speed = 1; } else { mSampleCuePoints[i].startSeconds = 0; mSampleCuePoints[i].lengthSeconds = 0; } } } void SamplePlayer::FilesDropped(std::vector<std::string> files, int x, int y) { Sample* sample = new Sample(); sample->Read(files[0].c_str()); UpdateSample(sample, true); } void SamplePlayer::SampleDropped(int x, int y, Sample* sample) { if (TheSynth->MouseMovedSignificantlySincePressed()) //avoid problem of grabbing a clip via the clip grab button and immediately dropping it onto this sampleplayer by accident { Sample* copy = new Sample(); copy->CopyFrom(sample); UpdateSample(copy, true); } } void SamplePlayer::UpdateSample(Sample* sample, bool ownsSample) { Sample* oldSamplePtr = mSample; bool ownedOldSample = mOwnsSample; float lengthSeconds = sample->LengthInSamples() / (gSampleRate * sample->GetSampleRateRatio()); mCuePointStartSlider->SetExtents(0, lengthSeconds); mCuePointLengthSlider->SetExtents(0, lengthSeconds); sample->SetPlayPosition(0); sample->SetLooping(mLoop); sample->SetRate(mSpeed); mSample = sample; mPlay = false; mOwnsSample = ownsSample; mZoomLevel = 1; mZoomOffset = 0; mRecordingLength = 0; mErrorString = ""; if (ownedOldSample) delete oldSamplePtr; mIsLoadingSample = true; } void SamplePlayer::ButtonClicked(ClickButton* button, double time) { if (button == mPlayButton && mSample != nullptr) { if (mRecord == false) { mCuePointSpeed = 1; mStopOnNoteOff = false; mPlay = true; mAdsr.Clear(); mAdsr.Start(time * gInvSampleRateMs, 1); } } if (button == mPauseButton && mSample != nullptr) { mPlay = false; mSwitchAndRamp.StartSwitch(); } if (button == mStopButton) { if (mRecord) { StopRecording(); } else if (mSample != nullptr) { mPlay = false; mSample->SetPlayPosition(0); mSwitchAndRamp.StartSwitch(); } } if (button == mDownloadYoutubeButton) DownloadYoutube("path_to_url" + mYoutubeId, mYoutubeId); if (button == mLoadFileButton) LoadFile(); if (button == mSaveFileButton) SaveFile(); if (button == mTrimToZoomButton && mSample != nullptr) { for (auto& cuePoint : mSampleCuePoints) cuePoint.startSeconds = MAX(0, cuePoint.startSeconds - GetZoomStartSeconds()); Sample* sample = new Sample(); sample->Create(GetZoomEndSample() - GetZoomStartSample()); sample->Data()->SetNumActiveChannels(mSample->NumChannels()); for (int ch = 0; ch < mSample->NumChannels(); ++ch) { float* sampleData = sample->Data()->GetChannel(ch); for (int i = 0; i < sample->LengthInSamples(); ++i) sampleData[i] = mSample->Data()->GetChannel(ch)[i + GetZoomStartSample()]; } sample->SetName(mSample->Name()); UpdateSample(sample, true); } for (size_t i = 0; i < mSearchResultButtons.size(); ++i) { if (button == mSearchResultButtons[i]) { if (i < mYoutubeSearchResults.size()) { DownloadYoutube("path_to_url" + mYoutubeSearchResults[i].youtubeId, mYoutubeSearchResults[i].name); mYoutubeSearchResults.clear(); break; } } } if (button == mPlayCurrentCuePointButton) PlayCuePoint(time, mActiveCuePointIndex, 127, 1, 0); if (button == mAutoSlice4) AutoSlice(4); if (button == mAutoSlice8) AutoSlice(8); if (button == mAutoSlice16) AutoSlice(16); if (button == mAutoSlice32) AutoSlice(32); if (button == mPlayHoveredClipButton) PlayCuePoint(time, mHoveredCuePointIndex, 127, 1, 0); if (button == mGrabHoveredClipButton) { ChannelBuffer* data = GetCueSampleData(mHoveredCuePointIndex); TheSynth->GrabSample(data, mSample->Name(), false); delete data; } } void SamplePlayer::TextEntryComplete(TextEntry* entry) { if (entry == mDownloadYoutubeSearch) { SearchYoutube(mYoutubeSearch); //youtube-dl "ytsearch5:duck quack sound effect" --no-playlist --write-info-json --skip-download -o "test/%(title)s [len %(duration)s] [id %(id)s].%(ext)s" } } void SamplePlayer::DownloadYoutube(std::string url, std::string title) { mPlay = false; if (mSample) mSample->SetPlayPosition(0); auto tempDownloadName = ofToString(this) + "_youtube.m4a"; { auto file = juce::File(ofToDataPath(tempDownloadName)); if (file.existsAsFile()) file.deleteFile(); } auto tempConvertedName = ofToString(this) + "_youtube.wav"; { auto file = juce::File(ofToDataPath(tempConvertedName)); if (file.existsAsFile()) file.deleteFile(); } StringArray args; args.add(UserPrefs.youtube_dl_path.Get()); args.add(url); args.add("--extract-audio"); args.add("--audio-format"); args.add("wav"); args.add("--audio-quality"); args.add("0"); args.add("--no-progress"); args.add("--ffmpeg-location"); args.add(UserPrefs.ffmpeg_path.Get()); args.add("-o"); args.add(ofToDataPath(tempDownloadName)); mRunningProcessType = RunningProcessType::DownloadYoutube; mOnRunningProcessComplete = [this, tempConvertedName, title] { OnYoutubeDownloadComplete(tempConvertedName, title); }; RunProcess(args); } void SamplePlayer::OnYoutubeDownloadComplete(std::string filename, std::string title) { if (juce::File(ofToDataPath(filename)).existsAsFile()) { Sample* sample = new Sample(); sample->Read(ofToDataPath(filename).c_str(), false, Sample::ReadType::Async); sample->SetName(title); UpdateSample(sample, true); } else { UpdateSample(new Sample(), true); mErrorString = "couldn't download sample. do you have youtube-dl and ffmpeg installed,\nwith their paths set in userprefs.json?"; } auto file = juce::File(ofToDataPath(filename)); if (file.existsAsFile()) file.deleteFile(); } void SamplePlayer::RunProcess(const StringArray& args) { std::string command = ""; for (auto& arg : args) command += arg.toStdString() + " "; ofLog() << "running " << command; if (mRunningProcess) mRunningProcess->kill(); delete mRunningProcess; mRunningProcess = new ChildProcess(); bool success = mRunningProcess->start(args); if (!success) ofLog() << "error running process from bespoke"; } void SamplePlayer::SearchYoutube(std::string searchTerm) { std::string tempPath = ofToDataPath("youtube_temp"); auto dir = juce::File(tempPath); if (dir.exists()) dir.deleteRecursively(); dir.createDirectory(); mYoutubeSearchResults.clear(); StringArray args; args.add(UserPrefs.youtube_dl_path.Get()); args.add("ytsearch" + ofToString(kMaxYoutubeSearchResults) + ":" + searchTerm); args.add("--no-playlist"); args.add("--write-info-json"); args.add("--skip-download"); args.add("-o"); args.add(tempPath + "/%(title)s#%(duration)s#%(id)s#%(uploader)s.%(ext)s"); mRunningProcessType = RunningProcessType::SearchYoutube; double searchTime = gTime; mOnRunningProcessComplete = [this, searchTerm, searchTime] { OnYoutubeSearchComplete(searchTerm, searchTime); }; RunProcess(args); } void SamplePlayer::OnYoutubeSearchComplete(std::string searchTerm, double searchTime) { if (mYoutubeSearchResults.size() == 0) { if (gTime - searchTime < 500) { mErrorString = "couldn't search. do you have youtube-dl installed, with its path set in userprefs.json?"; } else { mErrorString = "zero results found for " + searchTerm; } } } void SamplePlayer::LoadFile() { auto file_pattern = TheSynth->GetAudioFormatManager().getWildcardForAllFormats(); if (File::areFileNamesCaseSensitive()) file_pattern += ";" + file_pattern.toUpperCase(); FileChooser chooser("Load sample", File(ofToDataPath("samples")), file_pattern, true, false, TheSynth->GetFileChooserParent()); if (chooser.browseForFileToOpen()) { auto file = chooser.getResult(); Sample* sample = new Sample(); if (file.existsAsFile()) sample->Read(file.getFullPathName().toStdString().c_str()); UpdateSample(sample, true); } } void SamplePlayer::SaveFile() { FileChooser chooser("Save sample", File(ofToDataPath("samples")), "*.wav", true, false, TheSynth->GetFileChooserParent()); if (chooser.browseForFileToSave(true)) { auto file = chooser.getResult(); Sample::WriteDataToFile(file.getFullPathName().toStdString().c_str(), mSample->Data(), mSample->LengthInSamples()); } } void SamplePlayer::FillData(std::vector<float> data) { Sample* sample = new Sample(); sample->Create((int)data.size()); float* sampleData = sample->Data()->GetChannel(0); for (size_t i = 0; i < data.size(); ++i) sampleData[i] = data[i]; UpdateSample(sample, true); } void SamplePlayer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (right) return; if (mYoutubeSearchResults.size() > 0) return; if (y > 60 && y < mHeight - 20 && mSample != nullptr && gHoveredUIControl == nullptr) { mSwitchAndRamp.StartSwitch(); mCuePointSpeed = 1; mStopOnNoteOff = false; mPlay = true; mAdsr.Clear(); mAdsr.Start(NextBufferTime(false), 1); mSample->SetPlayPosition(int(GetPlayPositionForMouse(x))); mScrubbingSample = true; if (mSetCuePoint) SetCuePointForX(x); } } ChannelBuffer* SamplePlayer::GetCueSampleData(int cueIndex) { float startSeconds, lengthSeconds, speed; bool stopOnNoteOff; GetPlayInfoForPitch(cueIndex, startSeconds, lengthSeconds, speed, stopOnNoteOff); if (lengthSeconds <= 0) lengthSeconds = 1; int startSamples = startSeconds * gSampleRate * mSample->GetSampleRateRatio(); int lengthSamplesSrc = lengthSeconds * gSampleRate * mSample->GetSampleRateRatio(); if (startSamples >= mSample->Data()->BufferSize()) startSamples = mSample->Data()->BufferSize() - 1; if (startSamples + lengthSamplesSrc >= mSample->Data()->BufferSize()) lengthSamplesSrc = mSample->Data()->BufferSize() - 1 - startSamples; int lengthSamplesDest = lengthSamplesSrc / speed / mSample->GetSampleRateRatio(); ChannelBuffer* data = new ChannelBuffer(lengthSamplesDest); data->SetNumActiveChannels(mSample->Data()->NumActiveChannels()); /*for (int ch = 0; ch < data->NumActiveChannels(); ++ch) { BufferCopy(data->GetChannel(ch), mSample->Data()->GetChannel(ch) + startSamples, lengthSamplesSrc); }*/ for (int ch = 0; ch < data->NumActiveChannels(); ++ch) { for (int i = 0; i < lengthSamplesDest; ++i) { float offset = i * speed * mSample->GetSampleRateRatio(); data->GetChannel(ch)[i] = GetInterpolatedSample(offset, mSample->Data()->GetChannel(ch) + startSamples, lengthSamplesSrc); } } return data; } bool SamplePlayer::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); if (mScrubbingSample && mSample != nullptr) { mSwitchAndRamp.StartSwitch(); mSample->SetPlayPosition(int(GetPlayPositionForMouse(x))); mAdsr.Clear(); mAdsr.Start(NextBufferTime(false), 1); if (mSetCuePoint) SetCuePointForX(x); } if (gHoveredUIControl == nullptr) //make sure we don't update our hover while dragging a slider { mHoveredCuePointIndex = -1; if (y > 60 && y < mHeight - 20 && mSample != nullptr) { float seconds = GetSecondsForMouse(x); // find cue point closest to but not exceeding the cursor position int bestCuePointIndex = -1; float bestCuePointStart = 0.; for (size_t i = 0; i < mSampleCuePoints.size(); ++i) { float startSeconds = mSampleCuePoints[i].startSeconds; float lengthSeconds = mSampleCuePoints[i].lengthSeconds; if (lengthSeconds > 0.) { if (seconds >= startSeconds && seconds <= startSeconds + lengthSeconds && startSeconds > bestCuePointStart) { bestCuePointIndex = i; bestCuePointStart = startSeconds; } } } if (bestCuePointIndex != -1) { mHoveredCuePointIndex = bestCuePointIndex; //mActiveCuePointIndex = bestCuePointIndex; //UpdateActiveCuePoint(); } } } return true; } void SamplePlayer::SetCuePointForX(float mouseX) { mSampleCuePoints[mActiveCuePointIndex].startSeconds = GetPlayPositionForMouse(mouseX) / (gSampleRate * mSample->GetSampleRateRatio()); mSampleCuePoints[mActiveCuePointIndex].speed = 1; } void SamplePlayer::MouseReleased() { IDrawableModule::MouseReleased(); mScrubbingSample = false; } float SamplePlayer::GetPlayPositionForMouse(float mouseX) const { return ofMap(mouseX, 5, mWidth - 5, GetZoomStartSample(), GetZoomEndSample(), true); } float SamplePlayer::GetSecondsForMouse(float mouseX) const { return ofMap(mouseX, 5, mWidth - 5, GetZoomStartSeconds(), GetZoomEndSeconds(), true); } void SamplePlayer::GetPlayInfoForPitch(int pitch, float& startSeconds, float& lengthSeconds, float& speed, bool& stopOnNoteOff) const { if (pitch >= 0 && pitch < mSampleCuePoints.size()) { startSeconds = mSampleCuePoints[pitch].startSeconds; lengthSeconds = mSampleCuePoints[pitch].lengthSeconds; speed = mSampleCuePoints[pitch].speed; stopOnNoteOff = mSampleCuePoints[pitch].stopOnNoteOff; } else { startSeconds = 0; lengthSeconds = 0; speed = 1; stopOnNoteOff = false; } } void SamplePlayer::SetCuePoint(int pitch, float startSeconds, float lengthSeconds, float speed) { if (pitch < mSampleCuePoints.size()) { mSampleCuePoints[pitch].startSeconds = startSeconds; mSampleCuePoints[pitch].lengthSeconds = lengthSeconds; mSampleCuePoints[pitch].speed = speed; } } void SamplePlayer::DrawModule() { if (Minimized() || IsVisible() == false) return; mTrimToZoomButton->SetShowing(mZoomLevel != 1); mVolumeSlider->Draw(); mSpeedSlider->Draw(); mLoopCheckbox->Draw(); mPlayButton->Draw(); mPauseButton->Draw(); mStopButton->Draw(); mTrimToZoomButton->Draw(); mDownloadYoutubeButton->Draw(); mDownloadYoutubeSearch->Draw(); mLoadFileButton->Draw(); mSaveFileButton->Draw(); mRecordCheckbox->Draw(); mCuePointSelector->Draw(); mSetCuePointCheckbox->Draw(); mSelectPlayedCuePointCheckbox->Draw(); mCuePointStartSlider->Draw(); mCuePointLengthSlider->Draw(); mCuePointSpeedSlider->Draw(); mCuePointStopCheckbox->Draw(); mPlayCurrentCuePointButton->Draw(); mShowGridCheckbox->Draw(); mAutoSlice4->Draw(); mAutoSlice8->Draw(); mAutoSlice16->Draw(); mAutoSlice32->Draw(); mRecordingAppendModeCheckbox->Draw(); mRecordAsClipsCheckbox->Draw(); mRecordGate.Draw(); for (size_t i = 0; i < mSearchResultButtons.size(); ++i) { if (i < mYoutubeSearchResults.size()) { mSearchResultButtons[i]->SetShowing(true); int minutes = int(mYoutubeSearchResults[i].lengthSeconds / 60); int secondsRemainder = int(mYoutubeSearchResults[i].lengthSeconds) % 60; std::string lengthStr = ofToString(minutes) + ":"; if (secondsRemainder < 10) lengthStr += "0"; lengthStr += ofToString(secondsRemainder); mSearchResultButtons[i]->SetLabel(("(" + lengthStr + ") " + mYoutubeSearchResults[i].name + " [" + mYoutubeSearchResults[i].channel + "]").c_str()); } else { mSearchResultButtons[i]->SetShowing(false); } mSearchResultButtons[i]->Draw(); } ofPushMatrix(); ofTranslate(5, 58); float sampleWidth = mWidth - 10; if (mDoRecording) { ofSetColor(255, 0, 0, 100); ofRect(0, 0, mWidth - 10, mHeight - 65); ofPushMatrix(); int numChunks = mRecordingLength / kRecordingChunkSize + 1; float chunkWidth = sampleWidth / numChunks; for (int i = 0; i < numChunks; ++i) { DrawAudioBuffer(chunkWidth, mHeight - 65, mRecordChunks[i], 0, kRecordingChunkSize, -1); ofTranslate(chunkWidth, 0); } ofPopMatrix(); } else if (mRunningProcess != nullptr || (mSample && mSample->IsSampleLoading())) { const int kNumDots = 8; const float kCircleRadius = 20; const float kDotRadius = 3; const float kSpinSpeed = .003f; ofPushStyle(); ofFill(); for (int i = 0; i < kNumDots; ++i) { float theta = float(i) / kNumDots * M_PI * 2 + gTime * kSpinSpeed; ofCircle(cos(theta) * kCircleRadius + (mWidth - 10) * .5f, sin(theta) * kCircleRadius + (mHeight - 65) * .5f, kDotRadius); } ofPopStyle(); if (mSample && mSample->IsSampleLoading()) { ofPushStyle(); ofFill(); ofSetColor(255, 255, 255, 50); ofRect(0, 0, (mWidth - 10) * mSample->GetSampleLoadProgress(), mHeight - 65); ofSetColor(40, 40, 40); DrawTextNormal("loading sample...", 10, 10, 8); ofPopStyle(); } } else if (mYoutubeSearchResults.size() > 0) { //don't draw, buttons will draw instead } else if (mErrorString != "") { ofPushStyle(); ofFill(); ofSetColor(255, 255, 255, 50); ofRect(0, 0, mWidth - 10, mHeight - 65); ofSetColor(220, 0, 0); DrawTextNormal(mErrorString, 10, 10, 8); ofPopStyle(); } else if (mSample && mSample->LengthInSamples() > 0) { if (mIsLoadingSample && !mSample->IsSampleLoading()) { mIsLoadingSample = false; mDrawBuffer.Resize(mSample->LengthInSamples()); mDrawBuffer.CopyFrom(mSample->Data()); } int playPosition = mSample->GetPlayPosition(); if (mAdsr.Value(gTime) == 0) playPosition = -1; DrawAudioBuffer(sampleWidth, mHeight - 65, &mDrawBuffer, GetZoomStartSample(), GetZoomEndSample(), playPosition); ofPushStyle(); ofFill(); ofSetColor(255, 255, 255); DrawTextNormal(mSample->Name(), 5, 27); if (playPosition >= 0) { float x = ofMap(playPosition, GetZoomStartSample(), GetZoomEndSample(), 0, sampleWidth); DrawTextNormal(ofToString(playPosition / (gSampleRate * mSample->GetSampleRateRatio()), 1), x + 2, mHeight - 65, 9); } if (mShowGrid) { float lengthSeconds = GetZoomEndSeconds() - GetZoomStartSeconds(); float lengthBeats = TheTransport->GetTempo() * (lengthSeconds / 60) / mSampleCuePoints[mActiveCuePointIndex].speed; if (lengthBeats < 30) { float alpha = ofMap(lengthBeats, 30, 28, 0, 200, true); ofSetColor(0, 255, 255, alpha); float secondsPerBeat = 60 / (TheTransport->GetTempo() / mSampleCuePoints[mActiveCuePointIndex].speed); float offset = mSampleCuePoints[mActiveCuePointIndex].startSeconds; float firstBeat = ceil((GetZoomStartSeconds() - offset) / secondsPerBeat); float firstBeatSeconds = firstBeat * secondsPerBeat + offset; for (int i = 0; i < ceil(lengthBeats); ++i) { float second = firstBeatSeconds + i * secondsPerBeat; float x = ofMap(second, GetZoomStartSeconds(), GetZoomEndSeconds(), 0, sampleWidth); ofLine(x, 0, x, mHeight - 65); } } } ofPopStyle(); } else { ofPushStyle(); ofFill(); ofSetColor(255, 255, 255, 50); ofRect(0, 0, mWidth - 10, mHeight - 65); ofSetColor(40, 40, 40); DrawTextNormal("drag and drop a sample here...", 10, 10, 8); ofPopStyle(); } if ((mSample && mSample->LengthInSamples() > 0) || mDoRecording) { ofPushStyle(); ofFill(); for (size_t i = 0; i < mSampleCuePoints.size(); ++i) { if (mSampleCuePoints[i].lengthSeconds > 0 || mSampleCuePoints[i].startSeconds > 0) { float x = ofMap(mSampleCuePoints[i].startSeconds, GetZoomStartSeconds(), GetZoomEndSeconds(), 0, sampleWidth); float xEnd = ofMap(mSampleCuePoints[i].startSeconds + mSampleCuePoints[i].lengthSeconds, GetZoomStartSeconds(), GetZoomEndSeconds(), 0, sampleWidth); ofSetColor(0, 0, 0, 100); ofRect(x, 0, MAX((xEnd - x), 10), 10); ofRect(x, 0, 15, 10); ofSetColor(255, 255, 255); ofRect(x, 0, 1, 20, 1); if (i == mActiveCuePointIndex) { ofNoFill(); ofRect(x, 0, 15, 10); ofFill(); } DrawTextNormal(ofToString((int)i), x + 2, 8, 9); if (i == mHoveredCuePointIndex) { ofSetColor(255, 255, 255, 50); ofRect(x, 0, (xEnd - x), mHeight - 65); } } } ofPopStyle(); } ofPopMatrix(); if (mZoomLevel != 1) { ofNoFill(); ofRect(5, mHeight - 7, mWidth - 10, 7); ofFill(); ofRect(mZoomOffset * (mWidth - 10) + 5, mHeight - 7, (mWidth - 10) / mZoomLevel, 7); } if (mHoveredCuePointIndex != -1 && mSample && mSample->LengthInSamples() > 0 && !mRecord) { float x = ofMap(mSampleCuePoints[mHoveredCuePointIndex].startSeconds, GetZoomStartSeconds(), GetZoomEndSeconds(), 0, sampleWidth); float xEnd = ofMap(mSampleCuePoints[mHoveredCuePointIndex].startSeconds + mSampleCuePoints[mHoveredCuePointIndex].lengthSeconds, GetZoomStartSeconds(), GetZoomEndSeconds(), 0, sampleWidth); if (xEnd - x > 45) { mPlayHoveredClipButton->SetPosition(x + 5, 72); mGrabHoveredClipButton->SetPosition(x + 28, 72); mPlayHoveredClipButton->SetShowing(true); mGrabHoveredClipButton->SetShowing(true); mPlayHoveredClipButton->Draw(); mGrabHoveredClipButton->Draw(); } else { mPlayHoveredClipButton->SetShowing(false); mGrabHoveredClipButton->SetShowing(false); } } else { mPlayHoveredClipButton->SetShowing(false); mGrabHoveredClipButton->SetShowing(false); } } float SamplePlayer::GetLengthInSeconds() const { if (mSample != nullptr) return mSample->LengthInSamples() / (gSampleRate * mSample->GetSampleRateRatio()); return 0; } int SamplePlayer::GetZoomStartSample() const { if (mDoRecording) return 0; if (mSample == nullptr) return 0; return (int)ofClamp(mSample->LengthInSamples() * mZoomOffset, 0, mSample->LengthInSamples()); } int SamplePlayer::GetZoomEndSample() const { if (mDoRecording) { int numChunks = mRecordingLength / kRecordingChunkSize + 1; return (numChunks * kRecordingChunkSize); } if (mSample == nullptr) return 1; return (int)ofClamp(GetZoomStartSample() + mSample->LengthInSamples() / mZoomLevel, 1, mSample->LengthInSamples()); } float SamplePlayer::GetZoomStartSeconds() const { if (mDoRecording) return 0; if (mSample == nullptr) return 0; return GetZoomStartSample() / (gSampleRate * mSample->GetSampleRateRatio()); } float SamplePlayer::GetZoomEndSeconds() const { if (mDoRecording) return float(GetZoomEndSample()) / gSampleRate; if (mSample == nullptr) return 1; return GetZoomEndSample() / (gSampleRate * mSample->GetSampleRateRatio()); } void SamplePlayer::oscMessageReceived(const OSCMessage& msg) { if (msg.getAddressPattern().toString() == "/wheel/z") { bool grabbed = msg[0].getFloat32() > 0; if (grabbed) { mOscWheelPos = FLT_MAX; mOscWheelSpeed = 0; mOscWheelGrabbed = true; } else { mOscWheelGrabbed = false; } } else if (msg.getAddressPattern().toString() == "/wheel/x") { float pos = msg[0].getFloat32(); if (mOscWheelPos == FLT_MAX) { mOscWheelPos = pos; } mOscWheelSpeed = (pos - mOscWheelPos) * 70; mOscWheelPos = pos; } else if (msg.getAddressPattern().toString() == "/Fader/x") { float pos = msg[0].getFloat32(); mSpeed = ofLerp(mSpeedSlider->GetMin(), mSpeedSlider->GetMax(), pos); } } void SamplePlayer::oscBundleReceived(const OSCBundle& bundle) { for (const OSCBundle::Element* element = bundle.begin(); element != bundle.end(); ++element) { if (element->isMessage()) oscMessageReceived(element->getMessage()); else if (element->isBundle()) oscBundleReceived(element->getBundle()); } } bool SamplePlayer::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { if (fabs(scrollX) > fabsf(scrollY)) scrollY = 0; else scrollX = 0; //horizontal scroll mZoomOffset = ofClamp(mZoomOffset + scrollX * .005f, 0, 1); //zoom scroll float oldZoomLevel = mZoomLevel; mZoomLevel = ofClamp(mZoomLevel + scrollY * .2f, 1, 40); float zoomAmount = (mZoomLevel - oldZoomLevel) / oldZoomLevel; //find actual adjusted amount float zoomCenter = ofMap(x, 5, mWidth - 10, 0, 1, true) / oldZoomLevel; mZoomOffset += zoomCenter * zoomAmount; if (mZoomLevel == 1) mZoomOffset = 0; return false; } void SamplePlayer::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mLoopCheckbox) { if (mSample != nullptr) mSample->SetLooping(mLoop); } if (checkbox == mRecordCheckbox) { mPlay = false; if (mRecord) { if (!mRecordingAppendMode || mRecordingLength == 0) { mRecordingLength = 0; for (size_t i = mRecordChunks.size(); i < kMinRecordingChunks; ++i) { mRecordChunks.push_back(new ChannelBuffer(kRecordingChunkSize)); mRecordChunks[i]->GetChannel(0); //set up buffer } for (size_t i = 0; i < mRecordChunks.size(); ++i) mRecordChunks[i]->Clear(); mRecordAsClipsCueIndex = 0; for (int i = 0; i < (int)mSampleCuePoints.size(); ++i) SetCuePoint(i, 0, 0, 1); } mDoRecording = true; } else if (mRecordingLength > 0) { StopRecording(); } } if (checkbox == mRecordAsClipsCheckbox) mRecordGate.SetEnabled(mRecordAsClips); } void SamplePlayer::StopRecording() { if (mDoRecording) { mRecord = false; mDoRecording = false; Sample* sample = new Sample(); sample->Create(mRecordingLength); ChannelBuffer* data = sample->Data(); int channelCount = mRecordChunks[0]->NumActiveChannels(); data->SetNumActiveChannels(channelCount); int numChunks = mRecordingLength / kRecordingChunkSize + 1; for (int i = 0; i < numChunks; ++i) { int samplesLeftToRecord = mRecordingLength - i * kRecordingChunkSize; int samplesToCopy; if (samplesLeftToRecord > kRecordingChunkSize) samplesToCopy = kRecordingChunkSize; else samplesToCopy = samplesLeftToRecord; for (int ch = 0; ch < channelCount; ++ch) BufferCopy(data->GetChannel(ch) + i * kRecordingChunkSize, mRecordChunks[i]->GetChannel(ch), samplesToCopy); } int recordedLength = mRecordingLength; UpdateSample(sample, true); mRecordingLength = recordedLength; } } void SamplePlayer::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void SamplePlayer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void SamplePlayer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void SamplePlayer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadFloat("width", moduleInfo, mWidth); mModuleSaveData.LoadFloat("height", moduleInfo, mHeight); mModuleSaveData.LoadBool("show_youtube_process_output", moduleInfo, false); SetUpFromSaveData(); } void SamplePlayer::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["width"] = mWidth; moduleInfo["height"] = mHeight; } void SamplePlayer::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); Resize(mModuleSaveData.GetFloat("width"), mModuleSaveData.GetFloat("height")); } void SamplePlayer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); bool hasSample = (mSample != nullptr); out << hasSample; if (hasSample) mSample->SaveState(out); out << (int)mSampleCuePoints.size(); for (size_t i = 0; i < mSampleCuePoints.size(); ++i) { out << mSampleCuePoints[i].startSeconds; out << mSampleCuePoints[i].lengthSeconds; out << mSampleCuePoints[i].speed; out << mSampleCuePoints[i].stopOnNoteOff; } } void SamplePlayer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); bool hasSample; in >> hasSample; if (hasSample) { Sample* sample = new Sample(); sample->LoadState(in); UpdateSample(sample, true); } if (rev >= 1) { int size; in >> size; mSampleCuePoints.resize(size); for (size_t i = 0; i < size; ++i) { in >> mSampleCuePoints[i].startSeconds; in >> mSampleCuePoints[i].lengthSeconds; in >> mSampleCuePoints[i].speed; if (rev >= 2) in >> mSampleCuePoints[i].stopOnNoteOff; } } } std::vector<IUIControl*> SamplePlayer::ControlsToIgnoreInSaveState() const { std::vector<IUIControl*> ignore; ignore.push_back(mDownloadYoutubeSearch); ignore.push_back(mLoadFileButton); ignore.push_back(mSaveFileButton); for (size_t i = 0; i < mSearchResultButtons.size(); ++i) ignore.push_back(mSearchResultButtons[i]); return ignore; } ```
/content/code_sandbox/Source/SamplePlayer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
12,142
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ModulatorAccum.cpp Created: 2 Aug 2021 10:32:59pm Author: Ryan Challinor ============================================================================== */ #include "ModulatorAccum.h" #include "Profiler.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "UIControlMacros.h" ModulatorAccum::ModulatorAccum() { } void ModulatorAccum::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void ModulatorAccum::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mValueSlider, "value", &mValue, 0, 1); FLOATSLIDER(mVelocitySlider, "velocity", &mVelocity, -1, 1); ENDUIBLOCK(mWidth, mHeight); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } ModulatorAccum::~ModulatorAccum() { TheTransport->RemoveAudioPoller(this); } void ModulatorAccum::DrawModule() { if (Minimized() || IsVisible() == false) return; mValueSlider->Draw(); mVelocitySlider->Draw(); } void ModulatorAccum::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); if (GetSliderTarget() && fromUserClick) { mValue = GetSliderTarget()->GetValue(); mValueSlider->SetExtents(GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax()); mValueSlider->SetMode(GetSliderTarget()->GetMode()); } } void ModulatorAccum::OnTransportAdvanced(float amount) { float dt = amount * TheTransport->MsPerBar(); float newValue = ofClamp(mValue + mVelocity / 1000 * (GetMax() - GetMin()) * dt, GetMin(), GetMax()); mValue = newValue; } float ModulatorAccum::Value(int samplesIn) { ComputeSliders(samplesIn); float dt = samplesIn / gSampleRate; float value = ofClamp(mValue + mVelocity / 1000 * (GetMax() - GetMin()) * dt, GetMin(), GetMax()); return value; } void ModulatorAccum::SaveLayout(ofxJSONElement& moduleInfo) { } void ModulatorAccum::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void ModulatorAccum::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/ModulatorAccum.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
683
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // IMidiVoice.h // additiveSynth // // Created by Ryan Challinor on 11/20/12. // // #pragma once #include "ModulationChain.h" #include "Profiler.h" class IVoiceParams; class IMidiVoice { public: IMidiVoice() {} virtual ~IMidiVoice() {} virtual void ClearVoice() = 0; void SetPitch(float pitch) { mPitch = ofClamp(pitch, 0, 127); } void SetModulators(ModulationParameters modulators) { mModulators = modulators; } virtual void Start(double time, float amount) = 0; virtual void Stop(double time) = 0; virtual bool Process(double time, ChannelBuffer* out, int oversampling) = 0; virtual bool IsDone(double time) = 0; virtual void SetVoiceParams(IVoiceParams* params) = 0; void SetPan(float pan) { assert(pan >= -1 && pan <= 1); mPan = pan; } float GetPan() const { assert(mPan >= -1 && mPan <= 1); return mPan; } float GetPitch(int samplesIn) { return mPitch + (mModulators.pitchBend ? mModulators.pitchBend->GetValue(samplesIn) : ModulationParameters::kDefaultPitchBend); } float GetModWheel(int samplesIn) { return mModulators.modWheel ? mModulators.modWheel->GetValue(samplesIn) : ModulationParameters::kDefaultModWheel; } float GetPressure(int samplesIn) { return mModulators.pressure ? mModulators.pressure->GetValue(samplesIn) : ModulationParameters::kDefaultPressure; } private: float mPitch{ 0 }; float mPan{ 0 }; ModulationParameters mModulators; }; ```
/content/code_sandbox/Source/IMidiVoice.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
502
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== PulseFlag.h Created: 24 Feb 2023 Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "IPulseReceiver.h" #include "DropdownList.h" class PulseFlag : public IDrawableModule, public IPulseSource, public IPulseReceiver, public IDropdownListener { public: PulseFlag(); virtual ~PulseFlag(); static IDrawableModule* Create() { return new PulseFlag(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override {} void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; float mWidth{ 150 }; float mHeight{ 40 }; int mFlagValue{ 0 }; bool mReplaceFlags{ true }; DropdownList* mFlagValueSelector{ nullptr }; Checkbox* mReplaceFlagsCheckbox{ nullptr }; }; ```
/content/code_sandbox/Source/PulseFlag.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
430
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // MidiDevice.h // additiveSynth // // Created by Ryan Challinor on 11/19/12. // // #pragma once #include "ModularSynth.h" #include "juce_audio_devices/juce_audio_devices.h" struct MidiNote { const char* mDeviceName; double mTimestampMs{ 0 }; int mPitch{ 0 }; float mVelocity{ 0 }; //0-127 int mChannel{ -1 }; }; struct MidiControl { const char* mDeviceName; int mControl{ 0 }; float mValue{ 0 }; int mChannel{ -1 }; }; struct MidiProgramChange { const char* mDeviceName; int mProgram{ 0 }; int mChannel{ -1 }; }; struct MidiPitchBend { const char* mDeviceName; float mValue{ 0 }; int mChannel{ -1 }; }; struct MidiPressure { const char* mDeviceName; int mPitch{ 0 }; float mPressure{ 0 }; int mChannel{ -1 }; }; class MidiDeviceListener { public: virtual ~MidiDeviceListener() {} virtual void ControllerPageSelected() {} virtual void OnMidiNote(MidiNote& note) = 0; virtual void OnMidiControl(MidiControl& control) = 0; virtual void OnMidiProgramChange(MidiProgramChange& program) {} virtual void OnMidiPitchBend(MidiPitchBend& pitchBend) {} virtual void OnMidiPressure(MidiPressure& pressure) {} virtual void OnMidi(const juce::MidiMessage& message) {} }; class MidiDevice : public juce::MidiInputCallback { public: MidiDevice(MidiDeviceListener* listener); virtual ~MidiDevice(); bool ConnectInput(const char* name); void ConnectInput(int index); bool ConnectOutput(const char* name, int channel = 1); bool ConnectOutput(int index, int channel = 1); void DisconnectInput(); void DisconnectOutput(); bool Reconnect(); bool IsInputConnected(bool immediate); const char* Name() { return mIsInputEnabled ? mDeviceInInfo.name.toRawUTF8() : mDeviceOutInfo.name.toRawUTF8(); } std::vector<std::string> GetPortList(bool forInput); void SendNote(double time, int pitch, int velocity, bool forceNoteOn, int channel); void SendCC(int ctl, int value, int channel = -1); void SendAftertouch(int pressure, int channel = -1); void SendProgramChange(int program, int channel = -1); void SendPitchBend(int bend, int channel = -1); void SendSysEx(std::string data); void SendData(unsigned char a, unsigned char b, unsigned char c); void SendMessage(double time, juce::MidiMessage message); static void SendMidiMessage(MidiDeviceListener* listener, const char* deviceName, const juce::MidiMessage& message); static constexpr float kPitchBendCenter{ 8192.0f }; static constexpr float kPitchBendMax{ 16320.0f }; private: void handleIncomingMidiMessage(juce::MidiInput* source, const juce::MidiMessage& message) override; juce::MidiDeviceInfo mDeviceInInfo; juce::MidiDeviceInfo mDeviceOutInfo; std::unique_ptr<juce::MidiOutput> mMidiOut{ nullptr }; MidiDeviceListener* mListener{ nullptr }; int mOutputChannel{ 1 }; bool mIsInputEnabled{ false }; }; ```
/content/code_sandbox/Source/MidiDevice.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
902
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // VSTPlayhead.cpp // Bespoke // // Created by Ryan Challinor on 1/20/16. // // #include "VSTPlayhead.h" #include "Transport.h" juce::Optional<juce::AudioPlayHead::PositionInfo> VSTPlayhead::getPosition() const { PositionInfo pos; juce::AudioPlayHead::TimeSignature timeSignature; juce::AudioPlayHead::LoopPoints loopPoint; timeSignature.numerator = TheTransport->GetTimeSigTop(); timeSignature.denominator = TheTransport->GetTimeSigBottom(); juce::Optional<juce::AudioPlayHead::TimeSignature> posTM = pos.getTimeSignature(); loopPoint.ppqStart = 0; loopPoint.ppqEnd = 480; if (posTM) { loopPoint.ppqEnd *= posTM->denominator; } pos.setBpm(TheTransport->GetTempo()); pos.setTimeSignature(timeSignature); pos.setTimeInSamples(gTime * gSampleRateMs); pos.setTimeInSeconds(gTime / 1000); /* * getMeasureTime is a float of how many measures we are through with fractional * measures. We want to know the number of quarter notes from the epoch which is * just the tsRatio times measure count, and for start of measure we simply floor * the measure time */ double tsRatio = 4; if (pos.getTimeSignature()->numerator > 0) tsRatio = 1.0 * pos.getTimeSignature()->numerator / pos.getTimeSignature()->denominator * 4; pos.setPpqPosition((TheTransport->GetMeasureTime(gTime)) * tsRatio); pos.setPpqPositionOfLastBarStart(floor(TheTransport->GetMeasureTime(gTime)) * tsRatio); pos.setIsPlaying(true); pos.setIsRecording(false); pos.setIsLooping(false); pos.setLoopPoints(loopPoint); pos.setFrameRate(juce::AudioPlayHead::fps60); return pos; } ```
/content/code_sandbox/Source/VSTPlayhead.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
540
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // CurveLooper.cpp // Bespoke // // Created by Ryan Challinor on 3/5/16. // // #include "CurveLooper.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "SynthGlobals.h" #include <algorithm> namespace { const int kAdsrTime = 10000; } CurveLooper::CurveLooper() { mEnvelopeControl.SetADSR(&mAdsr); mEnvelopeControl.SetViewLength(kAdsrTime); mEnvelopeControl.SetFixedLengthMode(true); mAdsr.GetFreeReleaseLevel() = true; mAdsr.SetNumStages(2); mAdsr.GetHasSustainStage() = false; mAdsr.GetStageData(0).target = .5f; mAdsr.GetStageData(0).time = kAdsrTime * .1f; mAdsr.GetStageData(1).target = .5f; mAdsr.GetStageData(1).time = kAdsrTime * .8f; } void CurveLooper::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } CurveLooper::~CurveLooper() { TheTransport->RemoveAudioPoller(this); } void CurveLooper::CreateUIControls() { IDrawableModule::CreateUIControls(); mLengthSelector = new DropdownList(this, "length", 5, 3, (int*)(&mLength)); mRandomizeButton = new ClickButton(this, "randomize", -1, -1); mControlCable = new PatchCableSource(this, kConnectionType_ValueSetter); //mControlCable->SetManualPosition(86, 10); AddPatchCableSource(mControlCable); mLengthSelector->AddLabel("4n", -4); mLengthSelector->AddLabel("2n", -2); mLengthSelector->AddLabel("1", 1); mLengthSelector->AddLabel("2", 2); mLengthSelector->AddLabel("3", 3); mLengthSelector->AddLabel("4", 4); mLengthSelector->AddLabel("6", 6); mLengthSelector->AddLabel("8", 8); mLengthSelector->AddLabel("16", 16); mLengthSelector->AddLabel("32", 32); mLengthSelector->AddLabel("64", 64); mLengthSelector->AddLabel("128", 128); mRandomizeButton->PositionTo(mLengthSelector, kAnchor_Right); } void CurveLooper::Poll() { } void CurveLooper::OnTransportAdvanced(float amount) { if (mEnabled) { ADSR::EventInfo adsrEvent(0, kAdsrTime); for (auto* control : mUIControls) { if (control != nullptr) control->SetFromMidiCC(mAdsr.Value(GetPlaybackPosition() * kAdsrTime, &adsrEvent), gTime, true); } } } float CurveLooper::GetPlaybackPosition() { if (mLength == 0) mLength = 1; else if (mLength < 0) { float ret = TheTransport->GetMeasurePos(gTime) * (-mLength); return FloatWrap(ret, 1); } return (TheTransport->GetMeasurePos(gTime) + TheTransport->GetMeasure(gTime) % mLength) / mLength; } void CurveLooper::DrawModule() { if (Minimized() || IsVisible() == false) return; mLengthSelector->Draw(); mRandomizeButton->Draw(); mEnvelopeControl.Draw(); ofPushStyle(); ofSetColor(ofColor::lime); float x = ofLerp(mEnvelopeControl.GetPosition().x, mEnvelopeControl.GetPosition().x + mEnvelopeControl.GetDimensions().x, GetPlaybackPosition()); ofLine(x, mEnvelopeControl.GetPosition().y, x, mEnvelopeControl.GetPosition().y + mEnvelopeControl.GetDimensions().y); ofPopStyle(); } void CurveLooper::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); mEnvelopeControl.OnClicked(x, y, right); } void CurveLooper::MouseReleased() { IDrawableModule::MouseReleased(); mEnvelopeControl.MouseReleased(); } bool CurveLooper::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mEnvelopeControl.MouseMoved(x, y); return false; } void CurveLooper::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { for (size_t i = 0; i < mUIControls.size(); ++i) { if (i < mControlCable->GetPatchCables().size()) mUIControls[i] = dynamic_cast<IUIControl*>(mControlCable->GetPatchCables()[i]->GetTarget()); else mUIControls[i] = nullptr; } } void CurveLooper::CheckboxUpdated(Checkbox* checkbox, double time) { } void CurveLooper::DropdownUpdated(DropdownList* list, int oldVal, double time) { /*int newSteps = int(mLength/4.0f * TheTransport->CountInStandardMeasure(mInterval)); if (list == mIntervalSelector) { if (newSteps > 0) { SetNumSteps(newSteps, true); } else { mInterval = (NoteInterval)oldVal; } } if (list == mLengthSelector) { if (newSteps > 0) SetNumSteps(newSteps, false); else mLength = oldVal; }*/ } void CurveLooper::ButtonClicked(ClickButton* button, double time) { if (button == mRandomizeButton) { mAdsr.SetNumStages(gRandom() % 6 + 2); std::vector<float> times; for (int i = 0; i < mAdsr.GetNumStages(); ++i) times.push_back(ofRandom(1, kAdsrTime - 1)); std::sort(times.begin(), times.end()); float timeElapsed = 0; for (int i = 0; i < mAdsr.GetNumStages(); ++i) { mAdsr.GetStageData(i).time = times[i] - timeElapsed; mAdsr.GetStageData(i).target = ofRandom(0, 1); float val = ofRandom(-1, 1); mAdsr.GetStageData(i).curve = val * val * (val > 0 ? 1 : -1); timeElapsed += mAdsr.GetStageData(i).time; } } } void CurveLooper::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void CurveLooper::Resize(float w, float h) { mWidth = MAX(w, 200); mHeight = MAX(h, 120); mEnvelopeControl.SetDimensions(ofVec2f(mWidth - 10, mHeight - 30)); } void CurveLooper::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["width"] = mWidth; moduleInfo["height"] = mHeight; } void CurveLooper::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadInt("width", moduleInfo, 200, 120, 1000); mModuleSaveData.LoadInt("height", moduleInfo, 120, 15, 1000); SetUpFromSaveData(); } void CurveLooper::SetUpFromSaveData() { mWidth = mModuleSaveData.GetInt("width"); mHeight = mModuleSaveData.GetInt("height"); Resize(mWidth, mHeight); } void CurveLooper::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mAdsr.SaveState(out); } void CurveLooper::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); if (rev >= 1) mAdsr.LoadState(in); } ```
/content/code_sandbox/Source/CurveLooper.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,937
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== LinnstrumentControl.cpp Created: 28 Oct 2018 2:17:18pm Author: Ryan Challinor ============================================================================== */ #include "LinnstrumentControl.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "ModulationChain.h" #include "PolyphonyMgr.h" #include "MidiController.h" #include <chrono> #include <thread> using namespace std::chrono_literals; LinnstrumentControl::LinnstrumentControl() : mDevice(this) { TheScale->AddListener(this); for (size_t i = 0; i < mGridColorState.size(); ++i) mGridColorState[i] = kLinnColor_Invalid; } LinnstrumentControl::~LinnstrumentControl() { TheScale->RemoveListener(this); } void LinnstrumentControl::CreateUIControls() { IDrawableModule::CreateUIControls(); mControllerList = new DropdownList(this, "controller", 5, 5, &mControllerIndex); mDecaySlider = new FloatSlider(this, "decay", mControllerList, kAnchor_Below, 100, 15, &mDecayMs, 0, 2000); mBlackoutCheckbox = new Checkbox(this, "blackout", mDecaySlider, kAnchor_Below, &mBlackout); mLightOctavesCheckbox = new Checkbox(this, "octaves", mBlackoutCheckbox, kAnchor_Below, &mLightOctaves); mGuitarLinesCheckbox = new Checkbox(this, "guitar lines", mBlackoutCheckbox, kAnchor_Right, &mGuitarLines); } void LinnstrumentControl::Init() { IDrawableModule::Init(); InitController(); } void LinnstrumentControl::Poll() { for (int i = 0; i < 128; ++i) mNoteAge[i].Update(i, this); if (gTime - mRequestedOctaveTime > 2000) { SendNRPN(299, 36); //request left split octave mRequestedOctaveTime = gTime; } } void LinnstrumentControl::InitController() { BuildControllerList(); const std::vector<std::string>& devices = mDevice.GetPortList(false); for (int i = 0; i < devices.size(); ++i) { if (strstr(devices[i].c_str(), "LinnStrument") != nullptr) { mControllerIndex = i; mDevice.ConnectOutput(i); mDevice.ConnectInput(devices[i].c_str()); UpdateScaleDisplay(); break; } } } void LinnstrumentControl::DrawModule() { if (Minimized() || IsVisible() == false) return; mControllerList->Draw(); mDecaySlider->Draw(); mBlackoutCheckbox->Draw(); mLightOctavesCheckbox->Draw(); mGuitarLinesCheckbox->Draw(); } void LinnstrumentControl::BuildControllerList() { mControllerList->Clear(); const std::vector<std::string>& devices = mDevice.GetPortList(false); for (int i = 0; i < devices.size(); ++i) mControllerList->AddLabel(devices[i].c_str(), i); } void LinnstrumentControl::OnScaleChanged() { UpdateScaleDisplay(); } void LinnstrumentControl::UpdateScaleDisplay() { //SendScaleInfo(); for (int y = 0; y < kRows; ++y) { mDevice.SendCC(21, y); //only set row once, to cut down on messages for (int x = 0; x < kCols; ++x) { SetGridColor(x, y, GetDesiredGridColor(x, y), true); } } } void LinnstrumentControl::SetGridColor(int x, int y, LinnstrumentColor color, bool ignoreRow /*= false*/) { if (x < kCols && y < kRows) { if (color != mGridColorState[x + y * kCols]) { if (!ignoreRow) mDevice.SendCC(21, y); mDevice.SendCC(20, x + 1); mDevice.SendCC(22, color); mGridColorState[x + y * kCols] = color; } } } LinnstrumentControl::LinnstrumentColor LinnstrumentControl::GetDesiredGridColor(int x, int y) { if (mBlackout) return kLinnColor_Black; if (mGuitarLines) { if (x % 2 == 1) { /*LinnstrumentColor darkColor = kLinnColor_Green; LinnstrumentColor lightColor = kLinnColor_Lime; if (x % 6 == 1) { darkColor = kLinnColor_Blue; lightColor = kLinnColor_Cyan; } if (x % 4 == 1) { if (y % 4 < 2) return darkColor; return lightColor; } else { if (y % 4 < 2) return lightColor; return darkColor; }*/ LinnstrumentColor colors[4]; colors[0] = kLinnColor_Lime; colors[1] = kLinnColor_Green; colors[2] = kLinnColor_Cyan; colors[3] = kLinnColor_Blue; int horizontalIndex = x / 2; int verticalIndex = (7 - y) / 2; return colors[(horizontalIndex + verticalIndex) % 4]; } else { return kLinnColor_Black; } } int pitch = GridToPitch(x, y); if (TheScale->IsRoot(pitch)) return kLinnColor_Green; if (TheScale->IsInPentatonic(pitch)) return kLinnColor_Orange; if (TheScale->IsInScale(pitch)) return kLinnColor_Yellow; return kLinnColor_Black; } int LinnstrumentControl::GridToPitch(int x, int y) { return 30 + x + y * 5 + (mLinnstrumentOctave - 5) * 12; } void LinnstrumentControl::SetPitchColor(int pitch, LinnstrumentColor color) { for (int y = 0; y < kRows; ++y) { for (int x = 0; x < kCols; ++x) { if (GridToPitch(x, y) == pitch) SetGridColor(x, y, (color == kLinnColor_Off) ? GetDesiredGridColor(x, y) : color); } } } void LinnstrumentControl::SendScaleInfo() { /*NRPN format: send these 6 messages in a row: 1011nnnn 01100011 ( 99) 0vvvvvvv NRPN parameter number MSB CC 1011nnnn 01100010 ( 98) 0vvvvvvv NRPN parameter number LSB CC 1011nnnn 00000110 ( 6) 0vvvvvvv NRPN parameter value MSB CC 1011nnnn 00100110 ( 38) 0vvvvvvv NRPN parameter value LSB CC 1011nnnn 01100101 (101) 01111111 (127) RPN parameter number Reset MSB CC 1011nnnn 01100100 (100) 01111111 (127) RPN parameter number Reset LSB CC Linnstrument NRPN scale messages: 203 0-1 Global Main Note Light C (0: Off, 1: On) 204 0-1 Global Main Note Light C# (0: Off, 1: On) 205 0-1 Global Main Note Light D (0: Off, 1: On) 206 0-1 Global Main Note Light D# (0: Off, 1: On) 207 0-1 Global Main Note Light E (0: Off, 1: On) 208 0-1 Global Main Note Light F (0: Off, 1: On) 209 0-1 Global Main Note Light F# (0: Off, 1: On) 210 0-1 Global Main Note Light G (0: Off, 1: On) 211 0-1 Global Main Note Light G# (0: Off, 1: On) 212 0-1 Global Main Note Light A (0: Off, 1: On) 213 0-1 Global Main Note Light A# (0: Off, 1: On) 214 0-1 Global Main Note Light B (0: Off, 1: On) 215 0-1 Global Accent Note Light C (0: Off, 1: On) 216 0-1 Global Accent Note Light C# (0: Off, 1: On) 217 0-1 Global Accent Note Light D (0: Off, 1: On) 218 0-1 Global Accent Note Light D# (0: Off, 1: On) 219 0-1 Global Accent Note Light E (0: Off, 1: On) 220 0-1 Global Accent Note Light F (0: Off, 1: On) 221 0-1 Global Accent Note Light F# (0: Off, 1: On) 222 0-1 Global Accent Note Light G (0: Off, 1: On) 223 0-1 Global Accent Note Light G# (0: Off, 1: On) 224 0-1 Global Accent Note Light A (0: Off, 1: On) 225 0-1 Global Accent Note Light A# (0: Off, 1: On) 226 0-1 Global Accent Note Light B (0: Off, 1: On) */ const unsigned char setMainNoteBase = 203; const unsigned char setAccentNoteBase = 215; if (TheScale->GetPitchesPerOctave() == 12) //linnstrument only works with 12-tet { for (int pitch = 0; pitch < 12; ++pitch) { //set main note int number = setMainNoteBase + pitch; SendNRPN(number, TheScale->IsInScale(pitch)); std::this_thread::sleep_for(10ms); //set accent note number = setAccentNoteBase + pitch; SendNRPN(number, TheScale->IsRoot(pitch)); std::this_thread::sleep_for(10ms); } } } void LinnstrumentControl::SendNRPN(int param, int value) { const unsigned char channelHeader = 177; mDevice.SendData(channelHeader, 99, param >> 7); mDevice.SendData(channelHeader, 98, param & 0x7f); mDevice.SendData(channelHeader, 6, value >> 7); mDevice.SendData(channelHeader, 38, value & 0x7f); mDevice.SendData(channelHeader, 101, 127); mDevice.SendData(channelHeader, 100, 127); } void LinnstrumentControl::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (voiceIdx == -1) voiceIdx = 0; mModulators[voiceIdx] = modulation; if (pitch >= 0 && pitch < 128) { mNoteAge[pitch].mTime = velocity > 0 ? -1 : time; if (velocity > 0) mNoteAge[pitch].mVoiceIndex = voiceIdx; mNoteAge[pitch].Update(pitch, this); } } void LinnstrumentControl::OnMidiNote(MidiNote& note) { if (mControlPlayedLights) mDevice.SendNote(gTime, note.mPitch, 0, false, note.mChannel); //don't allow linnstrument to light played notes } void LinnstrumentControl::OnMidiControl(MidiControl& control) { if (control.mControl == 101) mLastReceivedNRPNParamMSB = control.mValue; if (control.mControl == 100) mLastReceivedNRPNParamLSB = control.mValue; if (control.mControl == 6) mLastReceivedNRPNValueMSB = control.mValue; if (control.mControl == 38) { mLastReceivedNRPNValueLSB = control.mValue; int nrpnParam = mLastReceivedNRPNParamMSB << 7 | mLastReceivedNRPNParamLSB; int nrpnValue = mLastReceivedNRPNValueMSB << 7 | mLastReceivedNRPNValueLSB; if (nrpnParam == 36) mLinnstrumentOctave = nrpnValue; } } void LinnstrumentControl::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mControllerList) { mDevice.ConnectOutput(mControllerIndex); UpdateScaleDisplay(); } } void LinnstrumentControl::DropdownClicked(DropdownList* list) { BuildControllerList(); } void LinnstrumentControl::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mBlackoutCheckbox) { if (mBlackout) mGuitarLines = false; UpdateScaleDisplay(); } if (checkbox == mGuitarLinesCheckbox) { if (mGuitarLines) mBlackout = false; UpdateScaleDisplay(); } } void LinnstrumentControl::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void LinnstrumentControl::SetUpFromSaveData() { InitController(); } void LinnstrumentControl::NoteAge::Update(int pitch, LinnstrumentControl* linnstrument) { if (!linnstrument->mControlPlayedLights) return; float age = gTime - mTime; LinnstrumentColor newColor; if (mTime < 0 || age < 0) newColor = kLinnColor_Red; else if (age < linnstrument->mDecayMs * .25f) newColor = kLinnColor_Pink; else if (age < linnstrument->mDecayMs * .5f) newColor = kLinnColor_Cyan; else if (age < linnstrument->mDecayMs) newColor = kLinnColor_Blue; else newColor = kLinnColor_Off; if (mVoiceIndex != -1 && linnstrument->mModulators[mVoiceIndex].pitchBend) { float bendRounded = round(linnstrument->mModulators[mVoiceIndex].pitchBend->GetValue(0)); pitch += (int)bendRounded; } if (newColor != mColor || pitch != mOutputPitch) { for (int i = -2; i <= 2; ++i) { if (i != 0 && !linnstrument->mLightOctaves) continue; LinnstrumentColor color = newColor; if (i != 0) { if (mTime < 0 || age < 0) color = kLinnColor_Pink; else color = kLinnColor_Off; } if (pitch != mOutputPitch) linnstrument->SetPitchColor(mOutputPitch + i * TheScale->GetPitchesPerOctave(), kLinnColor_Off); linnstrument->SetPitchColor(pitch + i * TheScale->GetPitchesPerOctave(), color); } mColor = newColor; mOutputPitch = pitch; } } ```
/content/code_sandbox/Source/LinnstrumentControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,723
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteDisplayer.h // Bespoke // // Created by Ryan Challinor on 6/17/15. // // #pragma once #include "IDrawableModule.h" #include "NoteEffectBase.h" class NoteDisplayer : public NoteEffectBase, public IDrawableModule { public: NoteDisplayer() = default; static IDrawableModule* Create() { return new NoteDisplayer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsResizable() const override { return true; } void Resize(float w, float h) override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void DrawNoteName(int pitch, float y) const; float mWidth{ 160 }; float mHeight{ 60 }; int mVelocities[128]{}; int mVoiceIds[128]{}; }; ```
/content/code_sandbox/Source/NoteDisplayer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
416
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== UserPrefsEditor.cpp Created: 12 Feb 2021 10:29:53pm Author: Ryan Challinor ============================================================================== */ #include "UserPrefsEditor.h" #include "ModularSynth.h" #include "SynthGlobals.h" #include "UserPrefs.h" #include "PatchCable.h" #include "QwertyToPitchMapping.h" #include "juce_audio_devices/juce_audio_devices.h" #include "juce_gui_basics/juce_gui_basics.h" UserPrefsEditor::UserPrefsEditor() { } UserPrefsEditor::~UserPrefsEditor() { } void UserPrefsEditor::CreateUIControls() { SetName("settings"); IDrawableModule::CreateUIControls(); for (auto* pref : UserPrefs.mUserPrefs) pref->SetUpControl(this); mCategorySelector = new RadioButton(this, "category", 5, 10, (int*)(&mCategory), kRadioHorizontal); mSaveButton = new ClickButton(this, "save", -1, -1); mCancelButton = new ClickButton(this, "cancel", -1, -1); mCategorySelector->AddLabel("general", (int)UserPrefCategory::General); mCategorySelector->AddLabel("graphics", (int)UserPrefCategory::Graphics); mCategorySelector->AddLabel("paths", (int)UserPrefCategory::Paths); std::array<int, 5> oversampleAmounts = { 1, 2, 4, 8, 16 }; for (int oversample : oversampleAmounts) { UserPrefs.oversampling.GetDropdown()->AddLabel(ofToString(oversample), oversample); if (UserPrefs.oversampling.Get() == oversample) UserPrefs.oversampling.GetIndex() = oversample; } UserPrefs.cable_drop_behavior.GetIndex() = 0; UserPrefs.cable_drop_behavior.GetDropdown()->AddLabel("show quickspawn", (int)CableDropBehavior::ShowQuickspawn); UserPrefs.cable_drop_behavior.GetDropdown()->AddLabel("do nothing", (int)CableDropBehavior::DoNothing); UserPrefs.cable_drop_behavior.GetDropdown()->AddLabel("disconnect", (int)CableDropBehavior::DisconnectCable); for (int i = 0; i < UserPrefs.cable_drop_behavior.GetDropdown()->GetNumValues(); ++i) { if (UserPrefs.cable_drop_behavior.GetDropdown()->GetElement(i).mLabel == UserPrefs.cable_drop_behavior.Get()) UserPrefs.cable_drop_behavior.GetIndex() = i; } UserPrefs.qwerty_to_pitch_mode.GetDropdown()->AddLabel("Ableton", (int)QwertyToPitchMappingMode::Ableton); UserPrefs.qwerty_to_pitch_mode.GetDropdown()->AddLabel("Fruity", (int)QwertyToPitchMappingMode::Fruity); for (int i = 0; i < UserPrefs.qwerty_to_pitch_mode.GetDropdown()->GetNumValues(); ++i) { if (UserPrefs.qwerty_to_pitch_mode.GetDropdown()->GetElement(i).mLabel == UserPrefs.qwerty_to_pitch_mode.Get()) UserPrefs.qwerty_to_pitch_mode.GetIndex() = i; } } void UserPrefsEditor::Show() { SetPosition(100 / TheSynth->GetUIScale() - TheSynth->GetDrawOffset().x, 250 / TheSynth->GetUIScale() - TheSynth->GetDrawOffset().y); UpdateDropdowns({}); SetShowing(true); if (TheSynth->HasFatalError()) { mSaveButton->SetLabel("save and exit"); mCancelButton->SetShowing(false); } } void UserPrefsEditor::CreatePrefsFileIfNonexistent() { UpdateDropdowns({}); if (!juce::File(TheSynth->GetUserPrefsPath()).existsAsFile()) { Save(); UserPrefs.mUserPrefsFile.open(TheSynth->GetUserPrefsPath()); } } void UserPrefsEditor::UpdateDropdowns(std::vector<DropdownList*> toUpdate) { auto& deviceManager = TheSynth->GetAudioDeviceManager(); int i; if (toUpdate.empty() || VectorContains(UserPrefs.devicetype.GetDropdown(), toUpdate)) { UserPrefs.devicetype.GetIndex() = -1; UserPrefs.devicetype.GetDropdown()->Clear(); UserPrefs.devicetype.GetDropdown()->AddLabel("auto", -1); i = 0; for (auto* deviceType : deviceManager.getAvailableDeviceTypes()) { UserPrefs.devicetype.GetDropdown()->AddLabel(deviceType->getTypeName().toStdString(), i); if (deviceType == deviceManager.getCurrentDeviceTypeObject() && UserPrefs.devicetype.Get() != "auto") UserPrefs.devicetype.GetIndex() = i; ++i; } } auto* selectedDeviceType = UserPrefs.devicetype.GetIndex() != -1 ? deviceManager.getAvailableDeviceTypes()[UserPrefs.devicetype.GetIndex()] : deviceManager.getCurrentDeviceTypeObject(); selectedDeviceType->scanForDevices(); if (toUpdate.empty() || VectorContains(UserPrefs.audio_output_device.GetDropdown(), toUpdate)) { UserPrefs.audio_output_device.GetIndex() = -1; UserPrefs.audio_output_device.GetDropdown()->Clear(); UserPrefs.audio_output_device.GetDropdown()->AddLabel("none", -2); UserPrefs.audio_output_device.GetDropdown()->AddLabel("auto", -1); i = 0; for (auto outputDevice : selectedDeviceType->getDeviceNames()) { UserPrefs.audio_output_device.GetDropdown()->AddLabel(outputDevice.toStdString(), i); if (deviceManager.getCurrentAudioDevice() != nullptr && i == selectedDeviceType->getIndexOfDevice(deviceManager.getCurrentAudioDevice(), false) && UserPrefs.audio_output_device.Get() != "auto") UserPrefs.audio_output_device.GetIndex() = i; ++i; } if (UserPrefs.audio_output_device.GetIndex() == -1) //update dropdown to match requested value, in case audio system failed to start { for (int j = -2; j < i; ++j) { if (UserPrefs.audio_output_device.GetDropdown()->GetLabel(j) == UserPrefs.audio_output_device.Get()) UserPrefs.audio_output_device.GetIndex() = j; } } } if (toUpdate.empty() || VectorContains(UserPrefs.audio_input_device.GetDropdown(), toUpdate)) { UserPrefs.audio_input_device.GetIndex() = -1; if (UserPrefs.audio_input_device.Get() == "none") UserPrefs.audio_input_device.GetIndex() = -2; UserPrefs.audio_input_device.GetDropdown()->Clear(); UserPrefs.audio_input_device.GetDropdown()->AddLabel("none", -2); UserPrefs.audio_input_device.GetDropdown()->AddLabel("auto", -1); i = 0; for (auto inputDevice : selectedDeviceType->getDeviceNames(true)) { UserPrefs.audio_input_device.GetDropdown()->AddLabel(inputDevice.toStdString(), i); if (deviceManager.getCurrentAudioDevice() != nullptr && i == selectedDeviceType->getIndexOfDevice(deviceManager.getCurrentAudioDevice(), true) && UserPrefs.audio_input_device.Get() != "auto") UserPrefs.audio_input_device.GetIndex() = i; ++i; } if (UserPrefs.audio_input_device.GetIndex() < 0) //update dropdown to match requested value, in case audio system failed to start { for (int j = -2; j < i; ++j) { if (UserPrefs.audio_input_device.GetDropdown()->GetLabel(j) == UserPrefs.audio_input_device.Get()) UserPrefs.audio_input_device.GetIndex() = j; } } } juce::String outputDeviceName; if (UserPrefs.audio_output_device.GetIndex() >= 0) outputDeviceName = selectedDeviceType->getDeviceNames()[UserPrefs.audio_output_device.GetIndex()]; else if (UserPrefs.audio_output_device.GetIndex() == -1) outputDeviceName = selectedDeviceType->getDeviceNames()[selectedDeviceType->getDefaultDeviceIndex(false)]; juce::String inputDeviceName; if (selectedDeviceType->hasSeparateInputsAndOutputs()) { if (UserPrefs.audio_input_device.GetIndex() >= 0) inputDeviceName = selectedDeviceType->getDeviceNames(true)[UserPrefs.audio_input_device.GetIndex()]; else if (UserPrefs.audio_input_device.GetIndex() == -1) inputDeviceName = selectedDeviceType->getDeviceNames()[selectedDeviceType->getDefaultDeviceIndex(true)]; } else { inputDeviceName = outputDeviceName; } auto* selectedDevice = deviceManager.getCurrentAudioDevice(); auto setup = deviceManager.getAudioDeviceSetup(); if (selectedDevice == nullptr || selectedDevice->getTypeName() != selectedDeviceType->getTypeName() || setup.outputDeviceName != outputDeviceName || setup.inputDeviceName != inputDeviceName) selectedDevice = selectedDeviceType->createDevice(outputDeviceName, inputDeviceName); if (selectedDevice == nullptr) return; if (toUpdate.empty() || VectorContains(UserPrefs.samplerate.GetDropdown(), toUpdate)) { UserPrefs.samplerate.GetIndex() = -1; UserPrefs.samplerate.GetDropdown()->Clear(); i = 0; for (auto rate : selectedDevice->getAvailableSampleRates()) { UserPrefs.samplerate.GetDropdown()->AddLabel(ofToString(rate), i); if (rate == gSampleRate / UserPrefs.oversampling.Get()) UserPrefs.samplerate.GetIndex() = i; ++i; } } if (toUpdate.empty() || VectorContains(UserPrefs.buffersize.GetDropdown(), toUpdate)) { UserPrefs.buffersize.GetIndex() = -1; UserPrefs.buffersize.GetDropdown()->Clear(); i = 0; for (auto bufferSize : selectedDevice->getAvailableBufferSizes()) { UserPrefs.buffersize.GetDropdown()->AddLabel(ofToString(bufferSize), i); if (bufferSize == gBufferSize / UserPrefs.oversampling.Get()) UserPrefs.buffersize.GetIndex() = i; ++i; } } if (selectedDevice != deviceManager.getCurrentAudioDevice()) delete selectedDevice; } void UserPrefsEditor::DrawModule() { auto& deviceManager = TheSynth->GetAudioDeviceManager(); auto* selectedDeviceType = UserPrefs.devicetype.GetIndex() != -1 ? deviceManager.getAvailableDeviceTypes()[UserPrefs.devicetype.GetIndex()] : deviceManager.getCurrentDeviceTypeObject(); mCategorySelector->Draw(); int controlX = 175; int controlY = 50; bool hasPrefThatRequiresRestart = false; for (auto* pref : UserPrefs.mUserPrefs) { bool onPage = pref->mCategory == mCategory; bool hide = false; if (pref == &UserPrefs.audio_input_device) hide = !selectedDeviceType->hasSeparateInputsAndOutputs(); if (pref == &UserPrefs.position_x || pref == &UserPrefs.position_y) hide = !UserPrefs.set_manual_window_position.Get(); pref->GetControl()->SetShowing(onPage && !hide); if (pref->GetControl()->IsShowing()) { pref->GetControl()->SetPosition(controlX, controlY); DrawTextNormal(pref->mName, 3, pref->GetControl()->GetPosition(K(local)).y + 12); pref->GetControl()->Draw(); if (PrefRequiresRestart(pref) && pref->DiffersFromSavedValue()) { DrawRightLabel(pref->GetControl(), "*", ofColor::magenta, 4); hasPrefThatRequiresRestart = true; } } if (onPage) controlY += 17; } controlY += 17; mSaveButton->SetPosition(controlX, controlY); mSaveButton->Draw(); mCancelButton->SetPosition(mSaveButton->GetRect(K(local)).getMaxX() + 10, controlY); mCancelButton->Draw(); mWidth = 1150; mHeight = controlY + 20; if (UserPrefs.devicetype.GetDropdown()->GetLabel(UserPrefs.devicetype.GetIndex()) == "DirectSound") DrawRightLabel(UserPrefs.devicetype.GetControl(), "warning: DirectSound can cause crackle and strange behavior for some sample rates and buffer sizes", ofColor::yellow); if (!selectedDeviceType->hasSeparateInputsAndOutputs() && mCategory == UserPrefCategory::General) { ofRectangle rect = UserPrefs.audio_output_device.GetControl()->GetRect(true); ofPushStyle(); ofSetColor(ofColor::white); DrawTextNormal("note: " + UserPrefs.devicetype.GetDropdown()->GetLabel(UserPrefs.devicetype.GetIndex()) + " uses the same audio device for output and input", rect.x, rect.getMaxY() + 14, 11); ofPopStyle(); } if (UserPrefs.samplerate.GetDropdown()->GetNumValues() == 0) { if (selectedDeviceType->hasSeparateInputsAndOutputs()) DrawRightLabel(UserPrefs.samplerate.GetControl(), "couldn't find a sample rate compatible between these output and input devices", ofColor::yellow); else DrawRightLabel(UserPrefs.samplerate.GetControl(), "couldn't find any sample rates for this device, for some reason (is it plugged in?)", ofColor::yellow); } if (UserPrefs.buffersize.GetDropdown()->GetNumValues() == 0) { if (selectedDeviceType->hasSeparateInputsAndOutputs()) DrawRightLabel(UserPrefs.buffersize.GetControl(), "couldn't find a buffer size compatible between these output and input devices", ofColor::yellow); else DrawRightLabel(UserPrefs.buffersize.GetControl(), "couldn't find any buffer sizes for this device, for some reason (is it plugged in?)", ofColor::yellow); } DrawRightLabel(UserPrefs.width.GetControl(), "(currently: " + ofToString(ofGetWidth()) + ")", ofColor::white); DrawRightLabel(UserPrefs.height.GetControl(), "(currently: " + ofToString(ofGetHeight()) + ")", ofColor::white); if (UserPrefs.set_manual_window_position.Get()) { auto pos = TheSynth->GetMainComponent()->getTopLevelComponent()->getScreenPosition(); DrawRightLabel(UserPrefs.position_y.GetControl(), "(currently: " + ofToString(pos.y) + ")", ofColor::white); DrawRightLabel(UserPrefs.position_x.GetControl(), "(currently: " + ofToString(pos.x) + ")", ofColor::white); } DrawRightLabel(UserPrefs.zoom.GetControl(), "(currently: " + ofToString(gDrawScale) + ")", ofColor::white); DrawRightLabel(UserPrefs.recordings_path.GetControl(), "(default: " + UserPrefs.recordings_path.GetDefault() + ")", ofColor::white); DrawRightLabel(UserPrefs.tooltips.GetControl(), "(default: " + UserPrefs.tooltips.GetDefault() + ")", ofColor::white); DrawRightLabel(UserPrefs.layout.GetControl(), "(default: " + UserPrefs.layout.GetDefault() + ")", ofColor::white); DrawRightLabel(UserPrefs.youtube_dl_path.GetControl(), "(default: " + UserPrefs.youtube_dl_path.GetDefault() + ")", ofColor::white); DrawRightLabel(UserPrefs.ffmpeg_path.GetControl(), "(default: " + UserPrefs.ffmpeg_path.GetDefault() + ")", ofColor::white); if (hasPrefThatRequiresRestart) DrawRightLabel(mCancelButton, "*requires restart before taking effect", ofColor::magenta, 4); } void UserPrefsEditor::DrawRightLabel(IUIControl* control, std::string text, ofColor color, float offsetX) { if (control->IsShowing()) { ofRectangle rect = control->GetRect(true); ofPushStyle(); ofSetColor(color); DrawTextNormal(text, rect.getMaxX() + offsetX, rect.getMaxY() - 3, 11); ofPopStyle(); } } void UserPrefsEditor::CleanUpSave(std::string& json) //remove the markup hack that got the json file to save ordered { for (int i = 0; i < (int)UserPrefs.mUserPrefs.size(); ++i) ofStringReplace(json, "**" + UserPrefsHolder::ToStringLeadingZeroes(i) + "**", "", true); } bool UserPrefsEditor::PrefRequiresRestart(UserPref* pref) const { return pref == &UserPrefs.devicetype || pref == &UserPrefs.audio_output_device || pref == &UserPrefs.audio_input_device || pref == &UserPrefs.samplerate || pref == &UserPrefs.buffersize || pref == &UserPrefs.oversampling || pref == &UserPrefs.max_output_channels || pref == &UserPrefs.max_input_channels || pref == &UserPrefs.record_buffer_length_minutes || pref == &UserPrefs.show_minimap; } void UserPrefsEditor::Save() { //make a copy ofxJSONElement prefsFile = UserPrefs.mUserPrefsFile; //remove legacy prefs prefsFile.removeMember("vstsearchdirs"); prefsFile.removeMember("youtube-dl_path"); for (int i = 0; i < (int)UserPrefs.mUserPrefs.size(); ++i) UserPrefs.mUserPrefs[i]->Save(i, prefsFile); std::string output = prefsFile.getRawString(true); CleanUpSave(output); juce::File file(TheSynth->GetUserPrefsPath()); file.create(); file.replaceWithText(output); if (TheSynth->HasFatalError()) //this popup spawned at load due to a bad init setting. in this case, the button says "save and exit" juce::JUCEApplicationBase::quit(); } void UserPrefsEditor::ButtonClicked(ClickButton* button, double time) { if (button == mSaveButton) { Save(); SetShowing(false); } if (button == mCancelButton) SetShowing(false); } void UserPrefsEditor::CheckboxUpdated(Checkbox* checkbox, double time) { } void UserPrefsEditor::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (!TheSynth->IsLoadingState()) { if (slider == UserPrefs.ui_scale.GetSlider()) TheSynth->SetUIScale(UserPrefs.ui_scale.Get()); if (slider == UserPrefs.lissajous_r.GetSlider() || slider == UserPrefs.lissajous_g.GetSlider() || slider == UserPrefs.lissajous_b.GetSlider()) { ModularSynth::sBackgroundLissajousR = UserPrefs.lissajous_r.Get(); ModularSynth::sBackgroundLissajousG = UserPrefs.lissajous_g.Get(); ModularSynth::sBackgroundLissajousB = UserPrefs.lissajous_b.Get(); } if (slider == UserPrefs.background_r.GetSlider() || slider == UserPrefs.background_g.GetSlider() || slider == UserPrefs.background_b.GetSlider()) { ModularSynth::sBackgroundR = UserPrefs.background_r.Get(); ModularSynth::sBackgroundG = UserPrefs.background_g.Get(); ModularSynth::sBackgroundB = UserPrefs.background_b.Get(); } if (slider == UserPrefs.cable_alpha.GetSlider()) ModularSynth::sCableAlpha = UserPrefs.cable_alpha.Get(); } } void UserPrefsEditor::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void UserPrefsEditor::TextEntryComplete(TextEntry* entry) { } void UserPrefsEditor::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == UserPrefs.devicetype.GetDropdown()) { UpdateDropdowns({ UserPrefs.audio_output_device.GetDropdown(), UserPrefs.audio_input_device.GetDropdown(), UserPrefs.samplerate.GetDropdown(), UserPrefs.buffersize.GetDropdown() }); } if (list == UserPrefs.audio_output_device.GetDropdown()) { UpdateDropdowns({ UserPrefs.samplerate.GetDropdown(), UserPrefs.buffersize.GetDropdown() }); } if (list == UserPrefs.audio_input_device.GetDropdown()) { UpdateDropdowns({ UserPrefs.samplerate.GetDropdown(), UserPrefs.buffersize.GetDropdown() }); } } void UserPrefsEditor::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { } std::vector<IUIControl*> UserPrefsEditor::ControlsToNotSetDuringLoadState() const { return GetUIControls(); } std::vector<IUIControl*> UserPrefsEditor::ControlsToIgnoreInSaveState() const { return GetUIControls(); } ```
/content/code_sandbox/Source/UserPrefsEditor.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
4,627
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== UIControlMacros.h Created: 12 Feb 2020 11:28:22pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "SynthGlobals.h" // variable-argument macro technique from path_to_url #define GLUE(x, y) x y #define RETURN_ARG_COUNT(_1_, _2_, _3_, _4_, _5_, count, ...) count #define EXPAND_ARGS(args) RETURN_ARG_COUNT args #define COUNT_ARGS_MAX5(...) EXPAND_ARGS((__VA_ARGS__, 5, 4, 3, 2, 1, 0)) #define OVERLOAD_MACRO2(name, count) name##count #define OVERLOAD_MACRO1(name, count) OVERLOAD_MACRO2(name, count) #define OVERLOAD_MACRO(name, count) OVERLOAD_MACRO1(name, count) #define CALL_OVERLOAD(name, ...) GLUE(OVERLOAD_MACRO(name, COUNT_ARGS_MAX5(__VA_ARGS__)), (__VA_ARGS__)) #define UIBLOCK0() UIBLOCK3(3, 3, 100) #define UIBLOCK1(A) UIBLOCK3(3, 3, A) #define UIBLOCK2(A, B) UIBLOCK3(A, B, 100) #define UIBLOCK3(A, B, C) \ { \ float xPos = A; \ float yPos = B; \ float originalY = B; \ float sliderWidth = C; \ float originalSliderWidth = C; \ IUIControl* lastUIControl = nullptr; \ float xMax = 0; \ float yMax = 0; \ float xOffset = 0; \ float savedX = 0; \ float savedY = 0; \ UNUSED(originalY); \ UNUSED(originalSliderWidth); \ UNUSED(sliderWidth); \ UNUSED(savedX); \ UNUSED(savedY); #define UIBLOCK(...) CALL_OVERLOAD(UIBLOCK, __VA_ARGS__) #define UIBLOCK_SHIFTDOWN() yPos += lastUIControl->GetDimensions().y + 2; #define UIBLOCK_SHIFTUP() yPos -= lastUIControl->GetDimensions().y + 2; #define UIBLOCK_SHIFTRIGHT() \ xOffset = lastUIControl->GetPosition(true).x + lastUIControl->GetDimensions().x + 3 - xPos; \ yPos = lastUIControl->GetPosition(true).y; #define UIBLOCK_SHIFTLEFT() \ xOffset = lastUIControl->GetPosition(true).x - xPos; \ yPos = lastUIControl->GetPosition(true).y; #define UIBLOCK_SHIFTX(amount) \ xOffset += amount; \ if (lastUIControl != nullptr) \ { \ yPos = lastUIControl->GetPosition(true).y; \ } #define UIBLOCK_SHIFTY(amount) yPos += amount; #define UIBLOCK_NEWLINE() xOffset = 0; #define UIBLOCK_NEWCOLUMN() \ xPos += sliderWidth + 3; \ yPos = originalY; #define UIBLOCK_PUSHSLIDERWIDTH(w) sliderWidth = w; #define UIBLOCK_POPSLIDERWIDTH() sliderWidth = originalSliderWidth; #define UIBLOCK_SAVEPOSITION() \ savedX = xPos; \ savedY = yPos; #define UIBLOCK_RESTOREPOSITION() \ xPos = savedX; \ yPos = savedY; #define UIBLOCK_OWNER this #define UIBLOCK_UPDATEEXTENTS() \ xMax = MAX(xMax, lastUIControl->GetPosition(true).x + lastUIControl->GetDimensions().x); \ yMax = MAX(yMax, lastUIControl->GetPosition(true).y + lastUIControl->GetDimensions().y); #define UICONTROL_BASICS(name) UIBLOCK_OWNER, name, xPos + xOffset, yPos #define FLOATSLIDER(slider, name, var, min, max) \ slider = new FloatSlider(UICONTROL_BASICS(name), sliderWidth, 15, var, min, max); \ lastUIControl = slider; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define FLOATSLIDER_DIGITS(slider, name, var, min, max, digits) \ slider = new FloatSlider(UICONTROL_BASICS(name), sliderWidth, 15, var, min, max, digits); \ lastUIControl = slider; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define INTSLIDER(slider, name, var, min, max) \ slider = new IntSlider(UICONTROL_BASICS(name), sliderWidth, 15, var, min, max); \ lastUIControl = slider; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define CHECKBOX(checkbox, name, var) \ checkbox = new Checkbox(UICONTROL_BASICS(name), var); \ lastUIControl = checkbox; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define DROPDOWN(dropdown, name, var, width) \ dropdown = new DropdownList(UICONTROL_BASICS(name), var, width); \ lastUIControl = dropdown; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define BUTTON(button, name) \ button = new ClickButton(UICONTROL_BASICS(name)); \ lastUIControl = button; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define BUTTON_STYLE(button, name, style) \ button = new ClickButton(UICONTROL_BASICS(name), style); \ lastUIControl = button; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define TEXTENTRY(entry, name, length, var) \ entry = new TextEntry(UICONTROL_BASICS(name), length, var); \ lastUIControl = entry; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define TEXTENTRY_NUM(entry, name, length, var, min, max) \ entry = new TextEntry(UICONTROL_BASICS(name), length, var, min, max); \ lastUIControl = entry; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define UICONTROL_CUSTOM(var, instance) \ var = instance; \ lastUIControl = var; \ UIBLOCK_SHIFTDOWN(); \ UIBLOCK_UPDATEEXTENTS(); #define UIBLOCKWIDTH() xMax + 3 #define UIBLOCKHEIGHT() yMax + 2 #define ENDUIBLOCK0() } #define ENDUIBLOCK1(A) \ A = UIBLOCKHEIGHT(); \ } #define ENDUIBLOCK2(A, B) \ A = UIBLOCKWIDTH(); \ B = UIBLOCKHEIGHT(); \ } #define ENDUIBLOCK(...) CALL_OVERLOAD(ENDUIBLOCK, __VA_ARGS__) ```
/content/code_sandbox/Source/UIControlMacros.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,590
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Ramper.cpp // Bespoke // // Created by Ryan Challinor on 5/19/16. // // #include "Ramper.h" #include "ModularSynth.h" #include "PatchCableSource.h" Ramper::Ramper() { } void Ramper::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } Ramper::~Ramper() { TheTransport->RemoveAudioPoller(this); } void Ramper::CreateUIControls() { IDrawableModule::CreateUIControls(); mLengthSelector = new DropdownList(this, "length", 3, 3, (int*)(&mLength)); mTriggerButton = new ClickButton(this, "start", 67, 3); mTargetValueSlider = new FloatSlider(this, "target", 3, 20, 94, 15, &mTargetValue, 0, 1); mControlCable = new PatchCableSource(this, kConnectionType_ValueSetter); //mControlCable->SetManualPosition(86, 10); AddPatchCableSource(mControlCable); mLengthSelector->AddLabel("64", kInterval_64); mLengthSelector->AddLabel("32", kInterval_32); mLengthSelector->AddLabel("16", kInterval_16); mLengthSelector->AddLabel("8", kInterval_8); mLengthSelector->AddLabel("4", kInterval_4); mLengthSelector->AddLabel("2", kInterval_2); mLengthSelector->AddLabel("1n", kInterval_1n); mLengthSelector->AddLabel("2n", kInterval_2n); mLengthSelector->AddLabel("4n", kInterval_4n); mLengthSelector->AddLabel("4nt", kInterval_4nt); mLengthSelector->AddLabel("8n", kInterval_8n); mLengthSelector->AddLabel("8nt", kInterval_8nt); mLengthSelector->AddLabel("16n", kInterval_16n); mLengthSelector->AddLabel("16nt", kInterval_16nt); mLengthSelector->AddLabel("32n", kInterval_32n); mLengthSelector->AddLabel("64n", kInterval_64n); } void Ramper::OnTransportAdvanced(float amount) { if (!mEnabled) mRamping = false; if (mRamping) { float curMeasure = TheTransport->GetMeasure(gTime) + TheTransport->GetMeasurePos(gTime); float measureProgress = curMeasure - mStartMeasure; float length = TheTransport->GetDuration(mLength) / TheTransport->MsPerBar(); float progress = measureProgress / length; if (progress >= 0 && progress < 1) { for (auto* control : mUIControls) { if (control != nullptr) control->SetValue(ofLerp(mStartValue, mTargetValue, progress), gTime); } } else if (progress >= 1) { for (auto* control : mUIControls) { if (control != nullptr) control->SetValue(mTargetValue, gTime); } mRamping = false; } } } void Ramper::DrawModule() { if (Minimized() || IsVisible() == false) return; mLengthSelector->Draw(); mTriggerButton->Draw(); mTargetValueSlider->Draw(); } void Ramper::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); } void Ramper::MouseReleased() { IDrawableModule::MouseReleased(); } bool Ramper::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); return false; } void Ramper::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { for (size_t i = 0; i < mUIControls.size(); ++i) { if (i < mControlCable->GetPatchCables().size()) { mUIControls[i] = dynamic_cast<IUIControl*>(mControlCable->GetPatchCables()[i]->GetTarget()); if (i == 0) { FloatSlider* floatSlider = dynamic_cast<FloatSlider*>(mUIControls[i]); if (floatSlider) mTargetValueSlider->MatchExtents(floatSlider); } } else { mUIControls[i] = nullptr; } } } void Ramper::Go(double time) { if (mUIControls[0] != nullptr) { mStartValue = mUIControls[0]->GetValue(); mStartMeasure = TheTransport->GetMeasureTime(time); mRamping = true; } } void Ramper::OnPulse(double time, float velocity, int flags) { if (velocity > 0 && mEnabled) Go(time); } void Ramper::ButtonClicked(ClickButton* button, double time) { if (button == mTriggerButton) Go(time); } void Ramper::GetModuleDimensions(float& width, float& height) { width = 100; height = 38; } void Ramper::SaveLayout(ofxJSONElement& moduleInfo) { } void Ramper::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void Ramper::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/Ramper.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,305
```objective-c #pragma once #include "SynthGlobals.h" void UpdateUserData(std::string destDirPath); ```
/content/code_sandbox/Source/UserData.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
21
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ButterworthFilterEffect.h // Bespoke // // Created by Ryan Challinor on 5/19/16. // // #pragma once #include "IAudioEffect.h" #include "DropdownList.h" #include "Slider.h" #include "FilterButterworth24db.h" class ButterworthFilterEffect : public IAudioEffect, public IDropdownListener, public IFloatSliderListener { public: ButterworthFilterEffect(); ~ButterworthFilterEffect(); static IAudioEffect* Create() { return new ButterworthFilterEffect(); } void CreateUIControls() override; void Init() override; void SetFilterParams(float f, float q) { mButterworth[0].Set(f, q); } //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } float GetEffectAmount() override; std::string GetType() override { return "butterworth"; } void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void LoadLayout(const ofxJSONElement& info) override; void SetUpFromSaveData() override; void SaveLayout(ofxJSONElement& info) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void DrawModule() override; void ResetFilter(); float mF{ 2000 }; FloatSlider* mFSlider{ nullptr }; float mQ{ 0 }; FloatSlider* mQSlider{ nullptr }; float mWidth{ 200 }; float mHeight{ 20 }; CFilterButterworth24db mButterworth[ChannelBuffer::kMaxNumChannels]{}; ChannelBuffer mDryBuffer; bool mCoefficientsHaveChanged{ true }; }; ```
/content/code_sandbox/Source/ButterworthFilterEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
558
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Granulator.cpp // modularSynth // // Created by Ryan Challinor on 9/12/13. // // #include "Granulator.h" #include "SynthGlobals.h" #include "Profiler.h" #include "ChannelBuffer.h" #include "juce_dsp/maths/juce_FastMathApproximations.h" Granulator::Granulator() { Reset(); } void Granulator::Reset() { mSpeed = 1; mGrainLengthMs = 60; mGrainOverlap = 10; mPosRandomizeMs = 5; mSpeedRandomize = 0; mSpacingRandomize = 1; mOctaves = false; mWidth = 1; for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) { mBiquad[i].SetFilterParams(10, sqrt(2) / 2); mBiquad[i].SetFilterType(kFilterType_Highpass); mBiquad[i].UpdateFilterCoeff(); mBiquad[i].Clear(); } } void Granulator::ProcessFrame(double time, ChannelBuffer* buffer, int bufferLength, double offset, float* output) { if (time + gInvSampleRateMs >= mNextGrainSpawnMs) { double startFromMs = mNextGrainSpawnMs; if (startFromMs < time - 1000) //must have recently started processing, reset startFromMs = time; SpawnGrain(mNextGrainSpawnMs, offset, buffer->NumActiveChannels() == 2 ? mWidth : 0); mNextGrainSpawnMs = startFromMs + mGrainLengthMs * 1 / mGrainOverlap * ofRandom(1 - mSpacingRandomize / 2, 1 + mSpacingRandomize / 2); } for (int i = 0; i < MAX_GRAINS; ++i) mGrains[i].Process(time, buffer, bufferLength, output); for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) { if (mGrainOverlap > 4) output[ch] *= ofMap(mGrainOverlap, MAX_GRAINS, 4, .5f, 1); //lower volume on dense granulation, starting at 4 overlap output[ch] = mBiquad[ch].Filter(output[ch]); } } void Granulator::SpawnGrain(double time, double offset, float width) { if (mLiveMode) { float speedMult = 1 + mSpeedRandomize; if (mOctaves) speedMult *= 1.5f; float extraSpeed = MAX(0, speedMult * mSpeed - 1); float extraMs = mGrainLengthMs * extraSpeed + mPosRandomizeMs; float extraSamples = extraMs / gInvSampleRateMs; offset -= extraSamples; } float speedMult = 1 + ofRandom(-mSpeedRandomize, mSpeedRandomize); float vol = 1; if (mOctaves) { int random = gRandom() % 5; if (random == 2) //fewer high-pitched ones { speedMult *= 1.5f; vol = .5f; } else if (random == 3 || random == 4) { speedMult *= .75f; } } offset += ofRandom(-mPosRandomizeMs, mPosRandomizeMs) / gInvSampleRateMs; mGrains[mNextGrainIdx].Spawn(this, time, offset, speedMult, mGrainLengthMs, vol, width); mNextGrainIdx = (mNextGrainIdx + 1) % MAX_GRAINS; } void Granulator::Draw(float x, float y, float w, float h, int bufferStart, int viewLength, int bufferLength) { for (int i = 0; i < MAX_GRAINS; ++i) mGrains[i].DrawGrain(i, x, y, w, h, bufferStart, viewLength, bufferLength); } void Granulator::ClearGrains() { for (int i = 0; i < MAX_GRAINS; ++i) mGrains[i].Clear(); } void Grain::Spawn(Granulator* owner, double time, double pos, float speedMult, float lengthInMs, float vol, float width) { mOwner = owner; mPos = pos; mSpeedMult = speedMult; mStartTime = time; mEndTime = time + lengthInMs; mStartToEnd = mEndTime - mStartTime; mStartToEndInv = 1.0 / mStartToEnd; mVol = vol; mStereoPosition = ofRandom(-width, width); mDrawPos = ofRandom(1); } inline double Grain::GetWindow(double time) { double phase = (time - mStartTime) * mStartToEndInv; return .5 + .5 * juce::dsp::FastMathApproximations::cos<double>(phase * TWO_PI - PI); } void Grain::Process(double time, ChannelBuffer* buffer, int bufferLength, float* output) { if (time >= mStartTime && time <= mEndTime && mVol != 0) { mPos += mSpeedMult * mOwner->mSpeed; float window = GetWindow(time); for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) { float sample = GetInterpolatedSample(mPos, buffer, bufferLength, std::clamp(ch + mStereoPosition, 0.f, 1.f)); output[ch] += sample * window * mVol * (1 + (ch == 0 ? mStereoPosition : -mStereoPosition)); } } } void Grain::DrawGrain(int idx, float x, float y, float w, float h, int bufferStart, int viewLength, int bufferLength) { float a = fmod((mPos - bufferStart), bufferLength) / viewLength; if (a < 0 || a > 1) return; ofPushStyle(); ofFill(); float alpha = GetWindow(std::clamp(gTime, mStartTime, mEndTime)); ofSetColor(255, 0, 0, alpha * 255); ofCircle(x + a * w, y + mDrawPos * h, MAX(3, h / MAX_GRAINS / 2)); ofPopStyle(); } ```
/content/code_sandbox/Source/Granulator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,539
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ModulatorSmoother.h Created: 29 Nov 2017 9:35:31pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "Slider.h" #include "IModulator.h" #include "Transport.h" #include "Ramp.h" class PatchCableSource; class ModulatorSmoother : public IDrawableModule, public IFloatSliderListener, public IModulator, public IAudioPoller { public: ModulatorSmoother(); virtual ~ModulatorSmoother(); static IDrawableModule* Create() { return new ModulatorSmoother(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; //IModulator float Value(int samplesIn = 0) override; bool Active() const override { return mEnabled; } bool CanAdjustRange() const override { return false; } //IAudioPoller void OnTransportAdvanced(float amount) override; FloatSlider* GetTarget() { return GetSliderTarget(); } //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 106; h = 17 * 2 + 4; } float mInput{ 0 }; float mSmooth{ .1 }; Ramp mRamp; FloatSlider* mInputSlider{ nullptr }; FloatSlider* mSmoothSlider{ nullptr }; }; ```
/content/code_sandbox/Source/ModulatorSmoother.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
579
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // MidiClockOut.h // Bespoke // // Created by Ryan Challinor on 1/1/22. // // #pragma once #include <iostream> #include "MidiDevice.h" #include "IDrawableModule.h" #include "DropdownList.h" #include "Transport.h" #include "Slider.h" #include "ClickButton.h" class IAudioSource; class MidiClockOut : public IDrawableModule, public IDropdownListener, public IAudioPoller, public IFloatSliderListener, public IButtonListener { public: MidiClockOut(); virtual ~MidiClockOut(); static IDrawableModule* Create() { return new MidiClockOut(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IAudioPoller void OnTransportAdvanced(float amount) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void DropdownClicked(DropdownList* list) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void ButtonClicked(ClickButton* button, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: void InitDevice(); void BuildDeviceList(); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = mWidth; h = mHeight; } float mWidth{ 200 }; float mHeight{ 20 }; enum class ClockMultiplier { Quarter, Half, One, Two, Four }; int mDeviceIndex{ -1 }; DropdownList* mDeviceList{ nullptr }; bool mClockStartQueued{ false }; ClickButton* mStartButton{ nullptr }; ClockMultiplier mMultiplier{ ClockMultiplier::One }; DropdownList* mMultiplierSelector{ nullptr }; MidiDevice mDevice{ nullptr }; }; ```
/content/code_sandbox/Source/MidiClockOut.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
596
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== GridSliders.h Created: 2 Aug 2021 10:32:04pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "Checkbox.h" #include "DropdownList.h" #include "GridController.h" class PatchCableSource; class GridSliders : public IDrawableModule, public IDropdownListener, public IGridControllerListener { public: GridSliders(); ~GridSliders(); static IDrawableModule* Create() { return new GridSliders(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IDrawableModule void Init() override; void Poll() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IGridControllerListener void OnControllerPageSelected() override; void OnGridButton(int x, int y, float velocity, IGridController* grid) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 0; } //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override; void OnClicked(float x, float y, bool right) override; bool MouseMoved(float x, float y) override; void MouseReleased() override; enum class Direction { kHorizontal, kVertical }; Direction mDirection{ Direction::kVertical }; DropdownList* mDirectionSelector{ nullptr }; std::array<PatchCableSource*, 32> mControlCables{}; GridControlTarget* mGridControlTarget{ nullptr }; TransportListenerInfo* mTransportListenerInfo{ nullptr }; }; ```
/content/code_sandbox/Source/GridSliders.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
628
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // IPatchable.h // Bespoke // // Created by Ryan Challinor on 12/13/15. // // #pragma once class PatchCableSource; class IPatchable { public: virtual ~IPatchable() {} virtual PatchCableSource* GetPatchCableSource(int index = 0) = 0; virtual void PreRepatch(PatchCableSource* cableSource) {} virtual void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) {} virtual void OnCableGrabbed(PatchCableSource* cableSource) {} }; ```
/content/code_sandbox/Source/IPatchable.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
229
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ControlTactileFeedback.cpp // modularSynth // // Created by Ryan Challinor on 1/9/14. // // #include "ControlTactileFeedback.h" #include "IAudioReceiver.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" ControlTactileFeedback::ControlTactileFeedback() { mPhaseInc = GetPhaseInc(50); } void ControlTactileFeedback::CreateUIControls() { IDrawableModule::CreateUIControls(); mVolumeSlider = new FloatSlider(this, "vol", 5, 43, 70, 15, &mVolume, 0, 1); } ControlTactileFeedback::~ControlTactileFeedback() { } void ControlTactileFeedback::Process(double time) { PROFILER(ControlTactileFeedback); IAudioReceiver* target = GetTarget(); if (!mEnabled || target == nullptr) return; int bufferSize = target->GetBuffer()->BufferSize(); float* out = target->GetBuffer()->GetChannel(0); assert(bufferSize == gBufferSize); for (int i = 0; i < bufferSize; ++i) { float sample = (mPhase / FTWO_PI * 2 - 1) * gControlTactileFeedback * mVolume; out[i] += sample; GetVizBuffer()->Write(sample, 0); mPhase += mPhaseInc; while (mPhase > FTWO_PI) { mPhase -= FTWO_PI; } const float decayTime = .005f; float decay = powf(0.5f, 1.0f / (decayTime * gSampleRate)); gControlTactileFeedback *= decay; if (gControlTactileFeedback <= FLT_EPSILON) gControlTactileFeedback = 0; time += gInvSampleRateMs; } } void ControlTactileFeedback::DrawModule() { if (Minimized() || IsVisible() == false) return; mVolumeSlider->Draw(); } void ControlTactileFeedback::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void ControlTactileFeedback::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/ControlTactileFeedback.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
624
```c++ // // M185Sequencer.cpp // Bespoke // // Created by Lionel Landwerlin on 7/22/21. // // #include "M185Sequencer.h" #include "SynthGlobals.h" #include "UIControlMacros.h" #include "FileStream.h" M185Sequencer::M185Sequencer() { } void M185Sequencer::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true); } void M185Sequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK2(10, 0); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 40); UIBLOCK_SHIFTRIGHT(); BUTTON(mResetStepButton, "reset step"); int i = 0; for (auto& step : mSteps) { UIBLOCK_NEWLINE(); step.xPos = 0; step.yPos = yPos; INTSLIDER(step.mPitchSlider, ("pitch" + ofToString(i)).c_str(), &step.mPitch, 0, 127); UIBLOCK_SHIFTRIGHT(); INTSLIDER(step.mPulseCountSlider, ("pulses" + ofToString(i)).c_str(), &step.mPulseCount, 0, 8); UIBLOCK_SHIFTRIGHT(); DROPDOWN(step.mGateSelector, ("gate" + ofToString(i)).c_str(), (int*)(&step.mGate), 60); step.mGateSelector->AddLabel("repeat", GateType::kGate_Repeat); step.mGateSelector->AddLabel("once", GateType::kGate_Once); step.mGateSelector->AddLabel("hold", GateType::kGate_Hold); step.mGateSelector->AddLabel("rest", GateType::kGate_Rest); ++i; } mWidth = UIBLOCKWIDTH(); mHeight = UIBLOCKHEIGHT(); ENDUIBLOCK0(); mIntervalSelector->AddLabel("4", kInterval_4); mIntervalSelector->AddLabel("3", kInterval_3); mIntervalSelector->AddLabel("2", kInterval_2); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("32n", kInterval_32n); mIntervalSelector->AddLabel("64n", kInterval_64n); mIntervalSelector->AddLabel("none", kInterval_None); } M185Sequencer::~M185Sequencer() { TheTransport->RemoveListener(this); } void M185Sequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; int totalSteps = 0; for (auto& step : mSteps) totalSteps += step.mPulseCount; DrawTextNormal("total steps: " + ofToString(totalSteps), 120, 13); ofPushStyle(); for (int i = 0; i < mSteps.size(); i++) { ofFill(); ofSetColor(0, i == mLastPlayedStepIdx ? 255 : 0, 0, gModuleDrawAlpha * .4f); ofRect(mSteps[i].xPos, mSteps[i].yPos, 10, 10); } ofPopStyle(); mResetStepButton->Draw(); mIntervalSelector->Draw(); for (auto& step : mSteps) { step.mPitchSlider->Draw(); step.mPulseCountSlider->Draw(); step.mGateSelector->Draw(); } } void M185Sequencer::OnTimeEvent(double time) { if (mHasExternalPulseSource) return; StepBy(time, 1, 0); } void M185Sequencer::OnPulse(double time, float velocity, int flags) { mHasExternalPulseSource = true; StepBy(time, velocity, flags); } void M185Sequencer::StepBy(double time, float velocity, int flags) { if (flags & kPulseFlag_Reset) ResetStep(); if (flags & kPulseFlag_SyncToTransport) { int totalSteps = 0; for (auto& step : mSteps) totalSteps += step.mPulseCount; int desiredStep = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, totalSteps); int stepsRemaining = desiredStep; mStepIdx = 0; for (auto& step : mSteps) { if (stepsRemaining < step.mPulseCount) { mStepPulseIdx = stepsRemaining; break; } stepsRemaining -= step.mPulseCount; ++mStepIdx; } if (mStepIdx >= mSteps.size()) { mStepIdx = 0; mStepPulseIdx = 0; } } if (mEnabled) { bool stopPrevNote = mStepPulseIdx == 0 || mSteps[mStepIdx].mGate == GateType::kGate_Repeat || (mStepPulseIdx > 0 && mSteps[mStepIdx].mGate == GateType::kGate_Once); bool playNextNote = (mStepPulseIdx == 0 && (mSteps[mStepIdx].mGate == GateType::kGate_Once || mSteps[mStepIdx].mGate == GateType::kGate_Hold)) || mSteps[mStepIdx].mGate == GateType::kGate_Repeat; if (mSteps[mStepIdx].mPulseCount == 0) playNextNote = false; if (stopPrevNote && mLastPitch >= 0) { PlayNoteOutput(time, mLastPitch, 0, -1); mLastPitch = -1; } if (playNextNote) { PlayNoteOutput(time, mSteps[mStepIdx].mPitch, velocity * 127, -1); mLastPitch = mSteps[mStepIdx].mPitch; } } else if (mLastPitch >= 0) { PlayNoteOutput(time, mLastPitch, 0, -1); mLastPitch = -1; } mLastPlayedStepIdx = mStepIdx; // Update step/pulse FindNextStep(); } void M185Sequencer::FindNextStep() { mStepPulseIdx++; int loopProtection = (int)mSteps.size() - 1; while (mStepPulseIdx >= mSteps[mStepIdx].mPulseCount) { mStepPulseIdx = 0; mStepIdx = (mStepIdx + 1) % mSteps.size(); --loopProtection; if (loopProtection < 0) break; } } void M185Sequencer::ResetStep() { mStepIdx = 0; mStepPulseIdx = 0; if (mSteps[mStepIdx].mPulseCount == 0) //if we don't have any pulses on the first step, find a step that does FindNextStep(); } void M185Sequencer::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void M185Sequencer::ButtonClicked(ClickButton* button, double time) { if (mResetStepButton == button) ResetStep(); } void M185Sequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mInterval; } } void M185Sequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void M185Sequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void M185Sequencer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } void M185Sequencer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); for (auto& step : mSteps) { out << step.mPitch; out << step.mPulseCount; out << (int)step.mGate; } out << (int)mInterval; out << mHasExternalPulseSource; } void M185Sequencer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); for (auto& step : mSteps) { in >> step.mPitch; in >> step.mPulseCount; int gate; in >> gate; step.mGate = (GateType)gate; } int interval; in >> interval; mInterval = (NoteInterval)interval; in >> mHasExternalPulseSource; } ```
/content/code_sandbox/Source/M185Sequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,149
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ListenPort.cpp // NI_SoftwareSide // // Created by Ryan Challinor on 11/5/14. // #include "ListenPort.h" #include <iostream> ListenPort::~ListenPort() { Close(); } void* SetupRunLoop(void* source) { //add the source to the run loop CFRunLoopAddSource(CFRunLoopGetCurrent(), *((CFRunLoopSourceRef*)source), kCFRunLoopDefaultMode); // start the run loop CFRunLoopRun(); // exit thread when the runloop is done CFShow(CFSTR("thread exiting")); pthread_exit(0); } void ListenPort::CreateListener(const char* portName, ListenPortCallback* callback) { std::cout << "Listening on port " << portName << std::endl; mPortName = portName; mCallback = callback; Boolean shouldFree; mReceivePort = CFMessagePortCreateLocal(kCFAllocatorDefault, CFStringCreateWithCString(kCFAllocatorDefault, portName, kCFStringEncodingASCII), ListenPortReceiver::OnMessageReceived, NULL, &shouldFree); ListenPortReceiver::RegisterPort(this, mReceivePort); // create the runloop source from the local message port passed in mLoopSource = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, mReceivePort, (CFIndex)0); pthread_t a; pthread_create(&a, 0, SetupRunLoop, (void*)&mLoopSource); pthread_detach(a); } CFDataRef ListenPort::OnMessageReceived(SInt32 msgid, CFDataRef data) { return mCallback->OnMessageReceived(mPortName, msgid, data); } void ListenPort::Close() { if (mReceivePort) { CFMessagePortInvalidate(mReceivePort); while (CFMessagePortIsValid(mReceivePort)) { // sleep 0.1ms usleep(100); } CFRelease(mReceivePort); } mReceivePort = NULL; } //static std::map<CFMessagePortRef, ListenPort*> ListenPortReceiver::mPortMap; //static void ListenPortReceiver::RegisterPort(ListenPort* port, CFMessagePortRef portRef) { mPortMap[portRef] = port; } //static ListenPort* ListenPortReceiver::LookupPort(CFMessagePortRef portRef) { return mPortMap[portRef]; } //static CFDataRef ListenPortReceiver::OnMessageReceived(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void* info) { ListenPort* port = LookupPort(local); return port->OnMessageReceived(msgid, data); } ```
/content/code_sandbox/Source/CFMessaging/ListenPort.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
672
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NIMessage.h // NI_FakeDaemon // // Created by Ryan Challinor on 11/23/14. // // #ifndef CFMessaging_NIMessage_h #define CFMessaging_NIMessage_h #include <iostream> typedef struct { uint32_t messageId; std::string className; } MessageIdToString; #define NUM_NI_MESSAGE_IDS 27 extern MessageIdToString MessageIdToStringTable[NUM_NI_MESSAGE_IDS]; std::string TypeForMessageID(uint32_t messageId); uint32_t MessageIDForType(std::string type); #endif ```
/content/code_sandbox/Source/CFMessaging/NIMessage.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
218
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // SendPort.cpp // NI_SoftwareSide // // Created by Ryan Challinor on 11/6/14. // // #include "SendPort.h" SendPort::~SendPort() { if (mSendPort) CFRelease(mSendPort); } void SendPort::CreateSender(const char* portName) { mSendPort = CFMessagePortCreateRemote(kCFAllocatorDefault, CFStringCreateWithCString(kCFAllocatorDefault, portName, kCFStringEncodingASCII)); assert(mSendPort != NULL); } void SendPort::SendData(uint32_t messageId, CFDataRef data, CFDataRef& replyData) { CFMessagePortSendRequest(mSendPort, messageId, data, 1, 1, kCFRunLoopDefaultMode, &replyData); } void SendPort::Close() { } ```
/content/code_sandbox/Source/CFMessaging/SendPort.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
279
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NIMessage.cpp // NI_FakeDaemon // // Created by Ryan Challinor on 11/24/14. // // #include "NIMessage.h" MessageIdToString MessageIdToStringTable[NUM_NI_MESSAGE_IDS] = { { 0x03536756, "NIGetServiceVersionMessage" }, { 0x03444300, "NIDeviceConnectMessage" }, { 0x03404300, "NISetAsciiStringMessage" }, { 0x03446724, "NIGetDeviceEnabledMessage" }, { 0x03444e00, "NIDeviceStateChangeMessage" }, { 0x03446743, "NIGetDeviceAvailableMessage" }, { 0x03434e00, "NISetFocusMessage" }, { 0x03446744, "NIGetDriverVersionMessage" }, { 0x03436746, "NIGetFirmwareVersionMessage" }, { 0x03436753, "NIGetSerialNumberMessage" }, { 0x03646749, "NIGetDisplayInvertedMessage" }, { 0x03646743, "NIGetDisplayContrastMessage" }, { 0x03646742, "NIGetDisplayBacklightMessage" }, { 0x03566766, "NIGetFloatPropertyMessage" }, { 0x03647344, "NIDisplayDrawMessage" }, { 0x03654e00, "NIWheelsChangedMessage" }, { 0x03504e00, "NIPadsChangedMessage" }, { 0x036c7500, "NISetLedStateMessage" }, { 0x02447500, "NIHWSDeviceConnectMessage" }, { 0x03447143, "NIRequestSerialNumberMessage" }, { 0x02444e2b, "NISetSerialNumberMessage" }, { 0x03442d00, "NISoftwareShuttingDownMessage" }, { 0x02444900, "NIHWSDeviceConnectSerialMessage" }, { 0x03434300, "NIMysteryMessage" }, { 0x03734e00, "NIButtonPressedMessage" }, { 0x03774e00, "NIBrowseWheelMessage" }, { 0x03564e66, "NIOctaveChangedMessage" }, }; std::string TypeForMessageID(uint32_t messageId) { for (int i = 0; i < NUM_NI_MESSAGE_IDS; ++i) { if (MessageIdToStringTable[i].messageId == messageId) return MessageIdToStringTable[i].className; } char messageIdStr[16]; snprintf(messageIdStr, sizeof(messageIdStr), "0x%08x", messageId); return std::string("Unknown message type ") + messageIdStr; } uint32_t MessageIDForType(std::string type) { for (int i = 0; i < NUM_NI_MESSAGE_IDS; ++i) { if (MessageIdToStringTable[i].className == type) return MessageIdToStringTable[i].messageId; } return 0; } ```
/content/code_sandbox/Source/CFMessaging/NIMessage.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
813
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // KontrolKommunicator.h // // Created by Ryan Challinor on 11/22/14. // // #ifndef __NI_FakeDaemon__KontrolKommunicator__ #define __NI_FakeDaemon__KontrolKommunicator__ #include <string> #include <map> #include "ListenPort.h" #include "SendPort.h" #include <CoreFoundation/CoreFoundation.h> #include "../OpenFrameworksPort.h" class KDataArray { public: KDataArray() {} KDataArray(uint8_t val) { mData.assign(&val, &val + 1); } KDataArray(uint16_t val) { mData.assign(((uint8_t*)&val), ((uint8_t*)&val) + 2); } KDataArray(uint32_t messageId) { mData.assign(((uint8_t*)&messageId), ((uint8_t*)&messageId) + 4); } KDataArray(std::string input) { mData.assign(input.c_str(), input.c_str() + input.length() + 1); } uint8_t* data() { return mData.data(); } void resize(size_t size) { mData.resize(size); } size_t size() const { return mData.size(); } bool empty() const { return mData.empty(); } const uint8_t& operator[](size_t i) const { return mData[i]; } uint8_t& operator[](size_t i) { return mData[i]; } KDataArray operator+(const KDataArray& b) { mData.insert(mData.end(), b.mData.begin(), b.mData.end()); return *this; } void operator+=(const KDataArray& b) { mData.insert(mData.end(), b.mData.begin(), b.mData.end()); } private: std::vector<uint8_t> mData; }; struct ReplyEntry { std::string mPort; KDataArray mInput; KDataArray mReply; }; struct QueuedMessage { std::string mPort; KDataArray mMessage; }; class IKontrolListener { public: virtual ~IKontrolListener() {} virtual void OnKontrolButton(int control, bool on) = 0; virtual void OnKontrolEncoder(int control, float change) = 0; virtual void OnKontrolOctave(int octave) = 0; }; class KontrolKommunicator : public ListenPortCallback { public: KontrolKommunicator(); virtual ~KontrolKommunicator() {} void Init(); void Exit(); void CreateListener(const char* portName); CFDataRef OnMessageReceived(std::string portName, SInt32 msgid, CFDataRef data) override; void AddReply(std::string portName, std::string input, std::string reply); void QueueMessage(std::string portName, KDataArray message); void Update(); static KDataArray StringToData(std::string input); static KDataArray LettersToData(std::string letters); static uint16_t CharToSegments(char input); KDataArray CreateMessage(std::string type); bool IsReady() const { return mState == kState_Focused; } void SetListener(IKontrolListener* listener) { mListener = listener; } void SetDisplay(const uint16_t sliders[72], std::string display); void SetKeyLights(ofColor keys[61]); private: void SendMessage(std::string portName, KDataArray data); void CreateSender(const char* portName); CFDataRef ProcessIncomingMessage(std::string portName, char* data, size_t length); static void Output(std::string str); std::string FormatString(std::string format, int number); KDataArray RespondToMessage(std::string portName, KDataArray input); void FollowUpToReply(std::string messageType, uint8_t* reply); bool DataEquals(const KDataArray& a, const KDataArray& b); void OutputData(const KDataArray& a); void OutputRawData(const uint8_t* data, size_t length); void OutputRawData2(const uint8_t* data, size_t length); //circumvents Output() being disabled enum State { kState_Initialization, kState_InitializeSerial, kState_Initialized, kState_Focused } mState; std::string mSerialNumber; std::string mRequestPort; std::string mNotificationPort; std::string mRequestSerialPort; std::string mNotificationSerialPort; std::vector<ReplyEntry> mReplies; std::list<QueuedMessage> mMessageQueue; std::map<std::string, ListenPort> mListenPorts; std::map<std::string, SendPort> mSendPorts; ofMutex mMessageQueueMutex; IKontrolListener* mListener; }; #endif /* defined(__NI_FakeDaemon__KontrolKommunicator__) */ ```
/content/code_sandbox/Source/CFMessaging/KontrolKommunicator.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,165
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // SendPort.h // NI_SoftwareSide // // Created by Ryan Challinor on 11/6/14. // // #ifndef __NI_SoftwareSide__SendPort__ #define __NI_SoftwareSide__SendPort__ #include <CoreFoundation/CoreFoundation.h> #include <string> class SendPort { public: SendPort() : mSendPort(NULL) {} ~SendPort(); void CreateSender(const char* portName); void SendData(uint32_t messageId, CFDataRef data, CFDataRef& replyData); void Close(); private: std::string mPortName; CFMessagePortRef mSendPort; }; #endif /* defined(__NI_SoftwareSide__SendPort__) */ ```
/content/code_sandbox/Source/CFMessaging/SendPort.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
252
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ListenPort.h // NI_SoftwareSide // // Created by Ryan Challinor on 11/5/14. // #ifndef __NI_SoftwareSide__ListenPort__ #define __NI_SoftwareSide__ListenPort__ #include <CoreFoundation/CoreFoundation.h> #include <string> #include <map> class ListenPortCallback { public: virtual ~ListenPortCallback() {} virtual CFDataRef OnMessageReceived(std::string portName, SInt32 msgid, CFDataRef data) = 0; }; class ListenPort { public: ListenPort() : mReceivePort(NULL) {} ~ListenPort(); void CreateListener(const char* portName, ListenPortCallback* callback); CFDataRef OnMessageReceived(SInt32 msgid, CFDataRef data); void Close(); private: std::string mPortName; CFMessagePortRef mReceivePort; CFRunLoopSourceRef mLoopSource; ListenPortCallback* mCallback; }; class ListenPortReceiver { public: static CFDataRef OnMessageReceived(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void* info); static void RegisterPort(ListenPort* port, CFMessagePortRef portRef); private: static ListenPort* LookupPort(CFMessagePortRef portRef); static std::map<CFMessagePortRef, ListenPort*> mPortMap; }; #endif /* defined(__NI_SoftwareSide__ListenPort__) */ ```
/content/code_sandbox/Source/CFMessaging/ListenPort.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
410
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // KontrolKommunicator.cpp // // Created by Ryan Challinor on 11/22/14. // // #include "KontrolKommunicator.h" #include <mach/mach.h> #include "NIMessage.h" #define KEYS_MESSAGE "75 67 56 02 73 79 65 4b" #define RKEY_MESSAGE "75 67 56 02 79 65 4b 52" KontrolKommunicator::KontrolKommunicator() : mState(kState_Initialization) , mListener(NULL) { } void KontrolKommunicator::Init() { } void KontrolKommunicator::Exit() { mSendPorts.clear(); mListenPorts.clear(); } void KontrolKommunicator::CreateSender(const char* portName) { mSendPorts[portName].CreateSender(portName); } void KontrolKommunicator::CreateListener(const char* portName) { mListenPorts[portName].CreateListener(portName, this); } void KontrolKommunicator::OutputRawData2(const uint8_t* data, size_t length) { for (int i = 0; i < length; ++i) { std::cout << ofToString(data[i]); if (i % 4 == 3) std::cout << " "; } std::cout << "\n"; for (int i = 0; i < length; ++i) { std::cout << FormatString("%02x ", data[i]); if (i % 4 == 3) std::cout << " "; } std::cout << "\n"; } CFDataRef KontrolKommunicator::OnMessageReceived(std::string portname, SInt32 msgid, CFDataRef data) { vm_address_t vmData; vm_allocate(mach_task_self(), &vmData, (vm_size_t)vm_page_size, TRUE); char* dataBuffer = (char*)vmData; size_t length = CFDataGetLength(data); CFDataGetBytes(data, CFRangeMake(0, length), (uint8_t*)dataBuffer); if (mListener) { switch (msgid) { case 0x03734e00: //NIButtonPressedMessage { mListener->OnKontrolButton((int)(((uint8_t*)dataBuffer)[16]), (bool)(((uint8_t*)dataBuffer)[20])); } break; case 0x03654e00: //NIWheelsChangedMessage { mListener->OnKontrolEncoder((int)(((uint8_t*)dataBuffer)[16]), (float)((((int32_t*)dataBuffer)[5]) / 1000000000.0f)); } break; case 0x03774e00: //NIBrowseWheelMessage { mListener->OnKontrolEncoder(8, (float)(((int8_t*)dataBuffer)[20])); } break; case 0x03564e66: //NIOctaveChangedMessage { mListener->OnKontrolOctave((int)(((uint8_t*)dataBuffer)[8])); } break; } } mMessageQueueMutex.lock(); Output(portname + " received CF message with length " + ofToString(length) + ":\n"); uint32_t messageID = *((uint32_t*)dataBuffer); Output(FormatString("0x%08x", messageID) + " (" + TypeForMessageID(messageID) + ")\n"); OutputRawData((uint8_t*)dataBuffer, length); CFDataRef reply = ProcessIncomingMessage(portname, dataBuffer, length); mMessageQueueMutex.unlock(); vm_deallocate(mach_task_self(), vmData, (vm_size_t)vm_page_size); return reply; } CFDataRef KontrolKommunicator::ProcessIncomingMessage(std::string portName, char* data, size_t length) { KDataArray input; input.resize(length); for (int i = 0; i < length; ++i) input[i] = data[i]; KDataArray reply = RespondToMessage(portName, input); if (!reply.empty()) { vm_address_t vmaddress; vm_allocate(mach_task_self(), &vmaddress, (vm_size_t)vm_page_size, TRUE); memcpy((void*)vmaddress, reply.data(), reply.size()); Output("Replying to " + portName + " with length " + ofToString(reply.size()) + ":\n"); OutputData(reply); return CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (uint8_t*)vmaddress, reply.size(), kCFAllocatorNull); } else { Output("Replying to " + portName + " with:\n[empty]\n"); } return NULL; } //static uint16_t KontrolKommunicator::CharToSegments(char input) { switch (input) { case ' ': return 0x0000; case 'A': return 0xcf18; case 'B': return 0x3f52; case 'C': return 0xf300; case 'D': return 0x3f42; case 'E': return 0xf318; case 'F': return 0xc318; case 'G': return 0xfb10; case 'H': return 0xcc18; case 'I': return 0x3342; case 'J': return 0x7c00; case 'K': return 0xc08c; case 'L': return 0xf000; case 'M': return 0xcc05; case 'N': return 0xcc81; case 'O': return 0xff00; case 'P': return 0xc718; case 'Q': return 0xff80; case 'R': return 0xc798; case 'S': return 0x3381; case 'T': return 0x0342; case 'U': return 0xfc00; case 'V': return 0xc024; case 'W': return 0xcca0; case 'X': return 0x00a5; case 'Y': return 0x0045; case 'Z': return 0x3324; case '0': return 0xff24; case '1': return 0x3142; case '2': return 0x7718; case '3': return 0x3f18; case '4': return 0x8c18; case '5': return 0xbb18; case '6': return 0xfb18; case '7': return 0x0324; case '8': return 0xff18; case '9': return 0xbf18; case '|': return 0x0042; case '/': return 0x0024; case '-': return 0x0018; case '\\': return 0x0081; case '\'': return 0x0002; case '?': return 0x0750; case '*': return 0x00ff; case '+': return 0x005a; case '#': return 0xc05a; case '.': return 0; } return 0xffff; } //static KDataArray KontrolKommunicator::LettersToData(std::string input) { KDataArray data; data.resize(input.length() * 2); for (int i = 0; i < input.length(); ++i) { uint16_t segments = CharToSegments(input[i]); data[i * 2] = *(((uint8_t*)&segments) + 1); data[i * 2 + 1] = segments; } return data; } void KontrolKommunicator::Update() { /*static float timer = 0; const char rotate[8] = { '|', '/', '-', '\\', '|', '/', '-', '\\'}; static uint8_t cycle = 0; static uint8_t color = 0; if (mState == kState_Focused) { timer += ofGetLastFrameTime(); const float timeStep = 1.0f/12.0f; while (timer > timeStep) { timer -= timeStep; cycle = (cycle+1) % 8; ++color; KDataArray text(MessageIDForType("NIDisplayDrawMessage")); text += StringToData("00 00 00 00 00 00 00 00 03 00 48 00 b0 01 00 00"); //some sort of header int idLength = 4; int headerLength = 16; int rowLength = 144; uint16_t segments = CharToSegments(rotate[cycle]); string row = " "; for (int i=0; i<18; ++i) row += rotate[cycle]; row += " WHO'S IN KONTROL NOW? "; for (int i=0; i<18; ++i) row += rotate[cycle]; KDataArray centerRow = LettersToData(row); row = " "; for (int i=0; i<8*8; ++i) row += rotate[cycle]; KDataArray bottomRow = LettersToData(row); text += (uint8_t)0; for (int i=0; i<rowLength-1; ++i) text += (uint8_t)4; text += centerRow; text += bottomRow; QueueMessage(mRequestSerialPort, text); KDataArray lights(MessageIDForType("NISetLedStateMessage")); lights += StringToData("d0 00 00 00 13 00 00 00 00 00 00 00 00 00 00 13 00 13 00 00 00 00 00 00 00 13 00 13 00"); //some sort of header for (int i=0; i<61*3; ++i) lights += (uint8_t)(powf(ofRandom(1),5)*255); QueueMessage(mRequestSerialPort, lights); } }*/ mMessageQueueMutex.lock(); if (!mMessageQueue.empty()) { QueuedMessage message = *mMessageQueue.begin(); mMessageQueue.pop_front(); SendMessage(message.mPort, message.mMessage); } mMessageQueueMutex.unlock(); } void KontrolKommunicator::SendMessage(std::string portName, KDataArray data) { if (mSendPorts.find(portName) == mSendPorts.end()) CreateSender(portName.c_str()); vm_address_t vmaddress; vm_allocate(mach_task_self(), &vmaddress, (vm_size_t)vm_page_size, TRUE); memcpy((void*)vmaddress, data.data(), data.size()); uint32_t messageID = *((uint32_t*)data.data()); Output("Sending message (" + TypeForMessageID(messageID) + ") to " + portName + " with length " + ofToString(data.size()) + " and contents:\n"); OutputRawData((uint8_t*)vmaddress, data.size()); CFDataRef reply = NULL; mSendPorts[portName].SendData(*((uint32_t*)vmaddress), CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (uint8_t*)vmaddress, data.size(), kCFAllocatorNull), reply); if (reply) { vm_deallocate(mach_task_self(), vmaddress, (vm_size_t)vm_page_size); Output("Received reply on " + portName + " with length " + ofToString(CFDataGetLength(reply)) + " and contents:\n"); vm_address_t vmData; vm_allocate(mach_task_self(), &vmData, (vm_size_t)vm_page_size, TRUE); char* dataBuffer = (char*)vmData; int replyLength = (int)CFDataGetLength(reply); CFDataGetBytes(reply, CFRangeMake(0, replyLength), (uint8_t*)dataBuffer); OutputRawData((uint8_t*)vmData, replyLength); if (DataEquals(data, StringToData(RKEY_MESSAGE))) { if (mListener) mListener->OnKontrolOctave((uint8_t)dataBuffer[0]); } FollowUpToReply(TypeForMessageID(messageID), (uint8_t*)vmData); vm_deallocate(mach_task_self(), vmData, (vm_size_t)vm_page_size); CFRelease(reply); } } void KontrolKommunicator::AddReply(std::string portName, std::string input, std::string reply) { ReplyEntry entry; entry.mPort = portName; entry.mInput = StringToData(input); entry.mReply = StringToData(reply); mReplies.push_back(entry); } void KontrolKommunicator::QueueMessage(std::string portName, KDataArray message) { QueuedMessage entry; entry.mPort = portName; entry.mMessage = message; mMessageQueueMutex.lock(); mMessageQueue.push_back(entry); mMessageQueueMutex.unlock(); } KDataArray KontrolKommunicator::RespondToMessage(std::string portName, KDataArray input) { uint32_t messageID = *((uint32_t*)input.data()); std::string type = TypeForMessageID(messageID); //fake software responses if (portName == mNotificationPort) { if (type == "NISetSerialNumberMessage") { mState = kState_InitializeSerial; mSerialNumber = ""; for (int i = 16; i < input.size(); i += 2) mSerialNumber += (char)input[i]; Output("SERIAL NUMBER:" + mSerialNumber + "\n"); QueueMessage("NIHWMainHandler", CreateMessage("NIGetServiceVersionMessage")); return KDataArray(); } } if (portName == mNotificationSerialPort) { if (type == "NIDeviceStateChangeMessage") { mState = kState_Initialized; QueueMessage(mRequestSerialPort, CreateMessage("NIDisplayDrawMessage")); //mystery message QueueMessage(mRequestSerialPort, StringToData("00 43 43 02 72 65 73 75 ")); return KDataArray(); } if (type == "NISetFocusMessage") { mState = kState_Focused; QueueMessage(mRequestSerialPort, StringToData("54 73 49 02 00 00 00 00")); //unknown QueueMessage(mRequestSerialPort, StringToData("74 73 49 02 65 75 72 74 ")); //unknown QueueMessage(mRequestSerialPort, StringToData("56 73 6b 02 03 00 00 00 ")); //unknown QueueMessage(mRequestSerialPort, StringToData("43 73 74 02 00 00 00 00 00 00 00 00 28 00 00 00 06 00 00 00 00 00 ff 3f 00 00 01 00 03 00 00 02 00 00 00 00 03 01 00 00 00 00 7f 00 00 00 00 01 00 00 00 00 00 00 00 00 ")); //unknown QueueMessage(mRequestSerialPort, StringToData("43 73 70 02 00 00 00 00 00 00 00 00 18 00 00 00 03 40 00 06 00 00 7f 00 03 41 00 06 00 00 7f 00 03 0b 00 00 00 00 7f 00 ")); //unknown return KDataArray(); } } Output("&&& No appropriate reply found.\n"); return KDataArray(); } int WordAlign(int input) { return (input + 3) / 4 * 4; } void KontrolKommunicator::FollowUpToReply(std::string messageType, uint8_t* reply) { //fake software followups if (messageType == "NIGetServiceVersionMessage") { if (mState == kState_Initialization) QueueMessage("NIHWMainHandler", CreateMessage("NIHWSDeviceConnectMessage")); else if (mState == kState_InitializeSerial) QueueMessage("NIHWMainHandler", CreateMessage("NIHWSDeviceConnectSerialMessage")); } if (messageType == "NIHWSDeviceConnectMessage") { mRequestPort = (char*)(reply + 8); mNotificationPort = (char*)(reply + 8 + WordAlign((int)mRequestPort.length()) + /*4*/ 5); // TODO(Ryan) plus 5??? it used to be plus 4. Output("REQUEST PORT:" + mRequestPort + " NOTIFICATION PORT:" + mNotificationPort + "\n"); CreateListener(mNotificationPort.c_str()); QueueMessage(mRequestPort, CreateMessage("NISetAsciiStringMessage")); } if (messageType == "NISetAsciiStringMessage") { if (mState == kState_Initialization) QueueMessage(mRequestPort, CreateMessage("NIRequestSerialNumberMessage")); if (mState == kState_InitializeSerial) { QueueMessage(mRequestSerialPort, StringToData(KEYS_MESSAGE)); QueueMessage(mRequestSerialPort, StringToData(RKEY_MESSAGE)); } } if (messageType == "NIHWSDeviceConnectSerialMessage") { mRequestSerialPort = (char*)(reply + 8); mNotificationSerialPort = (char*)(reply + 8 + WordAlign((int)mRequestSerialPort.length()) + 4); Output("REQUEST SERIAL PORT:" + mRequestSerialPort + " NOTIFICATION SERIAL PORT:" + mNotificationSerialPort + "\n"); CreateListener(mNotificationSerialPort.c_str()); QueueMessage(mRequestSerialPort, CreateMessage("NISetAsciiStringMessage")); } } KDataArray KontrolKommunicator::CreateMessage(std::string type) { uint32_t messageID = MessageIDForType(type); KDataArray ret(messageID); //fake software messages if (type == "NIGetServiceVersionMessage") { } if (type == "NIHWSDeviceConnectMessage") { //connects a Komplete Kontrol ret += StringToData("50 13 00 00 4b 4b 69 4e 79 6d 72 70 11 00 00 00 4b 00 6f 00 6d 00 70 00 6c 00 65 00 74 00 65 00 20 00 4b 00 6f 00 6e 00 74 00 72 00 6f 00 6c 00 00 00"); } if (type == "NISetAsciiStringMessage") { if (mState == kState_Initialization) { //sends a message with notification port in it ret += StringToData("80 bc 97 53 ff 7f 00 00 25 00 00 00"); ret += KDataArray(mNotificationPort); } if (mState == kState_InitializeSerial) { //sends a message with notification serial port in it ret += StringToData("00 00 00 00 00 00 00 00 2d 00 00 00"); ret += KDataArray(mNotificationSerialPort); } } if (type == "NIHWSDeviceConnectSerialMessage") { ret += StringToData("50 13 00 00 4b 4b 69 4e 79 6d 72 70 09 00 00 00"); KDataArray zero = KDataArray((uint8_t)0); for (int i = 0; i < mSerialNumber.length(); ++i) ret += KDataArray((uint8_t)mSerialNumber[i]) + zero; ret += zero + zero; } if (type == "NIDeviceStateChangeMessage") { ret += StringToData("65 75 72 74"); } if (type == "NIDisplayDrawMessage") { ret += StringToData("00 00 00 00 00 00 00 00 03 00 48 00 b0 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 c7 18 c7 98 f3 18 33 81 33 81 3f 52 c7 98 ff 00 cc a0 33 81 f3 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"); } if (type == "NISetFocusMessage") { ret += StringToData("65 75 72 74"); } return ret; } void KontrolKommunicator::Output(std::string str) { return; std::cout << str; } std::string KontrolKommunicator::FormatString(std::string format, int number) { char buffer[100]; snprintf(buffer, sizeof(buffer), format.c_str(), number); return (std::string)buffer; } KDataArray KontrolKommunicator::StringToData(std::string input) { std::vector<std::string> tokens = ofSplitString(input, " ", true); size_t length = tokens.size(); KDataArray data; data.resize(length); for (int i = 0; i < length; ++i) data[i] = ofHexToInt(tokens[i]); return data; } bool KontrolKommunicator::DataEquals(const KDataArray& a, const KDataArray& b) { if (a.size() != b.size()) return false; for (int i = 0; i < a.size(); ++i) { if (a[i] != b[i]) return false; } return true; } void KontrolKommunicator::OutputData(const KDataArray& a) { for (int i = 0; i < a.size(); ++i) { Output(ofToString(a[i])); if (i % 4 == 3) Output(" "); } Output("\n"); for (int i = 0; i < a.size(); ++i) { Output(FormatString("%02x ", a[i])); if (i % 4 == 3) Output(" "); } Output("\n"); for (int i = 0; i < a.size(); ++i) { char c; if (a[i] > 32 && a[i] < 127) c = a[i]; else c = '#'; Output(FormatString("%c ", c)); if (i % 4 == 3) Output(" "); } Output("\n"); } void KontrolKommunicator::OutputRawData(const uint8_t* data, size_t length) { for (int i = 0; i < length; ++i) { Output(ofToString(data[i])); if (i % 4 == 3) Output(" "); } Output("\n"); for (int i = 0; i < length; ++i) { Output(FormatString("%02x ", data[i])); if (i % 4 == 3) Output(" "); } Output("\n"); for (int i = 0; i < length; ++i) { char c; if (data[i] > 32 && data[i] < 127) c = data[i]; else c = '#'; Output(FormatString("%c ", c)); if (i % 4 == 3) Output(" "); } Output("\n"); } void KontrolKommunicator::SetDisplay(const uint16_t sliders[72], std::string display) { KDataArray text(MessageIDForType("NIDisplayDrawMessage")); text += StringToData("00 00 00 00 00 00 00 00 03 00 48 00 b0 01 00 00"); //some sort of header int rowLength = 72; assert(display.length() == rowLength * 2); for (int i = 0; i < rowLength; ++i) text += (uint16_t)sliders[i]; KDataArray output = LettersToData(display); text += output; SendMessage(mRequestSerialPort, text); } void KontrolKommunicator::SetKeyLights(ofColor keys[61]) { KDataArray lights(MessageIDForType("NISetLedStateMessage")); lights += StringToData("d0 00 00 00 13 00 00 00 00 00 00 00 00 00 00 13 00 13 00 00 00 00 00 00 00 13 00 13 00"); //some sort of header for (int i = 0; i < 61; ++i) { lights += (uint8_t)keys[i].r; lights += (uint8_t)keys[i].g; lights += (uint8_t)keys[i].b; } SendMessage(mRequestSerialPort, lights); } ```
/content/code_sandbox/Source/CFMessaging/KontrolKommunicator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
6,816
```cmake # This abomination is the only way I know how to install quietly at build time. # Arguments: <source> <destination> [QUIET] if("${CMAKE_ARGV5}" STREQUAL "QUIET") execute_process(COMMAND ${CMAKE_COMMAND} -P "${CMAKE_SCRIPT_MODE_FILE}" "${CMAKE_ARGV3}" "${CMAKE_ARGV4}" OUTPUT_VARIABLE output RESULT_VARIABLE result ) if(result AND NOT result EQUAL 0) message(SEND_ERROR "Failed to install \"${CMAKE_ARGV3}\" to \"${CMAKE_ARGV4}\"") endif() else() file(INSTALL "${CMAKE_ARGV3}" DESTINATION "${CMAKE_ARGV4}" USE_SOURCE_PERMISSIONS) endif() ```
/content/code_sandbox/Source/cmake/install-quiet.cmake
cmake
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
163
```cmake # Install resource directory to the output directory or bundle function(bespoke_copy_resource_dir TARGET) add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND ${CMAKE_COMMAND} -P "${CMAKE_CURRENT_LIST_DIR}/cmake/install-quiet.cmake" "${CMAKE_SOURCE_DIR}/resource" "$<TARGET_FILE_DIR:${TARGET}>$<$<BOOL:${APPLE}>:/../Resources>" QUIET VERBATIM ) endfunction() # Install dependencies to the output directory and fix up binaries function(bespoke_make_portable TARGET) if(NOT BESPOKE_PORTABLE) return() endif() get_target_property(pyDirDst ${TARGET} RUNTIME_OUTPUT_DIRECTORY) set(pyMajDotMin "${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}") if(APPLE) string(REGEX REPLACE "\.framework/Versions/${pyMajDotMin}/.*" ".framework/Versions/${pyMajDotMin}" pyFWDirSrc "${Python_STDLIB}") string(REGEX REPLACE "/Versions/${pyMajDotMin}" "" pyFWName "${pyFWDirSrc}") string(REGEX REPLACE ".*/" "" pyFWName "${pyFWName}") set(bundleContents "${pyDirDst}/${TARGET}.app/Contents") set(pyDirDst "${bundleContents}/Frameworks/${pyFWName}/Versions/${pyMajDotMin}") else() set(pyDirDst "${pyDirDst}/python") endif() add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND ${CMAKE_COMMAND} -D APPLE=${APPLE} -D MINGW=${MINGW} -D WIN32=${WIN32} -D UNIX=${UNIX} -D CMAKE_CURRENT_BINARY_DIR="${CMAKE_CURRENT_BINARY_DIR}" -D CMAKE_INSTALL_NAME_TOOL="${CMAKE_INSTALL_NAME_TOOL}" -D targetBinary="$<TARGET_FILE:${TARGET}>" -D bundleContents="${bundleContents}" -D pyBulkInstallFrom="$<IF:$<BOOL:${APPLE}>,${pyFWDirSrc},${Python_STDLIB}>" -D pyBulkInstallTo="$<IF:$<BOOL:${APPLE}>,"${bundleContents}/Frameworks/${pyFWName}/Versions",${pyDirDst}$<$<NOT:$<BOOL:${WIN32}>>:/lib>>" -D pyDirDst="${pyDirDst}" -D pyFWDirSrc="${pyFWDirSrc}" -D pyFWName="${pyFWName}" -D pyMajDotMin="${pyMajDotMin}" -D Python_EXECUTABLE="${Python_EXECUTABLE}" -D Python_LIBRARIES="${Python_LIBRARIES}" -D Python_VERSION_MAJOR="${Python_VERSION_MAJOR}" -D Python_VERSION_MINOR="${Python_VERSION_MINOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/bundle-python.cmake" ) if(UNIX) set_target_properties(${TARGET} PROPERTIES BUILD_RPATH $<IF:$<BOOL:${APPLE}>,@loader_path/../Frameworks,$ORIGIN/python/bin> ) elseif(WIN32) if (${CMAKE_SIZEOF_VOID_P} EQUAL 4) set(cpuArch "x86") else() set(cpuArch "amd64") endif() get_filename_component(pyDLL "${Python_LIBRARIES}" NAME) string(REGEX REPLACE "\.[Ll][Ii][Bb]$" ".dll" pyDLL "${pyDLL}") # Reject alien implibs such as MinGW .dll.a for now. MinGW Python has a # UNIX-y layout and needs different treatment. if("${CMAKE_MATCH_0}" STREQUAL "") message(FATAL_ERROR "The Python library \"${pyDLL}\" does not look \ like an import library (.lib extension). Portable builds require \ the official Python for Windows from python.org.") endif() configure_file(cmake/python.manifest.in python.manifest @ONLY) set(manifestPath ${CMAKE_CURRENT_BINARY_DIR}/${TARGET}.manifest) configure_file(cmake/${TARGET}.manifest.in ${manifestPath} @ONLY) if(MSVC) target_sources(${TARGET} PRIVATE ${manifestPath}) else() configure_file(cmake/${TARGET}.manifest.rc.in ${TARGET}.manifest.rc @ONLY) target_sources(${TARGET} PRIVATE ${TARGET}.manifest.rc) endif() endif() endfunction() ```
/content/code_sandbox/Source/cmake/lib.cmake
cmake
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
929
```cmake # Much of this exclusion list was lifted from Blender (GPL-2.0-or-later). Thanks! file(INSTALL "${pyBulkInstallFrom}" DESTINATION "${pyBulkInstallTo}" USE_SOURCE_PERMISSIONS PATTERN "*.a" EXCLUDE PATTERN "*.exe" EXCLUDE PATTERN "*.orig" EXCLUDE PATTERN "*.pyc" EXCLUDE PATTERN "*.pyo" EXCLUDE PATTERN "*.rej" EXCLUDE PATTERN ".DS_Store" EXCLUDE PATTERN ".git" EXCLUDE PATTERN ".svn" EXCLUDE PATTERN "__MACOSX" EXCLUDE PATTERN "__pycache__" EXCLUDE PATTERN "idlelib" EXCLUDE PATTERN "lib-dynload/_tkinter.*" EXCLUDE PATTERN "lib2to3" EXCLUDE PATTERN "site-packages" EXCLUDE PATTERN "test" EXCLUDE PATTERN "tkinter" EXCLUDE PATTERN "turtle.py" EXCLUDE PATTERN "turtledemo" EXCLUDE ) set(BESPOKE_PIP_PACKAGES jedi) if(APPLE) function(relinkPySigned binary newPySO) # execute_process(COMMAND codesign --remove-signature "${binary}") execute_process(COMMAND ${CMAKE_INSTALL_NAME_TOOL} -change "${pySO}" "${newPySO}" "${binary}" COMMAND_ECHO STDOUT) endfunction() file(CREATE_LINK "${pyMajDotMin}" "${pyBulkInstallTo}/Current" SYMBOLIC) # Make codesign happy file(CREATE_LINK "../Frameworks/${pyFWName}/Versions/${pyMajDotMin}" "${bundleContents}/Resources/python" SYMBOLIC) file(CREATE_LINK "python${pyMajDotMin}" "${pyDirDst}/bin/python" SYMBOLIC) get_filename_component(pySO "${Python_LIBRARIES}" REALPATH) get_filename_component(pySOName "${pySO}" NAME) string(REGEX REPLACE ".*/${pyFWName}" "${pyFWName}" pyFWRelative "${pySO}") set(pyExecutable "${pyDirDst}/bin/python${pyMajDotMin}") # python.org Python links and is linked without @rpath, the next 3 lines fix this. execute_process(COMMAND ${CMAKE_INSTALL_NAME_TOOL} -change "${pySO}" "@loader_path/../Frameworks/${pyFWRelative}" "${targetBinary}") relinkPySigned("${pyExecutable}" "@executable_path/../${pySOName}") relinkPySigned("${pyDirDst}/Resources/Python.app/Contents/MacOS/Python" "@executable_path/../../../../${pySOName}") execute_process(COMMAND chmod -R u+w "${bundleContents}/Frameworks/${pyFWName}") execute_process(COMMAND codesign --remove-signature --deep "${bundleContents}/Frameworks/${pyFWName}") execute_process(COMMAND codesign -s - --deep "${bundleContents}/Frameworks/${pyFWName}") execute_process(COMMAND "${pyExecutable}" -m ensurepip COMMAND_ECHO STDOUT) execute_process(COMMAND "${pyExecutable}" -m pip install ${BESPOKE_PIP_PACKAGES} COMMAND_ECHO STDOUT) elseif(WIN32) get_filename_component(pyDirSrc "${Python_EXECUTABLE}" DIRECTORY) file(GLOB pyBinaries LIST_DIRECTORIES false "${pyDirSrc}/*.dll" "${pyDirSrc}/*.exe") file(INSTALL ${pyBinaries} DESTINATION "${pyDirDst}") file(INSTALL "${pyDirSrc}/DLLs" DESTINATION "${pyDirDst}") file(INSTALL "${CMAKE_CURRENT_BINARY_DIR}/python.manifest" DESTINATION "${pyDirDst}") set(pyExecutable "${pyDirDst}/python.exe") execute_process(COMMAND "${pyExecutable}" -m ensurepip) execute_process(COMMAND "${pyExecutable}" -m pip install ${BESPOKE_PIP_PACKAGES}) else() get_filename_component(pySO "${Python_LIBRARIES}" REALPATH) file(INSTALL "${pySO}" DESTINATION "${pyDirDst}/bin") execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${Python_EXECUTABLE}" "${pyDirDst}/bin/python") execute_process(COMMAND patchelf --set-rpath "$ORIGIN" "${pyDirDst}/bin/python") set(pyExecutable "${pyDirDst}/bin/python") endif() ```
/content/code_sandbox/Source/cmake/bundle-python.cmake
cmake
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
943
```cmake # This is a multi-role CMake file. The IF branch runs on include, the ELSE # branch runs in script mode or when re-included after setting BESPOKESRC. if(CMAKE_PARENT_LIST_FILE AND NOT BESPOKESRC) # Toggle this to on by default. here's my reasoning # 1. Users who know what they are doing and dont want this can turn it off # 2. Self build users who are struggling to build won't know to turn it off but need reliable build inf # so having it 'on' means a few power users add an option but the bug reports on discord get more # version accurate option(BESPOKE_RELIABLE_VERSION_INFO "Update version info on every build (off: generate only at configuration time)" ON) function(bespoke_buildtime_version_info TARGET) configure_file(VersionInfo.cpp.in geninclude/VersionInfo.cpp) target_sources(${TARGET} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/geninclude/VersionInfo.cpp ${CMAKE_CURRENT_BINARY_DIR}/geninclude/VersionInfoBld.cpp ) set(BESPOKE_BUILD_ARCH "${MSVC_CXX_ARCHITECTURE_ID}") if("${BESPOKE_BUILD_ARCH}" STREQUAL "") set(BESPOKE_BUILD_ARCH "${CMAKE_SYSTEM_PROCESSOR}") endif() if(BESPOKE_RELIABLE_VERSION_INFO) add_custom_target(version-info BYPRODUCTS ${CMAKE_CURRENT_BINARY_DIR}/geninclude/VersionInfoBld.cpp WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} COMMAND ${CMAKE_COMMAND} -D CMAKE_PROJECT_VERSION_MAJOR=${CMAKE_PROJECT_VERSION_MAJOR} -D CMAKE_PROJECT_VERSION_MINOR=${CMAKE_PROJECT_VERSION_MINOR} -D BESPOKE_BUILD_ARCH="${BESPOKE_BUILD_ARCH}" -D BESPOKESRC=${CMAKE_SOURCE_DIR} -D BESPOKEBLD=${CMAKE_CURRENT_BINARY_DIR} -D WIN32=${WIN32} -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/versiontools.cmake ) add_dependencies(${TARGET} version-info) else() set(BESPOKESRC ${CMAKE_SOURCE_DIR}) set(BESPOKEBLD ${CMAKE_CURRENT_BINARY_DIR}) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/versiontools.cmake) endif() endfunction() else() find_package(Git) if (NOT EXISTS ${BESPOKESRC}/.git) message(STATUS "This is not a .git checkout; Defaulting versions") set(GIT_BRANCH "unknown-branch") set(GIT_COMMIT_HASH "deadbeef") elseif (Git_FOUND) execute_process( COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD WORKING_DIRECTORY ${BESPOKESRC} OUTPUT_VARIABLE GIT_BRANCH OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD WORKING_DIRECTORY ${BESPOKESRC} OUTPUT_VARIABLE GIT_COMMIT_HASH OUTPUT_STRIP_TRAILING_WHITESPACE ) else() message(STATUS "GIT EXE not found Defaulting versions") set(GIT_BRANCH "built-without-git") set(GIT_COMMIT_HASH "deadbeef") endif () cmake_host_system_information(RESULT BESPOKE_BUILD_FQDN QUERY FQDN) message(STATUS "Setting up BESPOKE version") message(STATUS " git hash is ${GIT_COMMIT_HASH} and branch is ${GIT_BRANCH}") message(STATUS " buildhost is ${BESPOKE_BUILD_FQDN}") message(STATUS " buildarch is ${BESPOKE_BUILD_ARCH}") string(TIMESTAMP BESPOKE_BUILD_DATE "%Y-%m-%d") string(TIMESTAMP BESPOKE_BUILD_TIME "%H:%M:%S") message(STATUS "Configuring ${BESPOKEBLD}/geninclude/VersionInfoBld.cpp") configure_file(${BESPOKESRC}/Source/VersionInfoBld.cpp.in ${BESPOKEBLD}/geninclude/VersionInfoBld.cpp) endif() ```
/content/code_sandbox/Source/cmake/versiontools.cmake
cmake
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
909
```batchfile "C:\Program Files (x86)\WiX Toolset v3.11\bin\heat" dir ..\ignore\build\Source\BespokeSynth_artefacts\Release\resource -o HarvestedResourceDir.wxs -scom -frag -srd -sreg -gg -cg BespokeResourceDir -dr RESOURCE_DIR_REF "C:\Program Files (x86)\WiX Toolset v3.11\bin\heat" dir ..\ignore\build\Source\BespokeSynth_artefacts\Release\python -o HarvestedPythonDir.wxs -scom -frag -srd -sreg -gg -cg BespokePythonDir -dr PYTHON_DIR_REF "C:\Program Files (x86)\WiX Toolset v3.11\bin\candle" BespokeSynth.wxs HarvestedResourceDir.wxs HarvestedPythonDir.wxs -arch x64 "C:\Program Files (x86)\WiX Toolset v3.11\bin\light" BespokeSynth.wixobj HarvestedResourceDir.wixobj HarvestedPythonDir.wixobj -b ..\ignore\build\Source\BespokeSynth_artefacts\Release\resource -b ..\ignore\build\Source\BespokeSynth_artefacts\Release\python -out Bespoke-Windows.msi -ext WixUIExtension @pause ```
/content/code_sandbox/bespoke_windows_installer/bespoke_installer_create.bat
batchfile
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
299
```python import json before = '''<!DOCTYPE html> <html lang="en"> <head> <title>Bespoke Synth Reference</title> <link href="../css/accordion.css" rel="stylesheet"> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <div class="container">''' after = ''' </div> </body> </html>''' def getAcceptsInputsString(moduleInfo): ret = "" if "canReceivePulses" in moduleInfo: if moduleInfo["canReceivePulses"]: ret += "<font color=yellow>pulses</font> " if "canReceiveNote" in moduleInfo: if moduleInfo["canReceiveNote"]: ret += "<font color=orange>notes</font> " if "canReceiveAudio" in moduleInfo: if moduleInfo["canReceiveAudio"]: ret += "<font color=cyan>audio</font> " if ret != "": ret = "accepts: "+ret return ret documentation = json.load(open("module_documentation.json","r")) moduleTypes = ["instruments","note effects","synths","audio effects","modulators","pulse","effect chain","other"] modulesByType = {} longestColumn = 0 for moduleName in documentation.keys(): module = documentation[moduleName] if not module["type"] in modulesByType: modulesByType[module["type"]] = [] modulesByType[module["type"]].append(moduleName) longestColumn = max(longestColumn, len(modulesByType[module["type"]])) for moduleType in moduleTypes: modulesByType[moduleType].sort() html = open("bespokesynth.com/docs/index.html", "w") html.write(before) html.write(''' <nav class="menu"> <ul></br>Bespoke Synth Reference</br></br> <a href="#video">overview video</a> <a href="#basics">basics</a>''') for moduleType in moduleTypes: html.write(''' <input type="checkbox" name="menu" id="'''+moduleType.replace(" ","")+'''"> <li> <label for="'''+moduleType.replace(" ","")+'''" class="title">'''+moduleType+'''</label>''') for entry in modulesByType[moduleType]: if documentation[entry]["description"][0] == '[': continue html.write(''' <a href="#'''+entry+'''">'''+entry+'''</a>''') html.write(''' </li>''') html.write(''' </ul> </nav>''') html.write(''' <main class="main"> <a name=video></a></br> <h1>Bespoke Synth Reference</h1> <h2>overview video</h2> <span style="display:inline-block;margin-left:15px;"> <p>Here is a video detailing basic usage of Bespoke, including a bunch of less-obvious shortcuts and workflow features.</p> <p>There are some things in this video that are slightly out of date (I should make a new video!), but there is still plenty of useful information in there.</p> <iframe width="1120" height="630" src="path_to_url" frameborder="0" allowfullscreen></iframe> </span> <br/><br/> <a name=basics></a> <h2>basics</h2> <p>''') html.write(open("../resource/help.txt","r").read()) html.write(''' </p>''') for moduleType in moduleTypes: html.write(''' <h2>'''+moduleType+'''</h2>''') for module in modulesByType[moduleType]: moduleInfo = documentation[module] if moduleInfo["description"][0] == '[': continue html.write(''' <a name='''+module+'''></a></br> <b>'''+module+'''</b></br> <img src="screenshots/'''+module+'''.png"> </br> <span style="display:inline-block;margin-left:50px;"> ''') if "description" in moduleInfo: html.write(moduleInfo["description"]+"<br/><br/>") if "controls" in moduleInfo: for control in moduleInfo["controls"].keys(): tooltip = moduleInfo["controls"][control] if tooltip != "" and tooltip != "[todo]" and tooltip != "[none]": html.write("<b>"+control+"</b>: "+tooltip+"<br/>") acceptsInputs = getAcceptsInputsString(moduleInfo) if acceptsInputs != "": html.write("<br/>"+acceptsInputs+"<br/>") html.write('''</br></br></br></br> </span>''') html.write('''</main>''') html.write(after) ```
/content/code_sandbox/autodoc/autodoc.py
python
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,089
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Bespoke Synth</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/grayscale.css" rel="stylesheet"> <link href="css/custom.css" rel="stylesheet"> <!-- Custom Fonts --> <link rel="stylesheet" href="path_to_url" integrity="sha256-gsmEoJAws/Kd3CjuOQzLie5Q3yshhvmo7YNtBG7aaEY=" crossorigin="anonymous"> <link href="path_to_url" rel="stylesheet" type="text/css"> <link href="path_to_url" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="path_to_url"></script> <script src="path_to_url"></script> <![endif]--> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <!-- Navigation --> <!--<nav class="navbar navbar-custom navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse"> <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="#page-top"> <i class="fa fa-play-circle"></i> Bespoke </a> </div> <div class="collapse navbar-collapse navbar-right navbar-main-collapse"> <ul class="nav navbar-nav"> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="#about">About</a> </li> <li> <a class="page-scroll" href="#video">Video</a> </li> <li> <a class="page-scroll" href="#contact">Get</a> </li> </ul> </div> </div> </nav>--> <!-- Intro Header --> <header class="intro"> <div class="intro-body"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1 class="brand-heading">Bespoke</h1> <p class="intro-text">A modular DAW for Mac, Windows, and Linux.</p> <a href="#contact" class="btn btn-circle page-scroll"> <i class="fa fa-angle-double-down animated"></i> </a> </div> </div> </div> </div> </header> <!-- About Section --> <section id="about" class="container content-section text-center"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <h2>Introducing: Bespoke!</h2> <p>Bespoke is a software modular synthesizer. It contains a bunch of modules, which you can connect together to create sounds.<br/><img src="img/bespoke_patching.gif"/></p> <p>Bespoke is like a DAW* in some ways, but with less of a focus on a global timeline. Instead, it has a design more optimized for jamming and exploration.</p> <p>Bespoke is a project I started in 2011 as a way for me to learn more about creating music. Instead of putting in the time to learn the intricacies of an existing DAW, I took on a foolhardy exercise to try to build my own. The software is custom built by me and for me, hence the name "Bespoke".</p> <p>Bespoke's core design is to break everything into separate modules that can be patched together in a custom layout, much like a hardware modular. Bespoke is designed to be highly customizable, with the idea that any of the custom layouts that you create will be "bespoke" to you as well.</p> <p>In a way, Bespoke is like if I smashed Ableton to bits with a baseball bat, and asked you to put it back together.</p> <p><span class="table-footer"></br>*("DAW" means "digital audio workstation", which is a fancy term for music production software)</span></p> </div> </div> <p> <iframe width="1120" height="630" src="path_to_url" frameborder="0" allowfullscreen></iframe></p> </section> <!-- Contact Section --> <section id="contact" class="container content-section text-center"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <h2>Get Bespoke</h2> <p>Bespoke has releases for Mac, Windows, and Linux.<br/>It is <a href="path_to_url">open source</a>, licensed with GPLv3.</p> <p>Bespoke is free, but you can pay for it if you want. All versions are identical.<br/>Your payment goes directly to the <a href="path_to_url">NAACP Legal Defense and Educational Fund</a>.<br/>Here is a feature matrix for the pricing tiers:</p> </div> <p> <div class="box"> <!-- The surrounding box --> <!-- The front container --> <div class="front"> <table class="services-table"> <tr> <th class="services">Access to all 190+ modules</th> </tr> <tr> <th class="services">VST plugin hosting</th> </tr> <tr> <th class="services">MIDI controller support</th> </tr> <tr> <th class="services">Python livecoding</th> </tr> <tr> <th class="services">Windows, Mac, and Linux builds</th> </tr> <tr> <th class="services">Discord access</th> </tr> <tr> <th class="services">Access to all future updates</th> </tr> <tr> <th class="services">Access to documentation</th> </tr> <tr> <th class="services">$20 donated to charity</th> </tr> <tr> <th class="services">$40 donated to charity</th> </tr> </table> <table class="price-matrix" border="0"> <tr> <th class="header-free"><b>bespoke</b> <hr /> free </th> <th class="header-plus"><b>bespoke plus</b> <hr /> $20 </th> <th class="header-pro"><b>bespoke pro</b> <hr /> $40 </th> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"><div class="check"></div></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"></td> <td class="border"><div class="check"></div></td> <td><div class="check"></div></td> </tr> <tr> <td class="border"></td> <td class="border"></td> <td><div class="check"></div></td> </tr> <tr> <td class="padded"> <a href="path_to_url">Download for Windows</a><br/><br/> <a href="path_to_url">Download for Mac</a><br/><br/> <a href="path_to_url">Download for Linux</a> </td> <td class="payment-td"> <span class="payment-price-plus">$20</span> <div id="smart-button-container"> <div style="text-align: center;"> <div id="payment-button-container"> <script> function replaceAfterButtonClick() { const element = document.getElementById('payment-button-container'); element.innerHTML = ''; element.innerHTML = '<td class="padded">Thank you!!!<br/><a href="path_to_url">Download for Windows</a><br/><a href="path_to_url">Download for Mac</a><br/><a href="path_to_url">Download for Linux</a></td>'; } </script> <a href="path_to_url" class="donate-button" target="_blank" onclick="replaceAfterButtonClick();"><img src="img/ldf_donate_grey.png"/></a> </div> </div> </div> </td> <td class="payment-td"> <span class="payment-price-pro">$40</span> <div id="smart-button-container"> <div style="text-align: center;"> <div id="payment-button-container2"> <script> function replaceAfterButtonClick2() { const element = document.getElementById('payment-button-container2'); element.innerHTML = ''; element.innerHTML = '<td class="padded">Thank you!!!<br/><a href="path_to_url">Download for Windows</a><br/><a href="path_to_url">Download for Mac</a><br/><a href="path_to_url">Download for Linux</a></td>'; } </script> <a href="path_to_url" class="donate-button" target="_blank" onclick="replaceAfterButtonClick2();"><img src="img/ldf_donate.png"/></a> </div> </div> </div> </div> </td> </tr> </table> </div> </div> <div class="col-lg-8 col-lg-offset-2"> <span class="table-footer">(To be extra clear: all three versions of Bespoke above are identical, they are the exact same files. You are completely welcome to use Bespoke for free forever without paying anything, guilt-free.)</span> </br></br> <span class="table-footer">(You can also get the download links to the releases from GitHub <a href="path_to_url">here.</a>)</span> </div> </p> <div class="col-lg-8 col-lg-offset-2"> <p><br/>You can join the <a href="path_to_url">Discord</a> for discussion and support, and you can follow development progress on <a href="path_to_url">GitHub</a>.</p> <p>You can also find me on Twitter at <a href="path_to_url">@awwbees</a></p> <ul class="list-inline banner-social-buttons"> <li> <a href="path_to_url" class="btn btn-default btn-lg"><i class="fa fa-discord fa-fw"></i> <span class="network-name">Discord</span></a> </li> <li> <a href="path_to_url" class="btn btn-default btn-lg"><i class="fa fa-twitter fa-fw"></i> <span class="network-name">Twitter</span></a> </li> <li> <a href="path_to_url" class="btn btn-default btn-lg"><i class="fa fa-github fa-fw"></i> <span class="network-name">Github</span></a> </li> <li> <a href="path_to_url" class="btn btn-default btn-lg"><i class="fa fa-reddit fa-fw"></i> <span class="network-name">Reddit</span></a> </li> </ul> </div> </div> </section> <!-- Video Section --> <section id="video" class="content-section text-center"> <div class="container"> <div class="col-lg-8 col-lg-offset-2"> <h2>Getting Started</h2> <p>You can find the documentation for Bespoke and an introduction video <a href="docs/index.html">here</a>.</p> <p>All of the information on the usage of modules is also available via a tooltip system within the application.</p> </div> </div> </section> <!-- Footer --> <footer> <div class="container text-center"> <br/><br/><br/> <a href="path_to_url"><img src="img/bespoke_footer.png"/></a> <br/><br/><br/> </div> </footer> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="js/jquery.easing.min.js"></script> <!-- Google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-59239115-1', 'auto'); ga('send', 'pageview'); </script> </body> </html> ```
/content/code_sandbox/autodoc/bespokesynth.com/index.html
html
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,464
```less // Mixins ```
/content/code_sandbox/autodoc/bespokesynth.com/less/mixins.less
less
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5
```less @import "variables.less"; @import "mixins.less"; body { width: 100%; height: 100%; font-family: "Lora","Helvetica Neue",Helvetica,Arial,sans-serif; color: @light; background-color: @dark; } html { width: 100%; height: 100%; } h1, h2, h3, h4, h5, h6 { margin: 0 0 35px; text-transform: uppercase; font-family: "Montserrat","Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; letter-spacing: 1px; } p { margin: 0 0 25px; font-size: 18px; line-height: 1.5; } @media(min-width:767px) { p { margin: 0 0 35px; font-size: 20px; line-height: 1.6; } } a { color: @primary; -webkit-transition: all .2s ease-in-out; -moz-transition: all .2s ease-in-out; transition: all .2s ease-in-out; &:hover, &:focus { text-decoration: none; color: darken(@primary,20%); } } .light { font-weight: 400; } .navbar-custom { margin-bottom: 0; border-bottom: 1px solid fade(@light, 30%); text-transform: uppercase; font-family: "Montserrat","Helvetica Neue",Helvetica,Arial,sans-serif; background-color: @dark; .navbar-brand { font-weight: 700; &:focus { outline: none; } .navbar-toggle { padding: 4px 6px; font-size: 16px; color: @light; &:focus, &:active { outline: none; } } } a { color: @light; } .nav { li { &.active { outline: nonte; background-color: fade(@light, 30%); } a { -webkit-transition: background .3s ease-in-out; -moz-transition: background .3s ease-in-out; transition: background .3s ease-in-out; &:hover, &:focus, &.active { outline: none; background-color: fade(@light, 30%); } } } } } @media(min-width:767px) { .navbar { padding: 20px 0; border-bottom: none; letter-spacing: 1px; background: transparent; -webkit-transition: background .5s ease-in-out,padding .5s ease-in-out; -moz-transition: background .5s ease-in-out,padding .5s ease-in-out; transition: background .5s ease-in-out,padding .5s ease-in-out; } .top-nav-collapse { padding: 0; background-color: @dark; } .navbar-custom.top-nav-collapse { border-bottom: 1px solid fade(@light, 30%); } } .intro { display: table; width: 100%; height: auto; padding: 100px 0; text-align: center; color: @light; background: url(../img/intro-bg.jpg) no-repeat bottom center scroll; background-color: @dark; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; .intro-body { display: table-cell; vertical-align: middle; .brand-heading { font-size: 40px; } .intro-text { font-size: 18px; } } } @media(min-width:767px) { .intro { height: 100%; padding: 0; .intro-body { .brand-heading { font-size: 100px; } .intro-text { font-size: 25px; } } } } .btn-circle { width: 70px; height: 70px; margin-top: 15px; padding: 7px 16px; border: 2px solid @light; border-radius: 35px; font-size: 40px; color: @light; background: transparent; -webkit-transition: background .3s ease-in-out; -moz-transition: background .3s ease-in-out; transition: background .3s ease-in-out; &:hover, &:focus { outline: none; color: @light; background: fade(@light, 10%); } i.animated { -webkit-transition-property: -webkit-transform; -webkit-transition-duration: 1s; -moz-transition-property: -moz-transform; -moz-transition-duration: 1s; } &:hover { i.animated { -webkit-animation-name: pulse; -moz-animation-name: pulse; -webkit-animation-duration: 1.5s; -moz-animation-duration: 1.5s; -webkit-animation-iteration-count: infinite; -moz-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; -moz-animation-timing-function: linear; } } } @-webkit-keyframes pulse { 0 { -webkit-transform: scale(1); transform: scale(1); } 50% { -webkit-transform: scale(1.2); transform: scale(1.2); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @-moz-keyframes pulse { 0 { -moz-transform: scale(1); transform: scale(1); } 50% { -moz-transform: scale(1.2); transform: scale(1.2); } 100% { -moz-transform: scale(1); transform: scale(1); } } .content-section { padding-top: 100px; } .download-section { width: 100%; padding: 50px 0; color: @light; background: url(../img/downloads-bg.jpg) no-repeat center center scroll; background-color: @dark; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } #map { width: 100%; height: 200px; margin-top: 100px; } @media(min-width:767px) { .content-section { padding-top: 250px; } .download-section { padding: 100px 0; } #map { height: 400px; margin-top: 250px; } } .btn { text-transform: uppercase; font-family: "Montserrat","Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 400; -webkit-transition: all .3s ease-in-out; -moz-transition: all .3s ease-in-out; transition: all .3s ease-in-out; } .btn-default { border: 1px solid @primary; color: @primary; background-color: transparent; &:hover, &:focus { border: 1px solid @primary; outline: none; color: @dark; background-color: @primary; } } ul.banner-social-buttons { margin-top: 0; } @media(max-width:1199px) { ul.banner-social-buttons { margin-top: 15px; } } @media(max-width:767px) { ul.banner-social-buttons { li { display: block; margin-bottom: 20px; padding: 0; &:last-child { margin-bottom: 0; } } } } footer { padding: 50px 0; p { margin: 0; } } ::-moz-selection { text-shadow: none; background: #fcfcfc; background: fade(@light, 20%); } ::selection { text-shadow: none; background: #fcfcfc; background: fade(@light, 20%); } img::selection { background: transparent; } img::-moz-selection { background: transparent; } body { webkit-tap-highlight-color: fade(@light, 20%); } ```
/content/code_sandbox/autodoc/bespokesynth.com/less/grayscale.less
less
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,869
```less // Variables @primary: #219AB3; @dark: #000; @light: #fff; ```
/content/code_sandbox/autodoc/bespokesynth.com/less/variables.less
less
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
24
```css div.blueTable { font-family: Tahoma, Geneva, sans-serif; width: 100%; text-align: center; } .divTable.blueTable .divTableCell, .divTable.blueTable .divTableHead .divTableCellWide .divTableCellImage { border: 0px solid #AAAAAA; padding: 3px 2px; } .divTable.blueTable .divTableBody .divTableCell .divTableCellWide .divTableCellImage { font-size: 18px; color: #FFFFFF; } .divTableCellWide { width: 1000px; text-align: left; } .divTableCellImage { width: 500px; text-align: left; } .divTable.blueTable .divTableHeading { background: #373737; } .divTable.blueTable .divTableHeading .divTableHead { font-size: 22px; font-weight: bold; color: #FFFFFF; text-align: center; border-left: 2px solid #D0E4F5; } .divTable.blueTable .divTableHeading .divTableHead:first-child { border-left: none; } .blueTable .tableFootStyle { font-size: 14px; } .blueTable .tableFootStyle .links { text-align: right; } .blueTable .tableFootStyle .links a{ display: inline-block; background: #1C6EA4; color: #FFFFFF; padding: 2px 8px; border-radius: 5px; } .blueTable.outerTableFooter { border-top: none; } .blueTable.outerTableFooter .tableFootStyle { padding: 3px 5px; } /* DivTable.com */ .divTable{ display: table; } .divTableRow { display: table-row; } .divTableHeading { display: table-header-group;} .divTableCell, .divTableHead { display: table-cell;} .divTableHeading { display: table-header-group;} .divTableFoot { display: table-footer-group;} .divTableBody { display: table-row-group;} ```
/content/code_sandbox/autodoc/bespokesynth.com/css/table.css
css
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
458
```css .box { width: 1100px; margin: 50px auto; position: relative; /*left: -50px;*/ } .table-footer { color: #bbb; font-size: 12px; } /* Services Col */ .services-table { float: left; margin-top: 156px; z-index: 0; margin-right: 1px; } .services-table tr { height: 40px; background: rgb(56, 56, 56); border-bottom: 1px solid #5a5a5a; } .services-table tr:last-child { border-bottom: none; } .services-table th.services { color: #e4e4e4; font-weight: 100; min-width: 300px; background: rgb(43, 43, 43); padding-left: 10px } /* Entrepreneur and Business Pro Col */ table.price-matrix { -webkit-box-shadow: 0 0 16px 0 rgba(0,0,0, 1); box-shadow: 0 0 16px 0 rgba(0,0,0, 1); float: left; } table.price-matrix tr { height: 40px; background: rgb(40, 40, 40); } /* Headers */ table.price-matrix th.header-free { color: #707478; } table.price-matrix th.header-plus, .payment-price-plus { color: #91979e; } table.price-matrix th.header-pro, .payment-price-pro { color: #b6c2ce; } table.price-matrix th.header-free, table.price-matrix th.header-plus, table.price-matrix th.header-pro { font-weight: 100; font-size: 30px; min-width: 230px; text-align: center; padding: 15px 0; background: rgb(43, 43, 43); border-right: 1px solid #464646; } table.price-matrix th:last-child { border-right: none; } th.header-free hr, th.header-plus hr, th.header-pro hr { width: 70%; /*border-bottom: 1px solid;*/ } /* Rows */ tr:nth-child(even) td { background: #3d3d3d; } td.border { border-right: 1px solid #464646; text-align:center; } td.padded { border-right: 1px solid #464646; text-align:center; padding-top: 10px; padding-bottom: 10px; padding-left: 20px; padding-right: 20px; position: relative; z-index: 10; } td.payment-td { border-right: 1px solid #464646; text-align:center; padding-top: 10px; padding-bottom: 10px; padding-left: 20px; padding-right: 20px; color: #a0a0a0; font-size: 10px; } td.payment-td:last-child { border-right: none; } .payment-price-plus, .payment-price-pro { font-size: 25px; } tr { height: 40px; } .check { --borderWidth: 5px; --height: 24px; --width: 12px; --borderColor: #78b13f; display: inline-block; transform: rotate(45deg); height: var(--height); width: var(--width); border-bottom: var(--borderWidth) solid var(--borderColor); border-right: var(--borderWidth) solid var(--borderColor); } .donate-button { background-color: #003F4E; border: none; color: white; padding: 5px 11px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 9999px; } .donate-button:hover { background-color: #04AA6D; color: white; } ```
/content/code_sandbox/autodoc/bespokesynth.com/css/custom.css
css
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
944
```css /*! * Bootstrap v3.3.2 (path_to_url ```
/content/code_sandbox/autodoc/bespokesynth.com/css/bootstrap.min.css
css
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
15
```css /*! * Start Bootstrap - Grayscale Bootstrap Theme (path_to_url * For details, see path_to_url */ body { width: 100%; height: 100%; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; color: #fff; background-color: #111; } html { width: 100%; height: 100%; } h1, h2, h3, h4, h5, h6 { margin: 0 0 35px; text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; letter-spacing: 1px; } p { margin: 0 0 25px; font-size: 18px; line-height: 1.5; } @media(min-width:767px) { p { margin: 0 0 35px; font-size: 20px; line-height: 1.6; } } a { color: #b0f2ff; -webkit-transition: all .2s ease-in-out; -moz-transition: all .2s ease-in-out; transition: all .2s ease-in-out; } a:hover, a:focus { text-decoration: none; color: #61a3b1; } .light { font-weight: 400; } .navbar-custom { margin-bottom: 0; border-bottom: 1px solid rgba(255,255,255,.3); text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; background-color: #000; } .navbar-custom .navbar-brand { font-weight: 700; } .navbar-custom .navbar-brand:focus { outline: 0; } .navbar-custom .navbar-brand .navbar-toggle { padding: 4px 6px; font-size: 16px; color: #fff; } .navbar-custom .navbar-brand .navbar-toggle:focus, .navbar-custom .navbar-brand .navbar-toggle:active { outline: 0; } .navbar-custom a { color: #fff; } .navbar-custom .nav li.active { outline: nonte; background-color: rgba(255,255,255,.3); } .navbar-custom .nav li a { -webkit-transition: background .3s ease-in-out; -moz-transition: background .3s ease-in-out; transition: background .3s ease-in-out; } .navbar-custom .nav li a:hover, .navbar-custom .nav li a:focus, .navbar-custom .nav li a.active { outline: 0; background-color: rgba(255,255,255,.3); } @media(min-width:767px) { .navbar { padding: 20px 0; border-bottom: 0; letter-spacing: 1px; background: 0 0; -webkit-transition: background .5s ease-in-out,padding .5s ease-in-out; -moz-transition: background .5s ease-in-out,padding .5s ease-in-out; transition: background .5s ease-in-out,padding .5s ease-in-out; } .top-nav-collapse { padding: 0; background-color: #000; } .navbar-custom.top-nav-collapse { border-bottom: 1px solid rgba(255,255,255,.3); } } .intro { display: table; width: 100%; height: auto; padding: 100px 0; text-align: center; color: #fff; background: url(../img/intro-bg.jpg) no-repeat bottom center scroll; background-color: #000; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } .intro .intro-body { display: table-cell; vertical-align: middle; } .intro .intro-body .brand-heading { font-size: 40px; } .intro .intro-body .intro-text { font-size: 18px; } @media(min-width:767px) { .intro { height: 100%; padding: 0; } .intro .intro-body .brand-heading { font-size: 100px; } .intro .intro-body .intro-text { font-size: 25px; } } .btn-circle { width: 70px; height: 70px; margin-top: 15px; padding: 7px 16px; border: 2px solid #fff; border-radius: 35px; font-size: 40px; color: #fff; background: 0 0; -webkit-transition: background .3s ease-in-out; -moz-transition: background .3s ease-in-out; transition: background .3s ease-in-out; } .btn-circle:hover, .btn-circle:focus { outline: 0; color: #fff; background: rgba(255,255,255,.1); } .btn-circle i.animated { -webkit-transition-property: -webkit-transform; -webkit-transition-duration: 1s; -moz-transition-property: -moz-transform; -moz-transition-duration: 1s; } .btn-circle:hover i.animated { -webkit-animation-name: pulse; -moz-animation-name: pulse; -webkit-animation-duration: 1.5s; -moz-animation-duration: 1.5s; -webkit-animation-iteration-count: infinite; -moz-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; -moz-animation-timing-function: linear; } @-webkit-keyframes pulse { 0 { -webkit-transform: scale(1); transform: scale(1); } 50% { -webkit-transform: scale(1.2); transform: scale(1.2); } 100% { -webkit-transform: scale(1); transform: scale(1); } } @-moz-keyframes pulse { 0 { -moz-transform: scale(1); transform: scale(1); } 50% { -moz-transform: scale(1.2); transform: scale(1.2); } 100% { -moz-transform: scale(1); transform: scale(1); } } .content-section { padding-top: 100px; } .download-section { width: 100%; padding: 50px 0; color: #fff; background: url(../img/downloads-bg.jpg) no-repeat center center scroll; background-color: #000; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } #map { width: 100%; height: 200px; margin-top: 100px; } @media(min-width:767px) { .content-section { padding-top: 250px; } .download-section { padding: 100px 0; } #map { height: 400px; margin-top: 250px; } } .btn { text-transform: uppercase; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 400; -webkit-transition: all .3s ease-in-out; -moz-transition: all .3s ease-in-out; transition: all .3s ease-in-out; } .btn-default { border: 1px solid #219ab3; color: #219ab3; background-color: transparent; } .btn-default:hover, .btn-default:focus { border: 1px solid #219ab3; outline: 0; color: #000; background-color: #219ab3; } ul.banner-social-buttons { margin-top: 0; } @media(max-width:1199px) { ul.banner-social-buttons { margin-top: 15px; } } @media(max-width:767px) { ul.banner-social-buttons li { display: block; margin-bottom: 20px; padding: 0; } ul.banner-social-buttons li:last-child { margin-bottom: 0; } } footer { padding: 50px 0; } footer p { margin: 0; } ::-moz-selection { text-shadow: none; background: #fcfcfc; background: rgba(255,255,255,.2); } ::selection { text-shadow: none; background: #fcfcfc; background: rgba(255,255,255,.2); } img::selection { background: 0 0; } img::-moz-selection { background: 0 0; } body { webkit-tap-highlight-color: rgba(255,255,255,.2); } ```
/content/code_sandbox/autodoc/bespokesynth.com/css/grayscale.css
css
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,960
```css @import url(path_to_url @import url(path_to_url|Open+Sans:400,300); * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; } .container { width: 100%; height: 100%; } nav { position: fixed; display: flex; align-items: flex-start; width: 15%; height: 100%; background-color: #111; overflow: auto; } main { position: fixed; right: 0; width: 85%; height: 100%; background-color: #111; overflow: auto; padding: 40px; color: #fff; } h1 { font-weight: bold; margin-bottom: 50px; font-size: 55px; text-align: center; } p { margin-bottom: 20px; line-height: 26px; white-space: pre-wrap; /* preserve WS, wrap as necessary, preserve LB */ } li, ul label.title, ul, a { width: 100%; color: #FFF; font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif; display: block; font-weight: bold; } ul label { height: 35px; } ul li{ height: 35px; overflow: hidden; transition: all .3s; } li { display: block; background-color: #555555; } label.title { font-size: 14px; background: #2f2f2f; padding: 10px 15px; cursor: pointer; transition: all .25s; } a{ font-size: 12px; text-decoration: none; color: #FFF; display: block; padding: 10px 25px; transition: all .25s; } label:hover { text-shadow: 0px 0px 10px #fff; } input[type="checkbox"] { display: none; } #edit:checked + li, #archive:checked + li, #tools:checked + li, #preferences:checked + li, #instruments:checked + li, #noteeffects:checked + li, #synths:checked + li, #audioeffects:checked + li, #modulators:checked + li, #pulse:checked + li, #effectchain:checked + li, #other:checked + li { height: 100%; } i { margin-right: 12px; } @media screen and (max-width: 600px){ nav { width: 100%; position: relative; } main { width: 100%; position: relative; } } ```
/content/code_sandbox/autodoc/bespokesynth.com/css/accordion.css
css
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
565
```html <!DOCTYPE html> <html lang="en"> <head> <title>Bespoke Synth Reference</title> <link href="../css/accordion.css" rel="stylesheet"> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <div class="container"> <nav class="menu"> <ul></br>Bespoke Synth Reference</br></br> <a href="#video">overview video</a> <a href="#basics">basics</a> <input type="checkbox" name="menu" id="instruments"> <li> <label for="instruments" class="title">instruments</label> <a href="#circlesequencer">circlesequencer</a> <a href="#drumsequencer">drumsequencer</a> <a href="#fouronthefloor">fouronthefloor</a> <a href="#gridkeyboard">gridkeyboard</a> <a href="#keyboarddisplay">keyboarddisplay</a> <a href="#m185sequencer">m185sequencer</a> <a href="#midicontroller">midicontroller</a> <a href="#notecanvas">notecanvas</a> <a href="#notechain">notechain</a> <a href="#notecounter">notecounter</a> <a href="#notecreator">notecreator</a> <a href="#notelooper">notelooper</a> <a href="#notesequencer">notesequencer</a> <a href="#notesinger">notesinger</a> <a href="#playsequencer">playsequencer</a> <a href="#polyrhythms">polyrhythms</a> <a href="#randomnote">randomnote</a> <a href="#slidersequencer">slidersequencer</a> </li> <input type="checkbox" name="menu" id="noteeffects"> <li> <label for="noteeffects" class="title">note effects</label> <a href="#arpeggiator">arpeggiator</a> <a href="#capo">capo</a> <a href="#chorddisplayer">chorddisplayer</a> <a href="#chorder">chorder</a> <a href="#chordholder">chordholder</a> <a href="#gridnotedisplayer">gridnotedisplayer</a> <a href="#midicc">midicc</a> <a href="#midioutput">midioutput</a> <a href="#modulationvizualizer">modulationvizualizer</a> <a href="#modwheel">modwheel</a> <a href="#modwheeltopressure">modwheeltopressure</a> <a href="#modwheeltovibrato">modwheeltovibrato</a> <a href="#mpesmoother">mpesmoother</a> <a href="#mpetweaker">mpetweaker</a> <a href="#notechance">notechance</a> <a href="#notedelayer">notedelayer</a> <a href="#notedisplayer">notedisplayer</a> <a href="#noteduration">noteduration</a> <a href="#noteecho">noteecho</a> <a href="#noteexpression">noteexpression</a> <a href="#notefilter">notefilter</a> <a href="#noteflusher">noteflusher</a> <a href="#notegate">notegate</a> <a href="#notehocket">notehocket</a> <a href="#notehumanizer">notehumanizer</a> <a href="#notelatch">notelatch</a> <a href="#noteoctaver">noteoctaver</a> <a href="#notepanalternator">notepanalternator</a> <a href="#notepanner">notepanner</a> <a href="#notepanrandom">notepanrandom</a> <a href="#noterangefilter">noterangefilter</a> <a href="#noteratchet">noteratchet</a> <a href="#noterouter">noterouter</a> <a href="#notesorter">notesorter</a> <a href="#notestepper">notestepper</a> <a href="#notestream">notestream</a> <a href="#notestrummer">notestrummer</a> <a href="#notetable">notetable</a> <a href="#notewrap">notewrap</a> <a href="#pitchbender">pitchbender</a> <a href="#pitchdive">pitchdive</a> <a href="#pitchpanner">pitchpanner</a> <a href="#pitchremap">pitchremap</a> <a href="#pitchsetter">pitchsetter</a> <a href="#portamento">portamento</a> <a href="#pressure">pressure</a> <a href="#pressuretomodwheel">pressuretomodwheel</a> <a href="#pressuretovibrato">pressuretovibrato</a> <a href="#previousnote">previousnote</a> <a href="#quantizer">quantizer</a> <a href="#scaledegree">scaledegree</a> <a href="#scaledetect">scaledetect</a> <a href="#sustainpedal">sustainpedal</a> <a href="#transposefrom">transposefrom</a> <a href="#unstablemodwheel">unstablemodwheel</a> <a href="#unstablepitch">unstablepitch</a> <a href="#unstablepressure">unstablepressure</a> <a href="#velocitycurve">velocitycurve</a> <a href="#velocityscaler">velocityscaler</a> <a href="#velocitysetter">velocitysetter</a> <a href="#velocitystepsequencer">velocitystepsequencer</a> <a href="#velocitytochance">velocitytochance</a> <a href="#vibrato">vibrato</a> <a href="#volcabeatscontrol">volcabeatscontrol</a> <a href="#whitekeys">whitekeys</a> </li> <input type="checkbox" name="menu" id="synths"> <li> <label for="synths" class="title">synths</label> <a href="#beats">beats</a> <a href="#drumplayer">drumplayer</a> <a href="#drumsynth">drumsynth</a> <a href="#fmsynth">fmsynth</a> <a href="#karplusstrong">karplusstrong</a> <a href="#metronome">metronome</a> <a href="#oscillator">oscillator</a> <a href="#samplecanvas">samplecanvas</a> <a href="#sampleplayer">sampleplayer</a> <a href="#sampler">sampler</a> <a href="#seaofgrain">seaofgrain</a> <a href="#signalgenerator">signalgenerator</a> </li> <input type="checkbox" name="menu" id="audioeffects"> <li> <label for="audioeffects" class="title">audio effects</label> <a href="#audiometer">audiometer</a> <a href="#audiorouter">audiorouter</a> <a href="#buffershuffler">buffershuffler</a> <a href="#dcoffset">dcoffset</a> <a href="#effectchain">effectchain</a> <a href="#eq">eq</a> <a href="#feedback">feedback</a> <a href="#fftvocoder">fftvocoder</a> <a href="#freqdelay">freqdelay</a> <a href="#gain">gain</a> <a href="#input">input</a> <a href="#inverter">inverter</a> <a href="#lissajous">lissajous</a> <a href="#looper">looper</a> <a href="#looperrecorder">looperrecorder</a> <a href="#looperrewriter">looperrewriter</a> <a href="#multitapdelay">multitapdelay</a> <a href="#output">output</a> <a href="#panner">panner</a> <a href="#ringmodulator">ringmodulator</a> <a href="#samplergrid">samplergrid</a> <a href="#send">send</a> <a href="#signalclamp">signalclamp</a> <a href="#spectrum">spectrum</a> <a href="#splitter">splitter</a> <a href="#stutter">stutter</a> <a href="#vocoder">vocoder</a> <a href="#vocodercarrier">vocodercarrier</a> <a href="#waveformviewer">waveformviewer</a> <a href="#waveshaper">waveshaper</a> </li> <input type="checkbox" name="menu" id="modulators"> <li> <label for="modulators" class="title">modulators</label> <a href="#accum">accum</a> <a href="#add">add</a> <a href="#addcentered">addcentered</a> <a href="#audiotocv">audiotocv</a> <a href="#controlsequencer">controlsequencer</a> <a href="#curve">curve</a> <a href="#curvelooper">curvelooper</a> <a href="#envelope">envelope</a> <a href="#expression">expression</a> <a href="#fubble">fubble</a> <a href="#gravity">gravity</a> <a href="#gridsliders">gridsliders</a> <a href="#leveltocv">leveltocv</a> <a href="#lfo">lfo</a> <a href="#macroslider">macroslider</a> <a href="#modwheeltocv">modwheeltocv</a> <a href="#mult">mult</a> <a href="#notetofreq">notetofreq</a> <a href="#notetoms">notetoms</a> <a href="#pitchtocv">pitchtocv</a> <a href="#pitchtospeed">pitchtospeed</a> <a href="#pressuretocv">pressuretocv</a> <a href="#ramper">ramper</a> <a href="#smoother">smoother</a> <a href="#subtract">subtract</a> <a href="#valuesetter">valuesetter</a> <a href="#velocitytocv">velocitytocv</a> <a href="#vinylcontrol">vinylcontrol</a> </li> <input type="checkbox" name="menu" id="pulse"> <li> <label for="pulse" class="title">pulse</label> <a href="#audiotopulse">audiotopulse</a> <a href="#boundstopulse">boundstopulse</a> <a href="#notetopulse">notetopulse</a> <a href="#pulsebutton">pulsebutton</a> <a href="#pulsechance">pulsechance</a> <a href="#pulsedelayer">pulsedelayer</a> <a href="#pulsedisplayer">pulsedisplayer</a> <a href="#pulseflag">pulseflag</a> <a href="#pulsegate">pulsegate</a> <a href="#pulsehocket">pulsehocket</a> <a href="#pulser">pulser</a> <a href="#pulsesequence">pulsesequence</a> <a href="#pulsetrain">pulsetrain</a> </li> <input type="checkbox" name="menu" id="effectchain"> <li> <label for="effectchain" class="title">effect chain</label> <a href="#basiceq">basiceq</a> <a href="#biquad">biquad</a> <a href="#bitcrush">bitcrush</a> <a href="#butterworth">butterworth</a> <a href="#compressor">compressor</a> <a href="#dcremover">dcremover</a> <a href="#delay">delay</a> <a href="#distortion">distortion</a> <a href="#freeverb">freeverb</a> <a href="#gainstage">gainstage</a> <a href="#gate">gate</a> <a href="#granulator">granulator</a> <a href="#muter">muter</a> <a href="#noisify">noisify</a> <a href="#pitchshift">pitchshift</a> <a href="#pumper">pumper</a> <a href="#tremolo">tremolo</a> </li> <input type="checkbox" name="menu" id="other"> <li> <label for="other" class="title">other</label> <a href="#abletonlink">abletonlink</a> <a href="#clockin">clockin</a> <a href="#clockout">clockout</a> <a href="#comment">comment</a> <a href="#eventcanvas">eventcanvas</a> <a href="#globalcontrols">globalcontrols</a> <a href="#grid">grid</a> <a href="#groupcontrol">groupcontrol</a> <a href="#loopergranulator">loopergranulator</a> <a href="#multitrackrecorder">multitrackrecorder</a> <a href="#notetoggle">notetoggle</a> <a href="#oscoutput">oscoutput</a> <a href="#prefab">prefab</a> <a href="#push2control">push2control</a> <a href="#radiosequencer">radiosequencer</a> <a href="#samplebrowser">samplebrowser</a> <a href="#scale">scale</a> <a href="#script">script</a> <a href="#scriptstatus">scriptstatus</a> <a href="#selector">selector</a> <a href="#snapshots">snapshots</a> <a href="#songbuilder">songbuilder</a> <a href="#timelinecontrol">timelinecontrol</a> <a href="#timerdisplay">timerdisplay</a> <a href="#transport">transport</a> <a href="#valuestream">valuestream</a> </li> </ul> </nav> <main class="main"> <a name=video></a></br> <h1>Bespoke Synth Reference</h1> <h2>overview video</h2> <span style="display:inline-block;margin-left:15px;"> <p>Here is a video detailing basic usage of Bespoke, including a bunch of less-obvious shortcuts and workflow features.</p> <p>There are some things in this video that are slightly out of date (I should make a new video!), but there is still plenty of useful information in there.</p> <iframe width="1120" height="630" src="path_to_url" frameborder="0" allowfullscreen></iframe> </span> <br/><br/> <a name=basics></a> <h2>basics</h2> <p> Navigation * space bar + move mouse to pan, or right-click drag in empty space * space bar + mousewheel/trackpad-scroll to zoom, or scroll in empty space * if you get lost, press ~ to bring up the console, type "home", and press enter to reset to the initial position and zoom * if you have enabled the minimap in the settings, you can click on the minimap to directly go to a location -at the bottom of the mimimap you can click on 9 bookmark buttons -hold shift while clicking will store your current location into that bookmark button -use shift+[num] to go to the specified bookmark Creating Modules * drag items out of the top bar menus OR * right-click and select from the popup menu OR * right-click and start typing the name of the module you want, then drag it out of the popup menu OR * hold the first letter of a module and drag them out of the popup menu OR * drag a cable into space and spawn a connecting module from the popup * to delete a module, lasso select + backspace OR use the triangle menu and choose "delete module" * to duplicate a module, hold alt/option and drag from the title bar Patching * drag the circle from the bottom of a module to the target OR click the circle then click the target to patch * drag a cable and press backspace to unpatch * hold shift while grabbing a patch cable circle to split * hold shift while releasing a patch cable on a target to insert * while holding shift, drag a module by the title bar and touch its circle to another module, or the mouse pointer to another module's circle, to quick patch UI Controls * click or drag a slider to adjust its value * hold shift to fine-tune * while hovered: -use mousewheel/trackpad-scroll to adjust (shift to fine-tune) -type a value into a slider (such as 1.5) and press enter -type an expression into a slider (such as 1/16 or +=10) and press enter -press up or down to increase the value by 1 (hold shift for .01) -press [ or ] to halve or double the value -press \ to reset to the initial value * hold alt/option and drag to adjust slew amount (smoothing) * right click a slider to add an LFO -click and drag a green modulated slider vertically to adjust the modulation min, and horizontally to adjust the modulation max * hold ctrl/command and click the lower or upper half of a slider to adjust that slider's minimum or maximum value, to give it increased or reduced range (warning! increasing range can lead to unpredictable behavior in some cases) * press tab to cycle through controls on a module * press ctrl/command+arrows to navigate around controls on a module Saving * "write audio" button: write the last 30 minutes of audio to the /data/recordings folder, perfect for making sure you don't miss any cool moments * "save state" button: save the current layout to a file. shortcut: ctrl-s * "load state" button: load previously saved layouts. shortcut: ctrl-l Key Commands * ctrl/command-'s': save * ctrl/command-'l': load * shift-'p': pause audio processing. this will stop all audio output. press shift-'p' again to resume * F2: toggle displaying all ADSR controls as sliders </p> <h2>instruments</h2> <a name=circlesequencer></a></br> <b>circlesequencer</b></br> <img src="screenshots/circlesequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> polyrhythmic sequencer that displays a loop as a circle<br/><br/><b>length*</b>: number of steps in this ring<br/><b>note*</b>: pitch to use for this ring<br/><b>offset*</b>: timing offset for this ring<br/></br></br></br></br> </span> <a name=drumsequencer></a></br> <b>drumsequencer</b></br> <img src="screenshots/drumsequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> step sequencer intended for drums. hold shift when dragging on the grid to adjust step velocity.<br/><br/><b>r lock*</b>: lock this row so it doesn't get randomized<br/><b>repeat</b>: repeat input notes at this rate<br/><b>offsets</b>: show "offsets" sliders<br/><b>column</b>: current column, to use for visualizing the step on a midi controller<br/><b>randomize</b>: randomize the sequence<br/><b>clear</b>: clear sequence<br/><b>measures</b>: length of the sequence in measures<br/><b>metastep</b>: patch a grid in here from a "midicontroller" module to control the "meta step". I forget what this does. oops.<br/><b>r den</b>: density of the randomizer output. the higher this is, the busier the random output will be.<br/><b>r amt</b>: the chance that each step will change when being randomized. low values will only change a small amount of the sequence, high values will replace more of the sequence.<br/><b>step</b>: length of each step<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><b>yoff</b>: vertical offset for grid controller's view of the pattern<br/><b>velocity</b>: patch a grid in here from a "midicontroller" module to control the velocity<br/><b>rowpitch*</b>: output pitch for this row<br/><b>vel</b>: velocity to use when setting a step<br/><b>random*</b>: randomize this row<br/><b><</b>: shift whole pattern one step earlier<br/><b>offset*</b>: shift row forward/backward in time. try making your snares a little early, your hats a little late, etc.<br/><b>></b>: shift whole pattern one step later<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=fouronthefloor></a></br> <b>fouronthefloor</b></br> <img src="screenshots/fouronthefloor.png"> </br> <span style="display:inline-block;margin-left:50px;"> sends note 0 every beat, to trigger a kick drum<br/><br/><b>two</b>: sends note only every two beats<br/></br></br></br></br> </span> <a name=gridkeyboard></a></br> <b>gridkeyboard</b></br> <img src="screenshots/gridkeyboard.png"> </br> <span style="display:inline-block;margin-left:50px;"> grid-based keyboard, intended primarily for 64-pad grid controllers<br/><br/><b>layout</b>: keyboard style<br/><b>p.root</b>: for chorder, make root note always play<br/><b>arrangement</b>: what style of layout should we use?<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><b>octave</b>: base octave<br/><b>latch</b>: latch key presses, so you press once to play a note, and press again to release a note<br/><b>ch.latch</b>: latch chord button presses<br/></br></br></br></br> </span> <a name=keyboarddisplay></a></br> <b>keyboarddisplay</b></br> <img src="screenshots/keyboarddisplay.png"> </br> <span style="display:inline-block;margin-left:50px;"> displays input notes on a keyboard, and allows you to click the keyboard to create notes<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=m185sequencer></a></br> <b>m185sequencer</b></br> <img src="screenshots/m185sequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> sequencer using the unique paradigm of the m185 or intellijel metropolis<br/><br/><b>gate*</b>: behavior for each row: "repeat" plays every step, "once" plays just the first step, "hold" holds across all steps, "rest" plays no steps<br/><b>pitch*</b>: pitch to use for this row<br/><b>interval</b>: interval per step<br/><b>pulses*</b>: number of steps this row should last<br/><b>reset step</b>: resets counter to first step<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=midicontroller></a></br> <b>midicontroller</b></br> <img src="screenshots/midicontroller.png"> </br> <span style="display:inline-block;margin-left:50px;"> get midi input from external devices. to get a nice display in the "layout" view, create a .json file with the same name as your controller to describe your controller's layout, and place it in your "data/controllers" directory. look at the other files in that directory for examples.<br/><br/><b>control</b>: pitch or control to refer to<br/><b>feedback</b>: which cc or note should we send the feedback to?<br/><b>blink</b>: when the targeted control is enabled, send alternating on/off messages, to blink the associated LED<br/><b>controltype</b>: how this control should modify the target. -slider: set the value interpolated between "midi off" and "midi on" to the slider's value -set: set the specified value directly when this button is pressed -release: set the specified value directly when this button is released -toggle: toggle the control's value to on/off when this button is pressed -direct: set the control to the literal midi input value<br/><b>increment</b>: when "controltype" is "set" or "release", the targeted control is incremented by this amount (and the "value" field is ignored). when "controltype" is "slider", the targeted control is changed by this amount in the direction the control was changed (this setting is useful for "infinite encoders")<br/><b>scale</b>: should the output of this midi slider be scaled between "midi off" and "midi on"?<br/><b>layout</b>: which layout file should we use for this controller? these can be created in your Documents/BespokeSynth/controllers folder.<br/><b>messagetype</b>: type of midi message<br/><b>add</b>: add a mapping manually<br/><b>midi on</b>: the upper end of the midi range. send this value when the targeted control is on. if "scale" is enabled, this also controls the upper end of the slider range, and you can set midi off to be higher than midi on to reverse a slider's direction.<br/><b>osc input port</b>: port to use for osccontroller input<br/><b>channel</b>: which channel to pay attention to<br/><b>midi off</b>: the lower end of the midi range. send this value when the targeted control is off. if "scale" is enabled, this also controls the lower end of the slider range, and you can set midi off to be higher than midi on to reverse a slider's direction.<br/><b>pageless</b>: should this connection work across all pages of the midicontroller?<br/><b>path</b>: path to the control that should be affected. you can also enter "hover" here, to affect whichever control the mouse is hovering over.<br/><b>bind (hold shift)</b>: when this is enabled, you can map a midi input to a UI control by hovering over a UI control, holding shift, and then using desired midi input<br/><b>copy</b>: duplicate this connection<br/><b>monome</b>: which monome should we use?<br/><b>mappingdisplay</b>: which mapping view to see<br/><b> x </b>: delete this connection<br/><b>controller</b>: midi device to use<br/><b>value</b>: the value to set<br/><b>twoway</b>: should we send feedback to the controller? (to control the LEDs associated with the button/knob)<br/><b>page</b>: select which page of midi controls to use. each page acts like an independent midi controller, so you can use pages to allow one midi controller to switch between controlling many things<br/></br></br></br></br> </span> <a name=notecanvas></a></br> <b>notecanvas</b></br> <img src="screenshots/notecanvas.png"> </br> <span style="display:inline-block;margin-left:50px;"> looping note roll<br/><br/><b>scrollv</b>: vertical scrollbar<br/><b>canvas</b>: canvas of notes. canvas controls: -shift-click to add a note -hold shift and drag a note to duplicate -hold alt to drag a note without snapping -hold ctrl while dragging to snap to an interval -hold shift and scroll to zoom -hold alt and grab empty space to move slide the canvas view -hold ctrl and grab empty space to zoom the canvas view<br/><b>measures</b>: loop length<br/><b>drag mode</b>: direction that elements can be dragged<br/><b>view rows</b>: number of visible rows<br/><b>loadtrack</b>: which track number to import when using "load midi"<br/><b>timeline</b>: control loop points<br/><b>clear</b>: delete all elements<br/><b>interval</b>: interval to quantize to<br/><b>play</b>: play notes on canvas<br/><b>quantize</b>: quantize selected notes to interval<br/><b>save midi</b>: export canvas contents to a midi file<br/><b>load midi</b>: import canvas contents from a midi file<br/><b>rec</b>: record input notes to canvas<br/><b>show chord intervals</b>: show brackets to indicate chord relationships<br/><b>free rec</b>: enable record mode, and extend canvas if we reach the end<br/><b>scrollh</b>: horizontal scrollbar<br/><b>delete</b>: delete highlighted elements<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notechain></a></br> <b>notechain</b></br> <img src="screenshots/notechain.png"> </br> <span style="display:inline-block;margin-left:50px;"> trigger a note, followed by a pulse to trigger another note after a delay<br/><br/><b>duration</b>: duration of note, in measures<br/><b>trigger</b>: play note for this chain node<br/><b>pitch</b>: pitch to play<br/><b>velocity</b>: velocity for note<br/><b>next</b>: interval until sending pulse<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=notecounter></a></br> <b>notecounter</b></br> <img src="screenshots/notecounter.png"> </br> <span style="display:inline-block;margin-left:50px;"> advance through pitches sequentially. useful for driving the "notesequencer" or "drumsequencer" modules.<br/><br/><b>interval</b>: rate to advance<br/><b>random</b>: output random pitches within the range, rather than sequential<br/><b>sync</b>: if the output pitch should be synchronized to the global transport<br/><b>start</b>: pitch at the start of the sequence<br/><b>length</b>: length of the sequence<br/><b>div</b>: measure division, when using "div" as the interval<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=notecreator></a></br> <b>notecreator</b></br> <img src="screenshots/notecreator.png"> </br> <span style="display:inline-block;margin-left:50px;"> create a one-off note<br/><br/><b>duration</b>: note length when "trigger" button is used<br/><b>on</b>: turn on to start note, turn off to end note<br/><b>trigger</b>: press to trigger note for specified duration<br/><b>velocity</b>: note velocity<br/><b>pitch</b>: output note pitch<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=notelooper></a></br> <b>notelooper</b></br> <img src="screenshots/notelooper.png"> </br> <span style="display:inline-block;margin-left:50px;"> note loop recorder with overdubbing and replacement functionality<br/><br/><b>canvas</b>: canvas of recorded notes<br/><b>load*</b>: restore pattern<br/><b>clear</b>: clear pattern<br/><b>del/mute</b>: if "write" is enabled, erase notes as the playhead passes over them. otherwise, just mute them.<br/><b>write</b>: should input should be recorded?<br/><b>store*</b>: save pattern<br/><b>num bars</b>: set loop length in measures<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notesequencer></a></br> <b>notesequencer</b></br> <img src="screenshots/notesequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> looping sequence of notes at an interval. pair with a "pulser" module for more interesting step control. hold "shift" to adjust step length.<br/><br/><b>len*</b>: length for this column<br/><b>random</b>: randomize pitch, length, and velocity of all steps.<br/><b>y offset</b>: y offset of attached grid controller<br/><b>pitch</b>: randomize pitches in the sequence. hold shift to constrain the randomization to only pick roots and fifths.<br/><b>rand vel density</b>: when clicking the random velocity button, what are the chances that a step should have a note?<br/><b>x offset</b>: x offset of attached grid controller<br/><b>rand pitch chance</b>: when clicking the random pitch button, what is the chance that a step gets changed?<br/><b>rand vel chance</b>: when clicking the random velocity button, what is the chance that a step gets changed?<br/><b>tone*</b>: pitch for this column<br/><b>rand len range</b>: when clicking the random length button, how much will the length change?<br/><b>rand len chance</b>: when clicking the random length button, what is the chance that a step gets changed?<br/><b>vel</b>: randomize the velocity of each step's note.<br/><b><</b>: shift the sequence to the left<br/><b>></b>: shift the sequence to the right<br/><b>vel*</b>: velocity for this column<br/><b>len</b>: randomize the length of each step's note.<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><b>loop reset</b>: when sequence loops, reset to here instead. send a "downbeat"-style message from a pulser to restart the sequence from the first step.<br/><b>octave</b>: octave of the bottom pitch of this sequence<br/><b>notemode</b>: which set of pitches should the rows represent?<br/><b>clear</b>: clear all steps<br/><b>interval</b>: note length<br/><b>rand pitch variety</b>: how many different random pitches should we generate?<br/><b>length</b>: length that the sequence below should play. the overall grid length can be changed by adjusting "gridsteps" in the triangle menu.<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notesinger></a></br> <b>notesinger</b></br> <img src="screenshots/notesinger.png"> </br> <span style="display:inline-block;margin-left:50px;"> output a note based on a detected pitch<br/><br/><b>oct</b>: octave to adjust output pitch by<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=playsequencer></a></br> <b>playsequencer</b></br> <img src="screenshots/playsequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> drum sequencer that allows you to punch in to record and overdub steps, inspired by the pulsar-23 drum machine<br/><br/><b>load*</b>: load the sequence stored in this slot<br/><b>link columns</b>: if the mute/delete control should be shared across the entire column<br/><b>interval</b>: the step size<br/><b>measures</b>: the loop length<br/><b>write</b>: if the current input should be written to the sequence. this will also delete steps if mute/delete is enabled for this row<br/><b>note repeat</b>: if held notes should repeat every step<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><b>mute/delete*</b>: if write is disabled, mute this row. if write is enabled, clear the steps as the playhead passes them<br/><b>store*</b>: store the current sequence to this slot<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=polyrhythms></a></br> <b>polyrhythms</b></br> <img src="screenshots/polyrhythms.png"> </br> <span style="display:inline-block;margin-left:50px;"> looping sequence with lines on different divisions<br/><br/><b>length*</b>: number of steps for this line<br/><b>note*</b>: pitch to use for this line<br/></br></br></br></br> </span> <a name=randomnote></a></br> <b>randomnote</b></br> <img src="screenshots/randomnote.png"> </br> <span style="display:inline-block;margin-left:50px;"> play a note at a given interval with a random chance<br/><br/><b>probability</b>: the chance that a note will play each interval<br/><b>skip</b>: after a note plays, don't play a note the next n-1 times that it would have played<br/><b>interval</b>: the note length<br/><b>offset</b>: the amount of time to offset playback within the interval<br/><b>pitch</b>: the pitch to use<br/><b>velocity</b>: the velocity to use<br/></br></br></br></br> </span> <a name=slidersequencer></a></br> <b>slidersequencer</b></br> <img src="screenshots/slidersequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> trigger notes along a continuous timeline<br/><br/><b>division</b>: rate to progress<br/><b>note*</b>: pitch for this element<br/><b>playing*</b>: is this element playing?<br/><b>vel*</b>: velocity of this element<br/><b>time*</b>: time to trigger this element<br/></br></br></br></br> </span> <h2>note effects</h2> <a name=arpeggiator></a></br> <b>arpeggiator</b></br> <img src="screenshots/arpeggiator.png"> </br> <span style="display:inline-block;margin-left:50px;"> arpeggiates held notes. there are several vestigial features in this module that should be cleaned up.<br/><br/><b>step</b>: direction and distance to step through arpeggiation. a value of zero is "pingpong".<br/><b>interval</b>: arpeggiation rate<br/><b>octaves</b>: how many octaves to step through<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=capo></a></br> <b>capo</b></br> <img src="screenshots/capo.png"> </br> <span style="display:inline-block;margin-left:50px;"> shifts incoming notes by semitones<br/><br/><b>capo</b>: number of semitones to shift<br/><b>retrigger</b>: immediately replay current notes when changing the capo amount<br/><b>diatonic</b>: should we keep transposed notes in the scale?<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=chorddisplayer></a></br> <b>chorddisplayer</b></br> <img src="screenshots/chorddisplayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> display which chord is playing, in the context of the current scale<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=chorder></a></br> <b>chorder</b></br> <img src="screenshots/chorder.png"> </br> <span style="display:inline-block;margin-left:50px;"> takes an incoming pitch and plays additional notes to form chords<br/><br/><b>inversion</b>: inversion presets<br/><b>chord</b>: chord presets<br/><b>diatonic</b>: should the grid be chromatic, or locked to the scale only?<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=chordholder></a></br> <b>chordholder</b></br> <img src="screenshots/chordholder.png"> </br> <span style="display:inline-block;margin-left:50px;"> keeps any notes pressed at the same time sustaining, until new notes are pressed<br/><br/><b>pulse to play</b>: when enabled, input notes aren't played immediately, but instead wait for an input pulse before playing<br/><b>stop</b>: stop notes from playing<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=gridnotedisplayer></a></br> <b>gridnotedisplayer</b></br> <img src="screenshots/gridnotedisplayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> use with a gridkeyboard to display currently playing notes, to visualize chords, arpeggiation, etc.<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=midicc></a></br> <b>midicc</b></br> <img src="screenshots/midicc.png"> </br> <span style="display:inline-block;margin-left:50px;"> outputs midi control change messages to route to a "midioutput" module<br/><br/><b>control</b>: CC control number<br/><b>value</b>: outputs a CC value when this changes<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=midioutput></a></br> <b>midioutput</b></br> <img src="screenshots/midioutput.png"> </br> <span style="display:inline-block;margin-left:50px;"> send midi to an external destination, such as hardware or other software<br/><br/><b>controller</b>: where to send midi to<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=modulationvizualizer></a></br> <b>modulationvizualizer</b></br> <img src="screenshots/modulationvizualizer.png"> </br> <span style="display:inline-block;margin-left:50px;"> display MPE modulation values for notes<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=modwheel></a></br> <b>modwheel</b></br> <img src="screenshots/modwheel.png"> </br> <span style="display:inline-block;margin-left:50px;"> adds an expression value to a note<br/><br/><b>modwheel</b>: expression level<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=modwheeltopressure></a></br> <b>modwheeltopressure</b></br> <img src="screenshots/modwheeltopressure.png"> </br> <span style="display:inline-block;margin-left:50px;"> swaps expression input to midi pressure in the output<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=modwheeltovibrato></a></br> <b>modwheeltovibrato</b></br> <img src="screenshots/modwheeltovibrato.png"> </br> <span style="display:inline-block;margin-left:50px;"> convert note mod wheel input rhythmic pitch bend<br/><br/><b>vibrato</b>: amount of pitch bend<br/><b>vibinterval</b>: rate of vibrato<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=mpesmoother></a></br> <b>mpesmoother</b></br> <img src="screenshots/mpesmoother.png"> </br> <span style="display:inline-block;margin-left:50px;"> smooth out MPE parameters<br/><br/><b>modwheel</b>: amount to smooth incoming modwheel<br/><b>pressure</b>: amount to smooth incoming pressure<br/><b>pitch</b>: amount to smooth incoming pitchbend<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=mpetweaker></a></br> <b>mpetweaker</b></br> <img src="screenshots/mpetweaker.png"> </br> <span style="display:inline-block;margin-left:50px;"> adjust incoming MPE modulation values<br/><br/><b>pressure mult</b>: amount to multiply incoming pressure<br/><b>modwheel offset</b>: amount to offset incoming modwheel<br/><b>pitchbend mult</b>: amount to multiply incoming pitchbend<br/><b>pitchbend offset</b>: amount to offset incoming pitchbend<br/><b>modwheel mult</b>: amount to multiply incoming modwheel<br/><b>pressure offset</b>: amount to offset incoming pressure<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notechance></a></br> <b>notechance</b></br> <img src="screenshots/notechance.png"> </br> <span style="display:inline-block;margin-left:50px;"> randomly allow notes through<br/><br/><b>*</b>: generate a new random seed<br/><b>beat length</b>: restart the deterministic random sequence at this interval<br/><b>deterministic</b>: allow for randomness to be repeated over an interval<br/><b>chance</b>: probability that a note is allowed<br/><b>seed</b>: number that determines the random sequence<br/><b><</b>: go to next seed<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notedelayer></a></br> <b>notedelayer</b></br> <img src="screenshots/notedelayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> delay input notes by a specified amount<br/><br/><b>delay</b>: amount of time to delay, in measures<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notedisplayer></a></br> <b>notedisplayer</b></br> <img src="screenshots/notedisplayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> show input note info<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noteduration></a></br> <b>noteduration</b></br> <img src="screenshots/noteduration.png"> </br> <span style="display:inline-block;margin-left:50px;"> sets the length a note will play, ignoring the note-off message<br/><br/><b>duration</b>: length of the note in measures<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noteecho></a></br> <b>noteecho</b></br> <img src="screenshots/noteecho.png"> </br> <span style="display:inline-block;margin-left:50px;"> output incoming notes at specified delays<br/><br/><b>delay *</b>: amount of time to delay this output, in measures<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noteexpression></a></br> <b>noteexpression</b></br> <img src="screenshots/noteexpression.png"> </br> <span style="display:inline-block;margin-left:50px;"> control where notes are routed based upon evaluated expressions. the variable "p" represents pitch, and "v" represents velocity<br/><br/><b>expression*</b>: expression to evaluate for this cable. example expression to route notes with pitch greater than 80 and velocity less than 60: "p > 80 && v < 60"<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notefilter></a></br> <b>notefilter</b></br> <img src="screenshots/notefilter.png"> </br> <span style="display:inline-block;margin-left:50px;"> only allow a certain pitches through<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noteflusher></a></br> <b>noteflusher</b></br> <img src="screenshots/noteflusher.png"> </br> <span style="display:inline-block;margin-left:50px;"> send a note-off for all notes<br/><br/><b>flush</b>: click to flush notes<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notegate></a></br> <b>notegate</b></br> <img src="screenshots/notegate.png"> </br> <span style="display:inline-block;margin-left:50px;"> allow or disallow notes to pass through<br/><br/><b>open</b>: if notes are allowed to pass<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notehocket></a></br> <b>notehocket</b></br> <img src="screenshots/notehocket.png"> </br> <span style="display:inline-block;margin-left:50px;"> sends notes to random destinations<br/><br/><b>weight *</b>: chance that note goes to this destination<br/><b>*</b>: generate a new random seed<br/><b>seed</b>: number that determines the random sequence<br/><b><</b>: go to next seed<br/><b>beat length</b>: restart the deterministic random sequence at this interval<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notehumanizer></a></br> <b>notehumanizer</b></br> <img src="screenshots/notehumanizer.png"> </br> <span style="display:inline-block;margin-left:50px;"> add randomness to timing and velocity<br/><br/><b>velocity</b>: amount of velocity randomness<br/><b>time</b>: amount of timing randomness, in milliseconds.<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notelatch></a></br> <b>notelatch</b></br> <img src="screenshots/notelatch.png"> </br> <span style="display:inline-block;margin-left:50px;"> use note on messages to toggle notes on and off<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noteoctaver></a></br> <b>noteoctaver</b></br> <img src="screenshots/noteoctaver.png"> </br> <span style="display:inline-block;margin-left:50px;"> transpose a note by octaves<br/><br/><b>retrigger</b>: immediately replay current notes when changing the transpose amount<br/><b>octave</b>: number of octaves to raise or lower<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notepanalternator></a></br> <b>notepanalternator</b></br> <img src="screenshots/notepanalternator.png"> </br> <span style="display:inline-block;margin-left:50px;"> sets a note's pan, alternating between two values, for the internal synths that support panned notes<br/><br/><b>two</b>: pan position, .5 is centered<br/><b>one</b>: pan position, .5 is centered<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notepanner></a></br> <b>notepanner</b></br> <img src="screenshots/notepanner.png"> </br> <span style="display:inline-block;margin-left:50px;"> sets a note's pan, for the internal synths that support panned notes<br/><br/><b>pan</b>: pan position, .5 is centered<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notepanrandom></a></br> <b>notepanrandom</b></br> <img src="screenshots/notepanrandom.png"> </br> <span style="display:inline-block;margin-left:50px;"> sets a note's pan to random values, for the internal synths that support panned notes<br/><br/><b>spread</b>: amount of randomness<br/><b>center</b>: center pan position<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noterangefilter></a></br> <b>noterangefilter</b></br> <img src="screenshots/noterangefilter.png"> </br> <span style="display:inline-block;margin-left:50px;"> only allows notes through within a certain pitch range<br/><br/><b>wrap</b>: instead of rejecting notes outside of this range, should we wrap them to the range instead?<br/><b>max</b>: maximum pitch allowed<br/><b>min</b>: minimum pitch allowed<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noteratchet></a></br> <b>noteratchet</b></br> <img src="screenshots/noteratchet.png"> </br> <span style="display:inline-block;margin-left:50px;"> rapidly repeat an input note over a duration<br/><br/><b>duration</b>: total length of time repeats should last<br/><b>skip first</b>: don't replay input note. this allows you to more easily separate the initial note from the ratcheted notes.<br/><b>subdivision</b>: length of each repeat<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=noterouter></a></br> <b>noterouter</b></br> <img src="screenshots/noterouter.png"> </br> <span style="display:inline-block;margin-left:50px;"> allows you to control where notes are routed to using a UI control. to add destinations to the list, patch them as a target<br/><br/><b>route</b>: the noterouter's destination module<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notesorter></a></br> <b>notesorter</b></br> <img src="screenshots/notesorter.png"> </br> <span style="display:inline-block;margin-left:50px;"> separate notes by pitch. any unmapped pitches go through the standard outlet.<br/><br/><b>pitch *</b>: pitch to use for this outlet<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notestepper></a></br> <b>notestepper</b></br> <img src="screenshots/notestepper.png"> </br> <span style="display:inline-block;margin-left:50px;"> output notes through a round robin of patch cables, to create sequential variety<br/><br/><b>reset</b>: reset to the start<br/><b>length</b>: length of the sequence<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notestream></a></br> <b>notestream</b></br> <img src="screenshots/notestream.png"> </br> <span style="display:inline-block;margin-left:50px;"> view a stream of notes as they're played<br/><br/><b>reset</b>: reset the pitch range<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notestrummer></a></br> <b>notestrummer</b></br> <img src="screenshots/notestrummer.png"> </br> <span style="display:inline-block;margin-left:50px;"> send a chord into this, and move a slider to strum each note of the chord<br/><br/><b>strum</b>: move the slider past each note to strum it<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notetable></a></br> <b>notetable</b></br> <img src="screenshots/notetable.png"> </br> <span style="display:inline-block;margin-left:50px;"> map a pitch (starting from zero) to a scale pitch<br/><br/><b>x offset</b>: x offset of attached grid controller<br/><b>rand pitch chance</b>: when clicking the random pitch button, what is the chance that a step gets changed?<br/><b>clear</b>: clear grid<br/><b>y offset</b>: y offset of attached grid controller<br/><b>tone*</b>: pitch for this column<br/><b>rand pitch range</b>: when clicking the random pitch button, how far will the pitch change?<br/><b>length</b>: the number of pitches<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><b>octave</b>: octave of the bottom pitch of this sequence<br/><b>random pitch</b>: randomize pitches in the sequence. hold shift to constrain the randomization to only pick roots and fifths.<br/><b>notemode</b>: which set of pitches should the rows represent?<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notewrap></a></br> <b>notewrap</b></br> <img src="screenshots/notewrap.png"> </br> <span style="display:inline-block;margin-left:50px;"> wrap an input pitch to stay within a desired range<br/><br/><b>range</b>: number of semitones before wrapping back down to min pitch<br/><b>min</b>: bottom of pitch range<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pitchbender></a></br> <b>pitchbender</b></br> <img src="screenshots/pitchbender.png"> </br> <span style="display:inline-block;margin-left:50px;"> add pitch bend to notes<br/><br/><b>bend</b>: bend amount, in semitones<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pitchdive></a></br> <b>pitchdive</b></br> <img src="screenshots/pitchdive.png"> </br> <span style="display:inline-block;margin-left:50px;"> use pitchbend to settle into an input pitch from a starting offset<br/><br/><b>start</b>: semitone offset to start from<br/><b>time</b>: time in milliseconds to ramp from pitch offset into input pitch<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pitchpanner></a></br> <b>pitchpanner</b></br> <img src="screenshots/pitchpanner.png"> </br> <span style="display:inline-block;margin-left:50px;"> add pan modulation to notes based upon input pitch, so low pitches are panned in one direction and high pitches are panned in another<br/><br/><b>right</b>: pitch that represents full right pan<br/><b>left</b>: pitch that represents full left pan<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pitchremap></a></br> <b>pitchremap</b></br> <img src="screenshots/pitchremap.png"> </br> <span style="display:inline-block;margin-left:50px;"> remap input pitches to different output pitches<br/><br/><b>to*</b>: desired pitch<br/><b>from*</b>: pitch to change<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pitchsetter></a></br> <b>pitchsetter</b></br> <img src="screenshots/pitchsetter.png"> </br> <span style="display:inline-block;margin-left:50px;"> set an incoming note to use a specified pitch<br/><br/><b>pitch</b>: the pitch to use<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=portamento></a></br> <b>portamento</b></br> <img src="screenshots/portamento.png"> </br> <span style="display:inline-block;margin-left:50px;"> only allows one note to play at a time, and uses pitch bend to glide between notes<br/><br/><b>mode</b>: always: always glide to new notes retrigger held: bend to notes if the prior note is held, and retrigger bend held: bend to notes if the prior note is held, without retriggering<br/><b>glide</b>: time to glide, in milliseconds<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pressure></a></br> <b>pressure</b></br> <img src="screenshots/pressure.png"> </br> <span style="display:inline-block;margin-left:50px;"> add pressure modulation to notes<br/><br/><b>pressure</b>: pressure amount<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pressuretomodwheel></a></br> <b>pressuretomodwheel</b></br> <img src="screenshots/pressuretomodwheel.png"> </br> <span style="display:inline-block;margin-left:50px;"> takes midi pressure modulation input and changes it to modwheel modulation<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pressuretovibrato></a></br> <b>pressuretovibrato</b></br> <img src="screenshots/pressuretovibrato.png"> </br> <span style="display:inline-block;margin-left:50px;"> takes midi pressure modulation input and changes it to vibrato, using pitch bend<br/><br/><b>vibrato</b>: amount of vibrato<br/><b>vibinterval</b>: vibrato speed<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=previousnote></a></br> <b>previousnote</b></br> <img src="screenshots/previousnote.png"> </br> <span style="display:inline-block;margin-left:50px;"> when receiving a note on, output the prior note on that we received<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=quantizer></a></br> <b>quantizer</b></br> <img src="screenshots/quantizer.png"> </br> <span style="display:inline-block;margin-left:50px;"> delay inputs until the next quantization interval<br/><br/><b>quantize</b>: the quantization interval<br/><b>repeat</b>: when holding a note, should we repeat it every interval?<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=scaledegree></a></br> <b>scaledegree</b></br> <img src="screenshots/scaledegree.png"> </br> <span style="display:inline-block;margin-left:50px;"> transpose input based on current scale<br/><br/><b>retrigger</b>: immediately replay current notes when changing the transpose amount<br/><b>diatonic</b>: should we keep transposed notes in the scale?<br/><b>degree</b>: amount to transpose<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=scaledetect></a></br> <b>scaledetect</b></br> <img src="screenshots/scaledetect.png"> </br> <span style="display:inline-block;margin-left:50px;"> detect which scales fit a collection of entered notes. the last played pitch is used as the root.<br/><br/><b>matches</b>: matching scales for this root<br/><b>reset</b>: reset the input collection of notes<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=sustainpedal></a></br> <b>sustainpedal</b></br> <img src="screenshots/sustainpedal.png"> </br> <span style="display:inline-block;margin-left:50px;"> keeps input notes sustaining<br/><br/><b>sustain</b>: should we hold the input notes?<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=transposefrom></a></br> <b>transposefrom</b></br> <img src="screenshots/transposefrom.png"> </br> <span style="display:inline-block;margin-left:50px;"> transpose input from a specified root to the root of the current scale. the primary usage of this would be to allow you to play a keyboard in C, but it gets transposed to the current scale.<br/><br/><b>root</b>: root to transpose from<br/><b>retrigger</b>: immediately replay current notes when changing the transpose root or the scale<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=unstablemodwheel></a></br> <b>unstablemodwheel</b></br> <img src="screenshots/unstablemodwheel.png"> </br> <span style="display:inline-block;margin-left:50px;"> mutate MPE slide with perlin noise<br/><br/><b>amount</b>: amount of mutation<br/><b>noise</b>: fast-later mutation rate<br/><b>warble</b>: slow-layer mutation rate<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=unstablepitch></a></br> <b>unstablepitch</b></br> <img src="screenshots/unstablepitch.png"> </br> <span style="display:inline-block;margin-left:50px;"> mutate MPE pitchbend with perlin noise<br/><br/><b>amount</b>: amount of mutation<br/><b>noise</b>: fast-later mutation rate<br/><b>warble</b>: slow-layer mutation rate<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=unstablepressure></a></br> <b>unstablepressure</b></br> <img src="screenshots/unstablepressure.png"> </br> <span style="display:inline-block;margin-left:50px;"> mutate MPE pressure with perlin noise<br/><br/><b>amount</b>: amount of mutation<br/><b>noise</b>: fast-later mutation rate<br/><b>warble</b>: slow-layer mutation rate<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=velocitycurve></a></br> <b>velocitycurve</b></br> <img src="screenshots/velocitycurve.png"> </br> <span style="display:inline-block;margin-left:50px;"> adjust velocity based upon a curve mapping<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=velocityscaler></a></br> <b>velocityscaler</b></br> <img src="screenshots/velocityscaler.png"> </br> <span style="display:inline-block;margin-left:50px;"> scale a note's velocity to be higher or lower<br/><br/><b>scale</b>: amount to multiply velocity by<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=velocitysetter></a></br> <b>velocitysetter</b></br> <img src="screenshots/velocitysetter.png"> </br> <span style="display:inline-block;margin-left:50px;"> set a note's velocity to this value<br/><br/><b>rand</b>: randomness to reduce output velocity by<br/><b>vel</b>: velocity to use<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=velocitystepsequencer></a></br> <b>velocitystepsequencer</b></br> <img src="screenshots/velocitystepsequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> adjusts the velocity of incoming notes based upon a sequence<br/><br/><b>downbeat</b>: should we reset the sequence every downbeat?<br/><b>interval</b>: speed to advance sequence<br/><b>vel*</b>: velocity for this step<br/><b>len</b>: length of sequence<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=velocitytochance></a></br> <b>velocitytochance</b></br> <img src="screenshots/velocitytochance.png"> </br> <span style="display:inline-block;margin-left:50px;"> use a note's velocity to determine the chance that the note plays<br/><br/><b>*</b>: generate a new random seed<br/><b>seed</b>: number that determines the random sequence<br/><b><</b>: go to next seed<br/><b>beat length</b>: restart the deterministic random sequence at this interval<br/><b>full velocity</b>: set velocity to full for notes that pass through<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=vibrato></a></br> <b>vibrato</b></br> <img src="screenshots/vibrato.png"> </br> <span style="display:inline-block;margin-left:50px;"> add rhythmic oscillating pitch bend to notes<br/><br/><b>vibrato</b>: amount of pitch bend to add<br/><b>vibinterval</b>: speed of pitch bend oscillation<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=volcabeatscontrol></a></br> <b>volcabeatscontrol</b></br> <img src="screenshots/volcabeatscontrol.png"> </br> <span style="display:inline-block;margin-left:50px;"> outputs MIDI data to control various aspects of the KORG volca beats drum machine<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=whitekeys></a></br> <b>whitekeys</b></br> <img src="screenshots/whitekeys.png"> </br> <span style="display:inline-block;margin-left:50px;"> remap the white keys that correspond to the C major scale to instead play the current global scale<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <h2>synths</h2> <a name=beats></a></br> <b>beats</b></br> <img src="screenshots/beats.png"> </br> <span style="display:inline-block;margin-left:50px;"> multi-loop player, for mixing sample layers together<br/><br/><b>double*</b>: enable this to play at double speed<br/><b>delete *</b>: remove the current sample from the list<br/><b>filter*</b>: layer filter. negative values bring in a low pass, positive values bring in a high pass.<br/><b>selector*</b>: which sample should we play in this slot? drag samples onto here to add them to this slot.<br/><b>pan*</b>: layer panorama<br/><b>volume*</b>: layer volume<br/><b>bars*</b>: how many measures long are the samples in this slot?<br/></br></br></br></br> </span> <a name=drumplayer></a></br> <b>drumplayer</b></br> <img src="screenshots/drumplayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> sample player intended for drum playback<br/><br/><b>shuffle</b>: random is samples, speeds, and pans<br/><b>hitcategory*</b>: folder to choose from, when clicking the "random" button. these folders are found in the data/drums/hits/ directory<br/><b>speed rnd</b>: global sample speed randomization amount<br/><b>test *</b>: play this sample<br/><b>quantize</b>: quantize input to this interval<br/><b>start *</b>: start offset percentage of sample<br/><b>speed</b>: global sample speed multiplier<br/><b>envelopedisplay *D</b>: envelope decay<br/><b>aud</b>: scroll to audition samples in the current pad's head category, or a directory last dropped onto a pad<br/><b>envelopedisplay *A</b>: envelope attack<br/><b>vol *</b>: volume of sample <br/><b>vol</b>: the output volume<br/><b>view ms *</b>: envelope view length in milliseconds<br/><b>envelopedisplay *R</b>: envelope release<br/><b>envelopedisplay *S</b>: envelope sustain<br/><b>random *</b>: choose a random sample from the selected hitcategory<br/><b>repeat</b>: if quantizing, should held notes repeat at that interval?<br/><b>widen *</b>: stereo delay of sample to create width<br/><b>grab *</b>: grab this sample<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><b>next *</b>: choose the next sample from the selected hitcategory<br/><b>envelope *</b>: should we apply a volume envelope to the sample?<br/><b>linkid *</b>: if linkid is not -1, silence any other sample with a matching linkid (useful for linking open and closed hats)<br/><b>edit</b>: show pads for editing<br/><b>mono</b>: force output to mono<br/><b>pan *</b>: stereo pan position of sample<br/><b>speed *</b>: speed of sample<br/><b>single out *</b>: should the sample have its own individual output?<br/><b>prev *</b>: choose the previous sample from the selected hitcategory<br/><b>full vel</b>: always play drum hits at full velocity<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=drumsynth></a></br> <b>drumsynth</b></br> <img src="screenshots/drumsynth.png"> </br> <span style="display:inline-block;margin-left:50px;"> oscillator+noise drum synth<br/><br/><b>vol</b>: the output volume<br/><b>type*</b>: oscillator type<br/><b>cutoffmax*</b>: filter start cutoff frequency<br/><b>q*</b>: filter resonance<br/><b>freqmin*</b>: oscillator end frequency<br/><b>freqmax*</b>: oscillator start frequency<br/><b>oversampling</b>: oversampling amount. increases sound quality, but also increases cpu usage.<br/><b>vol*</b>: oscillator volume<br/><b>edit</b>: display parameters for each hit<br/><b>cutoffmin*</b>: filter end cutoff frequency<br/><b>noise*</b>: noise volume<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=fmsynth></a></br> <b>fmsynth</b></br> <img src="screenshots/fmsynth.png"> </br> <span style="display:inline-block;margin-left:50px;"> polyphonic fm synthesis<br/><br/><b>harmratio</b>: harmonic ratio of first-order modulator to input pitch<br/><b>vol</b>: the output volume<br/><b>tweak</b>: multiplier to harmonic ratio for first-order modulator<br/><b>tweak2</b>: multiplier to harmonic ratio for second-order modulator<br/><b>mod2</b>: amount to modulate second-order modulator<br/><b>mod</b>: amount to modulate first-order modulator<br/><b>harmratio2</b>: harmonic ratio of second-order modulator to input pitch<br/><b>phase1</b>: phase offset for first-order modulator<br/><b>phase0</b>: phase offset for base oscillator<br/><b>phase2</b>: phase offset for second-order modulator<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=karplusstrong></a></br> <b>karplusstrong</b></br> <img src="screenshots/karplusstrong.png"> </br> <span style="display:inline-block;margin-left:50px;"> polyphonic plucked string physical modeling synth<br/><br/><b>x freq</b>: frequency of excitation audio<br/><b>vel2vol</b>: how much velocity should affect voice volume<br/><b>feedback</b>: amount of feedback for resonance<br/><b>vol</b>: output volume<br/><b>invert</b>: should the feedback invert?<br/><b>x att</b>: fade in time for excitation audio<br/><b>filter</b>: amount to filter resonance<br/><b>pitchtone</b>: adjust how pitch influences filter amount. a value of zero gives even filtering across the entire pitch range, higher values filter high pitches less, low values filter low pitches less.<br/><b>x dec</b>: fade out time for excitation audio<br/><b>source type</b>: audio to use for excitation<br/><b>lite cpu</b>: only recalculate some parameters once per buffer, to reduce CPU load. can make pitch bends and rapid modulation sound worse in some scenarios.<br/><b>vel2env</b>: how much velocity should affect excitation attack time<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=metronome></a></br> <b>metronome</b></br> <img src="screenshots/metronome.png"> </br> <span style="display:inline-block;margin-left:50px;"> beeps to the beat<br/><br/><b>vol</b>: metronome volume<br/></br></br></br></br> </span> <a name=oscillator></a></br> <b>oscillator</b></br> <img src="screenshots/oscillator.png"> </br> <span style="display:inline-block;margin-left:50px;"> polyphonic enveloped oscillator. modulations (with MPE support): modwheel closes filter further (if filter is enabled), pressure decreases detune amount<br/><br/><b>unison</b>: how many oscillators to play for one note<br/><b>envfilterA</b>: filter envelope attack<br/><b>shuffle</b>: stretches and squeezes every other cycle of the waveform<br/><b>envfilterD</b>: filter envelope decay<br/><b>envS</b>: volume envelope sustain<br/><b>envR</b>: volume envelope release<br/><b>sync</b>: turns on "sync" mode, to reset the phase at syncf's frequency<br/><b>soften</b>: soften edges of square and saw waveforms<br/><b>envfilterS</b>: filter envelope sustain<br/><b>envfilterR</b>: filter envelope release<br/><b>osc</b>: oscillator type<br/><b>envA</b>: volume envelope attack<br/><b>envD</b>: volume envelope decay<br/><b>vel2vol</b>: how much should the input velocity affect the output volume?<br/><b>pw</b>: pulse width (or shape for non-square waves)<br/><b>width</b>: controls how voices are panned with unison is greater than 1<br/><b>vol</b>: this oscillator's volume<br/><b>syncf</b>: frequency to reset the phase, when "sync" is enabled<br/><b>lite cpu</b>: only recalculate some parameters once per buffer, to reduce CPU load. can make pitch bends and rapid modulation sound worse in some scenarios.<br/><b>fmax</b>: frequency cutoff of lowpass filter at the max of the envelope. set this slider to the max to disable the filter<br/><b>phase</b>: phase offset of oscillator, and phase offset between unison voices. useful to patch into with a very fast modulator, to achieve phase modulation.<br/><b>vel2env</b>: how much should the input velocity affect the speed of the volume and filter envelopes?<br/><b>mult</b>: multiply frequency of incoming pitch<br/><b>adsr len</b>: view length of ADSR controls<br/><b>q</b>: resonance of lowpass filter<br/><b>detune</b>: when unison is 1, detunes oscillator by this amount. when unison is 2, one oscillator is tuned normally and the other is detuned by this amount. when unison is >2, oscillators are randomly detuned within this range.<br/><b>fmin</b>: frequency cutoff of lowpass filter at the min of the envelope<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=samplecanvas></a></br> <b>samplecanvas</b></br> <img src="screenshots/samplecanvas.png"> </br> <span style="display:inline-block;margin-left:50px;"> sample arranging view<br/><br/><b>scrollv</b>: vertical scrollbar<br/><b>canvas</b>: canvas of samples. drag and drop samples onto here. canvas controls: -hold shift and drag a sample to duplicate -hold alt to drag a sample without snapping -hold ctrl while dragging to snap to an interval -hold shift and scroll to zoom -hold alt and grab empty space to move slide the canvas view -hold ctrl and grab empty space to zoom the canvas view<br/><b>interval</b>: grid subdivision interval<br/><b>drag mode</b>: direction that elements can be dragged<br/><b>timeline</b>: control loop points<br/><b>clear</b>: delete all elements<br/><b>measures</b>: length of canvas in measures<br/><b>view rows</b>: number of visible rows<br/><b>scrollh</b>: horizontal scrollbar<br/><b>delete</b>: delete highlighted elements<br/></br></br></br></br> </span> <a name=sampleplayer></a></br> <b>sampleplayer</b></br> <img src="screenshots/sampleplayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> sample playback with triggerable cue points, clip extraction, and youtube search/download functionality. resize this module larger to access additional features. if you have a youtube URL in your clipboard, a button will appear to allow you to download the audio.<br/><br/><b>load</b>: show a file chooser to load a sample<br/><b>trim</b>: discard all audio outside the current zoom range<br/><b>select played</b>: when true, any cue point played via incoming notes will become the current cue<br/><b>cue len</b>: length in seconds of the current cue. a value of zero will play to the end of the sample.<br/><b>append to rec</b>: when recording, append to the previous recording, rather than clearing the sample first<br/><b>cue start</b>: start point in seconds of the current cue<br/><b>play cue</b>: play the current cue<br/><b>threshold</b>: volume threshold to open up the gate for recording<br/><b>speed</b>: current playback speed<br/><b>pause</b>: pause playing and leave playhead where it is<br/><b>cue stop</b>: stop playing this cue if a note-off is received<br/><b>attack</b>: speed at which gate blends open<br/><b>4</b>: auto-slice 4 slices<br/><b>8</b>: auto-slice 8 slices<br/><b>save</b>: save this sample to a file<br/><b>playhovered</b>: play this cue<br/><b>play</b>: start playing from the current playhead<br/><b>click sets cue</b>: when true, clicking on the waveform will set the start position of the current cue<br/><b>stop</b>: stop playing and reset playhead<br/><b>volume</b>: output gain<br/><b>searchresult*</b>: click to download this youtube search result. downloading long videos may take a while.<br/><b>record as clips</b>: when recording, only record when there is enough input to open the gate, and mark up each recorded segment with cue points<br/><b>grabhovered</b>: grab a sample of this cue to drop onto another module<br/><b>cuepoint</b>: sets the current cue to edit<br/><b>yt:</b>: search youtube for this string<br/><b>16</b>: auto-slice 16 slices<br/><b>32</b>: auto-slice 32 slices<br/><b>youtube</b>: download the audio of the youtube URL currently on your clipboard<br/><b>record</b>: record audio input into our sample buffer. clears the current sample.<br/><b>cue speed</b>: playback speed of the current cue<br/><b>release</b>: speed at which gate blends closed<br/><b>show grid</b>: show a quarter note grid (when zoomed in far enough)<br/><b>loop</b>: wrap playhead to beginning when it reaches end<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=sampler></a></br> <b>sampler</b></br> <img src="screenshots/sampler.png"> </br> <span style="display:inline-block;margin-left:50px;"> very basic polyphonic pitched sample player and recorder. send audio in, and use note input to play the recorded audio.<br/><br/><b>envS</b>: volume envelope sustain<br/><b>envR</b>: volume envelope release<br/><b>pitch</b>: should we attempt pitch-correct the audio?<br/><b>vol</b>: output volume<br/><b>thresh</b>: when recording is enabled, exceed this threshold with input audio to begin recording<br/><b>env</b>: volume envelope<br/><b>passthrough</b>: should input audio pass through as we're recording?<br/><b>rec</b>: enable to clear the current recording, and record new audio once the input threshold is reached<br/><b>envA</b>: volume envelope attack<br/><b>envD</b>: volume envelope decay<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=seaofgrain></a></br> <b>seaofgrain</b></br> <img src="screenshots/seaofgrain.png"> </br> <span style="display:inline-block;margin-left:50px;"> granular synth, playable with sliders or MPE input<br/><br/><b>load</b>: load a sample file<br/><b>pos r *</b>: randomization of grain start point<br/><b>pos *</b>: position of this voice within the sample<br/><b>speed r *</b>: randomization of grain speed<br/><b>pan *</b>: stereo panorama of grain placement<br/><b>offset</b>: where to start view of the sample<br/><b>speed *</b>: speed of grain playback<br/><b>keyboard num pitches</b>: amount of pitches to assign across the sample<br/><b>volume</b>: output volume<br/><b>len ms *</b>: length of each grain in milliseconds<br/><b>overlap *</b>: number of overlapping grains<br/><b>spacing r*</b>: randomization of time between grains<br/><b>display length</b>: amount of sample to view<br/><b>gain *</b>: volume of this voice<br/><b>keyboard base pitch</b>: midi pitch that represents the start of the sample<br/><b>octaves *</b>: should we add octaves and fifths?<br/><b>width *</b>: stereo width of grain placement<br/><b>record</b>: record input as the granular buffer, to use seaofgrain a live granular delay<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=signalgenerator></a></br> <b>signalgenerator</b></br> <img src="screenshots/signalgenerator.png"> </br> <span style="display:inline-block;margin-left:50px;"> basic oscillator signal. send a note into it to set the frequency, and send a pulse to reset the phase.<br/><br/><b>syncf</b>: frequency to reset the phase, when "sync" is enabled<br/><b>shuffle</b>: stretches and squeezes every other cycle of the waveform<br/><b>pw</b>: pulse width (or shape for non-square waves)<br/><b>slider</b>: slider to interpolate between last two input pitches<br/><b>vol</b>: output volume<br/><b>ramp</b>: amount of time to ramp to input frequency<br/><b>sync</b>: turns on "sync" mode, to reset the phase at syncf's frequency<br/><b>freq mode</b>: what mode should we use for input notes? "instant" changes to the input note's frequency instantly, "ramp" ramps to the frequency over time, and "slider" allows you to use a slider to interpolate between the last two input notes<br/><b>soften</b>: soften edges of square and saw waveforms<br/><b>detune</b>: amount to detune from specified frequency<br/><b>phase</b>: phase offset<br/><b>freq</b>: signal frequency<br/><b>osc</b>: oscillator type<br/><b>mult</b>: multiplier for frequency<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <h2>audio effects</h2> <a name=audiometer></a></br> <b>audiometer</b></br> <img src="screenshots/audiometer.png"> </br> <span style="display:inline-block;margin-left:50px;"> sets a slider to an audio level's volume. useful to map a midi display value to.<br/><br/><b>level</b>: the input audio level. hook this up to an LED-display midi control to see the value displayed on your controller.<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=audiorouter></a></br> <b>audiorouter</b></br> <img src="screenshots/audiorouter.png"> </br> <span style="display:inline-block;margin-left:50px;"> selector for switching where audio is routed to. connect to targets to add them to the list.<br/><br/><b>route</b>: audio destination<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=buffershuffler></a></br> <b>buffershuffler</b></br> <img src="screenshots/buffershuffler.png"> </br> <span style="display:inline-block;margin-left:50px;"> use notes to play back slices of a constantly-recording live input buffer. input notes trigger slices, with the pitch mapping to slice index. you can also click with a mouse to trigger slices.<br/><br/><b>freeze input</b>: retain the current buffer, without writing in new input<br/><b>playback style</b>: how to play clicked slices. or, with input notes, velocity range determines playback style.<br/><b>interval</b>: slice size<br/><b>num bars</b>: number of bars to capture<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=dcoffset></a></br> <b>dcoffset</b></br> <img src="screenshots/dcoffset.png"> </br> <span style="display:inline-block;margin-left:50px;"> add a constant offset to an audio signal<br/><br/><b>offset</b>: amount of offset to add<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=effectchain></a></br> <b>effectchain</b></br> <img src="screenshots/effectchain.png"> </br> <span style="display:inline-block;margin-left:50px;"> container to hold a list of effects, applied in series. the effects can be easily reordered with the < and > buttons, and deleted with the x button. hold shift to expose a x button for all effects.<br/><br/><b>spawn</b>: spawn the currently highlighted effect<br/><b>volume</b>: output gain<br/><b>effect</b>: select which effect to add<br/><b>exit effect</b>: on push2, back effect control out to the main effectchain controls<br/><b>mix*</b>: wet/dry slider for this effect<br/><b>x</b>: delete this effect<br/><b><</b>: move this effect to earlier in the chain<br/><b>></b>: move this effect to later in the chain<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=eq></a></br> <b>eq</b></br> <img src="screenshots/eq.png"> </br> <span style="display:inline-block;margin-left:50px;"> multi-band equalizer, to adjust output levels at frequency ranges<br/><br/><b>q*</b>: resonance for this band<br/><b>f*</b>: frequency cutoff for this band<br/><b>enabled*</b>: enable this band?<br/><b>g*</b>: gain for this band<br/><b>type*</b>: what type of filter should this band use<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=feedback></a></br> <b>feedback</b></br> <img src="screenshots/feedback.png"> </br> <span style="display:inline-block;margin-left:50px;"> feed delayed audio back into earlier in the signal chain. use the "feedback out" connector for sending the audio back up the chain, and the primary output connector for sending the resulting audio forward. using feedback can often lead to extreme and difficult-to-control results!<br/><br/><b>limit</b>: clip the feedback audio to this range, to avoid issues with feedback blowing out too intensely.<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=fftvocoder></a></br> <b>fftvocoder</b></br> <img src="screenshots/fftvocoder.png"> </br> <span style="display:inline-block;margin-left:50px;"> FFT-based vocoder<br/><br/><b>cut</b>: how many bass partials to remove<br/><b>phase off</b>: how much we should offset the phase of the carrier signal's partials<br/><b>whisper</b>: how much the carrier signal partial's phases should be randomized, which affects how whispery the output sound is<br/><b>dry/wet</b>: how much original input vs vocoded signal to output<br/><b>volume</b>: output gain<br/><b>fric thresh</b>: fricative detection sensitivity, to switch between using the carrier signal and white noise for vocoding<br/><b>carrier</b>: carrier signal gain<br/><b>input</b>: input signal gain<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=freqdelay></a></br> <b>freqdelay</b></br> <img src="screenshots/freqdelay.png"> </br> <span style="display:inline-block;margin-left:50px;"> delay effect with delay length based upon input notes<br/><br/><b>dry/wet</b>: how much of the effect to apply<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=gain></a></br> <b>gain</b></br> <img src="screenshots/gain.png"> </br> <span style="display:inline-block;margin-left:50px;"> adjusts volume of audio signal<br/><br/><b>gain</b>: amount to adjust signal. a value of 1 will cause no change to the signal.<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=input></a></br> <b>input</b></br> <img src="screenshots/input.png"> </br> <span style="display:inline-block;margin-left:50px;"> get audio from input source, like a microphone<br/><br/><b>ch</b>: which channel (or channels, if you want stereo) to use<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=inverter></a></br> <b>inverter</b></br> <img src="screenshots/inverter.png"> </br> <span style="display:inline-block;margin-left:50px;"> multiply a signal by -1. enables some pretty interesting effects when used with sends, to subtract out parts of signals when recombined.<br/><br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=lissajous></a></br> <b>lissajous</b></br> <img src="screenshots/lissajous.png"> </br> <span style="display:inline-block;margin-left:50px;"> draw input audio as a lissajous curve. turn off "autocorrelation" in the module's triangle menu to use stereo channels to show stereo width.<br/><br/><b>scale</b>: visual scale of lissajous image<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=looper></a></br> <b>looper</b></br> <img src="screenshots/looper.png"> </br> <span style="display:inline-block;margin-left:50px;"> loop input audio. use with a "looperrecorder" for full functionality.<br/><br/><b>fourtet</b>: use a textural trick I saw four tet illustrate in a video once: slice the audio into chunks, and for each chunk it at double speed followed by playing it in reverse at double speed. this slider adjusts the mix between the original audio and this "fourtetified" audio.<br/><b>.5x</b>: make loop play at half speed<br/><b>mute</b>: silence this looper<br/><b>passthrough</b>: should we pass incoming audio through to the output? turn off to mute incoming audio.<br/><b>pitch</b>: amount to pitch shift looper output<br/><b>apply</b>: shift the contents of the looper so the current offset is the start of the buffer<br/><b>scr</b>: allow loop to be scratched by adjusting "scrspd"<br/><b>decay</b>: amount to lower volume each loop<br/><b>write</b>: write input audio to loop buffer<br/><b>swap</b>: swap the contents of this looper and with another. click this button on two loopers to swap them.<br/><b>save</b>: save this loop to a wav file<br/><b> m </b>: take the contents of this looper and merge it into another. click this button on the merge source, then on the merge target.<br/><b>extend</b>: make loop twice as long<br/><b>capture</b>: when the next loop begins, record input for the duration of the loop<br/><b>auto</b>: should pitch shift auto-adjust as the transport tempo adjusts?<br/><b>undo</b>: undo last loop commit<br/><b>offset</b>: amount to offset looper's playhead from transport position<br/><b>copy</b>: take the contents of this looper and copy it onto another. click this button on the copy source, then on the copy target.<br/><b>num bars</b>: loop length in measures<br/><b>resample for tempo</b>: this button appears when the current global tempo no longer matches the tempo that the buffer was recorded at. click this to resample the buffer to match the new tempo.<br/><b>volume</b>: output volume<br/><b>b</b>: bake current volume into waveform<br/><b>clear</b>: clear the loop audio<br/><b>2x</b>: make loop play at double speed<br/><b>scrspd</b>: playback speed, used with "scr" is enabled. modulate quickly for a vinyl-like scratching effect.<br/><b>fourtetslices</b>: chunk size to use for "fourtet" effect<br/><b>commit</b>: commit the current looperrecorder buffer to this loop<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=looperrecorder></a></br> <b>looperrecorder</b></br> <img src="screenshots/looperrecorder.png"> </br> <span style="display:inline-block;margin-left:50px;"> command center to manage recording into multiple loopers, and allow retroactive loop capture (i.e., always-on recording)<br/><br/><b>orig speed</b>: reset looper to tempo that loops were recorded at<br/><b>target</b>: looper to commit audio to when using the on-buffer capture buttons to the left<br/><b>2xtempo</b>: double global transport tempo, while keeping connected loopers sounding the same<br/><b>cancel free rec</b>: if "free rec" is enabled, cancel recording without setting the loop length<br/><b>clear</b>: clear the recorded buffer<br/><b>snap to pitch</b>: snap tempo to nearest value that matches a key<br/><b>1</b>: capture the last measure to the currently-targeted looper<br/><b>length</b>: length in measures to use when connected loopers use the "commit" button<br/><b>2</b>: capture the last 2 measures to the currently-targeted looper<br/><b>free rec</b>: enable to start recording a loop with no predetermined length. disable to end recording, adjust global transport to match the loop length, and switch the recorder's mode to "loop"<br/><b>4</b>: capture the last 4 measures to the currently-targeted looper<br/><b>resample</b>: resample all connected loopers to new tempo<br/><b>.5tempo</b>: halve global transport tempo, while keeping connected loopers sounding the same<br/><b>resample & set key</b>: snap tempo to nearest value that matches a key (based upon the current key and the tempo change), resample all connected loopers to that new tempo, and change global scale to the new key<br/><b>8</b>: capture the last 8 measures to the currently-targeted looper<br/><b>auto-advance</b>: automatically advance to the next looper when committing<br/><b>mode</b>: recorder mode: use "record" to record input and allow it to be committed to buffers when you're ready to loop, use "overdub" to record input and play the loop at our specified length, and use "loop" to play the current loop without adding input<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=looperrewriter></a></br> <b>looperrewriter</b></br> <img src="screenshots/looperrewriter.png"> </br> <span style="display:inline-block;margin-left:50px;"> rewrites the contents of a looper with received input, to help you resample your own loops. attach the grey dot to a "looper" module. the ideal way to use this module is to hook the "looper" directly up to a "send", hook the leftmost outlet of the "send" up to your effects processing (like an "effectchain"), hook the effect processing up to this "rewriter", and then also connect the rightmost outlet of the "send" up to this "rewriter"<br/><br/><b>go</b>: rewrite the connected looper, and if that looper is connected to a send, set that send to output only to the right outlet<br/><b>new loop</b>: start recording a dynamic loop length. press "go" when you want to rewrite it to the looper. this will also change bespoke's global tempo to match this new loop, so it's quite powerful and scary! click it again to cancel.<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=multitapdelay></a></br> <b>multitapdelay</b></br> <img src="screenshots/multitapdelay.png"> </br> <span style="display:inline-block;margin-left:50px;"> delay with multiple tap points<br/><br/><b>dry</b>: how much dry signal to allow through<br/><b>pan *</b>: stereo pan for this tap<br/><b>delay *</b>: tap delay time, in milliseconds<br/><b>display length</b>: length of buffer display, in seconds<br/><b>feedback *</b>: how much delayed audio from this tap should feed back in to the input<br/><b>gain *</b>: tap delay amount<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=output></a></br> <b>output</b></br> <img src="screenshots/output.png"> </br> <span style="display:inline-block;margin-left:50px;"> route audio in here to send it to an output channel (your speakers or audio interface)<br/><br/><b>ch</b>: channel (or channels, if you want stereo) to send audio to<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=panner></a></br> <b>panner</b></br> <img src="screenshots/panner.png"> </br> <span style="display:inline-block;margin-left:50px;"> pan audio left and right. also, converts a mono input to a stereo output.<br/><br/><b>widen</b>: delay a channel by this many samples. results in a pan-like effect where the sound seems to come from from a direction.<br/><b>pan</b>: amount to send signal to the left and right channels. a value of 0 is centered.<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=ringmodulator></a></br> <b>ringmodulator</b></br> <img src="screenshots/ringmodulator.png"> </br> <span style="display:inline-block;margin-left:50px;"> modulate a signal's amplitude at a frequency<br/><br/><b>volume</b>: volume output<br/><b>freq</b>: frequency to use. can also be set by patching a note input into this module.<br/><b>dry/wet</b>: how much of the original audio to use vs modulated audio<br/><b>glide</b>: how long an input note should take to glide to the desired frequency<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=samplergrid></a></br> <b>samplergrid</b></br> <img src="screenshots/samplergrid.png"> </br> <span style="display:inline-block;margin-left:50px;"> record input onto pads, and play back the pads. intended to be used with an 64-pad grid controller.<br/><br/><b>vol</b>: the output volume<br/><b>end</b>: sample end<br/><b>edit</b>: enable controls to adjust recorded sample for last pressed grid square<br/><b>passthrough</b>: should the incoming audio pass through to the output?<br/><b>clear</b>: when enabled, clears any pressed grid squares<br/><b>start</b>: sample start<br/><b>duplicate</b>: what enabled, duplicates last pressed sample onto any pressed grid squares<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=send></a></br> <b>send</b></br> <img src="screenshots/send.png"> </br> <span style="display:inline-block;margin-left:50px;"> duplicate a signal and send it to a second destination<br/><br/><b>amount</b>: amount to send out the right-side cable<br/><b>crossfade</b>: when true, output of the left-side cable is reduced as "amount" increases<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=signalclamp></a></br> <b>signalclamp</b></br> <img src="screenshots/signalclamp.png"> </br> <span style="display:inline-block;margin-left:50px;"> clamps an audio signal's value within a range<br/><br/><b>max</b>: maximum output value<br/><b>min</b>: minimum output value<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=spectrum></a></br> <b>spectrum</b></br> <img src="screenshots/spectrum.png"> </br> <span style="display:inline-block;margin-left:50px;"> display audio signal's spectral data<br/><br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=splitter></a></br> <b>splitter</b></br> <img src="screenshots/splitter.png"> </br> <span style="display:inline-block;margin-left:50px;"> splits a stereo signal into two mono signals, or duplicates a mono signal<br/><br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=stutter></a></br> <b>stutter</b></br> <img src="screenshots/stutter.png"> </br> <span style="display:inline-block;margin-left:50px;"> captures and stutters input<br/><br/><b>free length</b>: length in seconds for "free" stutter mode<br/><b>reverse</b>: reversed half note stutter<br/><b>half speed</b>: stutter at half speed, low pitched<br/><b>ramp in</b>: stutter with speed climbing up from zero to one<br/><b>triplets</b>: stutter on a triplet interval<br/><b>32nd</b>: 32nd note stutter<br/><b>64th</b>: 64th note stutter<br/><b>tumble up</b>: accelerating stutter<br/><b>half note</b>: half note stutter<br/><b>tumble down</b>: decelerating stutter<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><b>free</b>: stutter with the settings specified by the following sliders<br/><b>dotted eighth</b>: stutter on a dotted eighth interval<br/><b>free speed</b>: rate for "free" stutter mode<br/><b>double speed</b>: stutter at double speed, high pitched<br/><b>quarter</b>: quarter note stutter<br/><b>ramp out</b>: stutter with speed quickly falling to zero<br/><b>16th</b>: 16th note stutter<br/><b>8th</b>: 8th note stutter<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=vocoder></a></br> <b>vocoder</b></br> <img src="screenshots/vocoder.png"> </br> <span style="display:inline-block;margin-left:50px;"> frequency band-based vocoder. this must be paired with a "vocodercarrier" module. voice should be routed into this module, and a synth should be patched into the vocodercarrier.<br/><br/><b>volume</b>: output gain<br/><b>max band</b>: volume limit for each frequency band<br/><b>bands</b>: how many frequency bands to use<br/><b>spacing</b>: how frequency bands should be spaced<br/><b>f base</b>: frequency for lowest band<br/><b>q</b>: resonance of the bands<br/><b>mix</b>: how much original input vs vocoded signal to output<br/><b>carrier</b>: carrier signal gain<br/><b>f range</b>: frequency range to highest band<br/><b>input</b>: input signal gain<br/><b>ring</b>: how long it should take the bands to "cool down"<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=vocodercarrier></a></br> <b>vocodercarrier</b></br> <img src="screenshots/vocodercarrier.png"> </br> <span style="display:inline-block;margin-left:50px;"> connect to "vocoder" or "fftvocoder" modules. send the synth audio into this module, and the voice audio into the vocoder module.<br/><br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=waveformviewer></a></br> <b>waveformviewer</b></br> <img src="screenshots/waveformviewer.png"> </br> <span style="display:inline-block;margin-left:50px;"> waveform display<br/><br/><b>length</b>: number of samples to capture<br/><b>draw gain</b>: adjust waveform display scale<br/><b>freq</b>: frequency to sync display to. gets automatically set if you patch a note input into this module<br/><br/>accepts: <font color=orange>notes</font> <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=waveshaper></a></br> <b>waveshaper</b></br> <img src="screenshots/waveshaper.png"> </br> <span style="display:inline-block;margin-left:50px;"> waveshaping with expressions<br/><br/><b>a</b>: variable to use in expressions<br/><b>c</b>: variable to use in expressions<br/><b>b</b>: variable to use in expressions<br/><b>e</b>: variable to use in expressions<br/><b>d</b>: variable to use in expressions<br/><b>rescale</b>: rescales input before feeding it into expression<br/><b>y=</b>: waveshaping expression. try something like "x+sin(x*pi*a)". available variables: a,b,c,d,e = the sliders below. t = time. x1,x2,y1,y2 = biquad state storage.<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <h2>modulators</h2> <a name=accum></a></br> <b>accum</b></br> <img src="screenshots/accum.png"> </br> <span style="display:inline-block;margin-left:50px;"> accumulate a value over time<br/><br/><b>velocity</b>: amount to accumulate<br/><b>value</b>: output value<br/></br></br></br></br> </span> <a name=add></a></br> <b>add</b></br> <img src="screenshots/add.png"> </br> <span style="display:inline-block;margin-left:50px;"> outputs the result of value 1 plus value 2. value 1 and value 2 are intended to be patch targets for modulators.<br/><br/><b>value 1</b>: value to sum<br/><b>value 2</b>: value to sum<br/></br></br></br></br> </span> <a name=addcentered></a></br> <b>addcentered</b></br> <img src="screenshots/addcentered.png"> </br> <span style="display:inline-block;margin-left:50px;"> outputs the result of value 1 plus value 2, multiplied by range 2. optimized for using to modulation value 1 by range 2 at a frequency. value 1 or value 2 are intended to be patch targets for modulators.<br/><br/><b>range 2</b>: modulation amount<br/><b>value 1</b>: center value<br/><b>value 2</b>: modulation value<br/></br></br></br></br> </span> <a name=audiotocv></a></br> <b>audiotocv</b></br> <img src="screenshots/audiotocv.png"> </br> <span style="display:inline-block;margin-left:50px;"> use an audio signal to modulate a control. allow for audio-rate modulation, to achieve effects such as FM.<br/><br/><b>max</b>: maximum output value<br/><b>gain</b>: multiply incoming audio<br/><b>min</b>: minimum output value<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=controlsequencer></a></br> <b>controlsequencer</b></br> <img src="screenshots/controlsequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> modulate a control step-wise at an interval<br/><br/><b>random</b>: randomize sequence values<br/><b>length</b>: length of the sequence<br/><b>interval</b>: rate to advance<br/><b>step *</b>: value for this step<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=curve></a></br> <b>curve</b></br> <img src="screenshots/curve.png"> </br> <span style="display:inline-block;margin-left:50px;"> remap an input over its range with a curve. double-click on the curve to add points, right click on points to remove them, drag on lines to bend them.<br/><br/><b>input</b>: input value (intended as a modulation target)<br/></br></br></br></br> </span> <a name=curvelooper></a></br> <b>curvelooper</b></br> <img src="screenshots/curvelooper.png"> </br> <span style="display:inline-block;margin-left:50px;"> modulate a value over time with a looping curve<br/><br/><b>length</b>: length of the loop<br/><b>randomize</b>: create a random curve<br/></br></br></br></br> </span> <a name=envelope></a></br> <b>envelope</b></br> <img src="screenshots/envelope.png"> </br> <span style="display:inline-block;margin-left:50px;"> modulate a value with a triggered envelope<br/><br/><b>has sustain</b>: should this envelope have a sustain stage?<br/><b>adsrD</b>: envelope decay<br/><b>adsrA</b>: envelope attack<br/><b>use velocity</b>: should envelope output be scaled by input velocity?<br/><b>max sustain</b>: what's the maximum length of the sustain, in milliseconds? a value of -1 indicates no maximum<br/><b>sustain stage</b>: which step of the envelope should have the sustain?<br/><b>high</b>: output high value<br/><b>length</b>: length of envelope display<br/><b>low</b>: output low value<br/><b>adsrS</b>: envelope sustain<br/><b>adsrR</b>: envelope release<br/><b>adsr</b>: envelope view<br/><b>advanced</b>: switch to advanced envelope editor (allows for a more complicated envelope than just an ADSR). double-click on an advanced envelope line to add stages, right click on points to remove them, drag on lines to bend them.<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=expression></a></br> <b>expression</b></br> <img src="screenshots/expression.png"> </br> <span style="display:inline-block;margin-left:50px;"> shape modulation with a text-based mathematical expression<br/><br/><b>a</b>: variable to use in expressions<br/><b>c</b>: variable to use in expressions<br/><b>b</b>: variable to use in expressions<br/><b>e</b>: variable to use in expressions<br/><b>d</b>: variable to use in expressions<br/><b>y=</b>: expression to modify input. try something like "x+sin(x*pi*a)". available variables: a,b,c,d,e = the sliders below. t = time.<br/><b>input</b>: input to use as x variable<br/></br></br></br></br> </span> <a name=fubble></a></br> <b>fubble</b></br> <img src="screenshots/fubble.png"> </br> <span style="display:inline-block;margin-left:50px;"> draw on an X/Y pad and replay the drawing to modulate values. based on a concept proposed by olivia jack<br/><br/><b>mutate amount</b>: amount to affect drawing by perlin noise field<br/><b>mutate warp</b>: scale of perlin noise field<br/><b>speed</b>: speed up or slow down playback<br/><b>clear</b>: clear the drawing<br/><b>quantize</b>: should we quantize playback to a specified rhythmic interval?<br/><b>length</b>: the interval to quantize to<br/><b>mutate noise</b>: rate to move through perlin noise field<br/><b>reseed</b>: jump to a different location in the perlin noise field<br/></br></br></br></br> </span> <a name=gravity></a></br> <b>gravity</b></br> <img src="screenshots/gravity.png"> </br> <span style="display:inline-block;margin-left:50px;"> make a modulation value rise and fall with physics<br/><br/><b>kick amt</b>: the amount of upward force to apply when kicking<br/><b>drag</b>: the resistance force to apply opposite the velocity<br/><b>gravity</b>: the gravitational force to apply downwards<br/><b>kick</b>: click to apply kick force (or, pulse this module for the same result)<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=gridsliders></a></br> <b>gridsliders</b></br> <img src="screenshots/gridsliders.png"> </br> <span style="display:inline-block;margin-left:50px;"> use a grid controller to control multiple sliders<br/><br/><b>direction</b>: should the grid display the sliders vertically, or horizontally?<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/></br></br></br></br> </span> <a name=leveltocv></a></br> <b>leveltocv</b></br> <img src="screenshots/leveltocv.png"> </br> <span style="display:inline-block;margin-left:50px;"> output a modulation value based on the level of incoming audio<br/><br/><b>release</b>: decay from the input level at this rate<br/><b>max</b>: output when level is one<br/><b>attack</b>: rise to the input level at this rate<br/><b>gain</b>: multiply the input audio by this value<br/><b>min</b>: output when level is zero<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=lfo></a></br> <b>lfo</b></br> <img src="screenshots/lfo.png"> </br> <span style="display:inline-block;margin-left:50px;"> modulates a slider with a low-frequency oscillator<br/><br/><b>enable</b>: turn on/off modulation<br/><b>shuffle</b>: adjust the waveoform to have a fast and slow cycle<br/><b>pin</b>: make LFO window remain visible<br/><b>interval</b>: length of oscillation period<br/><b>soften</b>: smooth out the hard edges of square and saw waveforms<br/><b>high</b>: output value at waveform's high point<br/><b>free rate</b>: rate of oscillator running in non-clock-synced time<br/><b>length</b>: proportion of time that should be spent on the waveform cycle<br/><b>bias</b>: bias the waveform towards the low or high point<br/><b>low</b>: output value at waveform's low point<br/><b>offset</b>: phase offset, to make oscillation earlier/later<br/><b>lite cpu</b>: only recalculate some parameters once per buffer, to reduce CPU load. can sound worse in some scenarios, especially with rapid modulation.<br/><b>osc</b>: type of oscillation waveform<br/><b>spread</b>: spread the waveform out to be closer to the low and high points<br/></br></br></br></br> </span> <a name=macroslider></a></br> <b>macroslider</b></br> <img src="screenshots/macroslider.png"> </br> <span style="display:inline-block;margin-left:50px;"> take a value and send scaled versions of that value to multiple destinations<br/><br/><b>start*</b>: the output value at the bottom of the input's range<br/><b>input</b>: the input value. intended to be a modulation patch target.<br/><b>end*</b>: the output value at the top of the input's range<br/></br></br></br></br> </span> <a name=modwheeltocv></a></br> <b>modwheeltocv</b></br> <img src="screenshots/modwheeltocv.png"> </br> <span style="display:inline-block;margin-left:50px;"> take a note's modwheel value and convert it to a modulation value<br/><br/><b>max</b>: output for modwheel value 127<br/><b>min</b>: output for modwheel value 0<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=mult></a></br> <b>mult</b></br> <img src="screenshots/mult.png"> </br> <span style="display:inline-block;margin-left:50px;"> outputs the result of value 1 multiplier by value 2. value 1 and value 2 are intended to be patch targets for modulators.<br/><br/></br></br></br></br> </span> <a name=notetofreq></a></br> <b>notetofreq</b></br> <img src="screenshots/notetofreq.png"> </br> <span style="display:inline-block;margin-left:50px;"> takes an input note, and outputs that note's frequency in hertz<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=notetoms></a></br> <b>notetoms</b></br> <img src="screenshots/notetoms.png"> </br> <span style="display:inline-block;margin-left:50px;"> takes an input note, and outputs the period of that note's frequency in milliseconds. useful for setting delay lines to create specific pitches.<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pitchtocv></a></br> <b>pitchtocv</b></br> <img src="screenshots/pitchtocv.png"> </br> <span style="display:inline-block;margin-left:50px;"> take a note's pitch and convert it to a modulation value<br/><br/><b>max</b>: output for pitch 127<br/><b>min</b>: output for pitch 0<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pitchtospeed></a></br> <b>pitchtospeed</b></br> <img src="screenshots/pitchtospeed.png"> </br> <span style="display:inline-block;margin-left:50px;"> convert an input pitch to a speed ratio. you could use this to control a sample's playback speed and make it playable with a keyboard.<br/><br/><b>ref freq</b>: the output is the input frequency divided by this number<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pressuretocv></a></br> <b>pressuretocv</b></br> <img src="screenshots/pressuretocv.png"> </br> <span style="display:inline-block;margin-left:50px;"> take a note's pressure and convert it to a modulation value<br/><br/><b>max</b>: output for pressure 127<br/><b>min</b>: output for pressure 0<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=ramper></a></br> <b>ramper</b></br> <img src="screenshots/ramper.png"> </br> <span style="display:inline-block;margin-left:50px;"> blend a control to a specified value over a specified time<br/><br/><b>start</b>: begin blending (or, send a pulse to this module for the same result)<br/><b>length</b>: length of time to blend over<br/><b>target</b>: the value to arrive at when the ramp is over<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=smoother></a></br> <b>smoother</b></br> <img src="screenshots/smoother.png"> </br> <span style="display:inline-block;margin-left:50px;"> outputs a smoothed value of the input<br/><br/><b>input</b>: set a value to smooth, patch a modulator into here<br/><b>smooth</b>: amount of smoothing to apply<br/></br></br></br></br> </span> <a name=subtract></a></br> <b>subtract</b></br> <img src="screenshots/subtract.png"> </br> <span style="display:inline-block;margin-left:50px;"> outputs the result of value 2 subtracted from value 1. value 1 and value 2 are intended to be patch targets for modulators.<br/><br/></br></br></br></br> </span> <a name=valuesetter></a></br> <b>valuesetter</b></br> <img src="screenshots/valuesetter.png"> </br> <span style="display:inline-block;margin-left:50px;"> set a specified value on a targeted control<br/><br/><b>slider</b>: value to set<br/><b>set</b>: click here to send the value (or, send a pulse to this module for the same result)<br/><b>value</b>: value to set<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=velocitytocv></a></br> <b>velocitytocv</b></br> <img src="screenshots/velocitytocv.png"> </br> <span style="display:inline-block;margin-left:50px;"> take a note's velocity and convert it to a modulation value<br/><br/><b>max</b>: output for velocity 127<br/><b>0 at note off</b>: output zero when note is released<br/><b>min</b>: output for velocity 0<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=vinylcontrol></a></br> <b>vinylcontrol</b></br> <img src="screenshots/vinylcontrol.png"> </br> <span style="display:inline-block;margin-left:50px;"> modulator which outputs a speed value based upon control vinyl input audio. provide it with a stereo signal from control vinyl (like you'd use to control serato) patched in from an "input" module.<br/><br/><b>control</b>: enable/disable transport control. when you enable it, it will use the current speed as the reference speed (so, the output will output a value of 1 until you change the vinyl's speed)<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <h2>pulse</h2> <a name=audiotopulse></a></br> <b>audiotopulse</b></br> <img src="screenshots/audiotopulse.png"> </br> <span style="display:inline-block;margin-left:50px;"> sends a pulse when the audio level surpasses a specified threshold<br/><br/><b>release</b>: the cooldown time for the audio signal before a pulse can be triggered again<br/><b>threshold</b>: send a pulse when the signal hits this threshold<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=boundstopulse></a></br> <b>boundstopulse</b></br> <img src="screenshots/boundstopulse.png"> </br> <span style="display:inline-block;margin-left:50px;"> sends a pulse when its input slider hits its max or min limit<br/><br/><b>input</b>: the slider to check bounds on<br/></br></br></br></br> </span> <a name=notetopulse></a></br> <b>notetopulse</b></br> <img src="screenshots/notetopulse.png"> </br> <span style="display:inline-block;margin-left:50px;"> trigger a pulse whenever a note is received<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=pulsebutton></a></br> <b>pulsebutton</b></br> <img src="screenshots/pulsebutton.png"> </br> <span style="display:inline-block;margin-left:50px;"> trigger a pulse with a button press<br/><br/><b>pulse</b>: trigger a pulse<br/></br></br></br></br> </span> <a name=pulsechance></a></br> <b>pulsechance</b></br> <img src="screenshots/pulsechance.png"> </br> <span style="display:inline-block;margin-left:50px;"> randomly allow pulses through, based on chance<br/><br/><b>deterministic</b>: allow for randomness to be repeated over an interval<br/><b>chance</b>: chance that pulses are allowed through<br/><b>*</b>: generate a new random seed<br/><b>seed</b>: number that determines the random sequence. send reset pulses to restart the deterministic random sequence.<br/><b><</b>: go to next seed<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=pulsedelayer></a></br> <b>pulsedelayer</b></br> <img src="screenshots/pulsedelayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> delay pulses<br/><br/><b>delay</b>: time to delay, in fractions of a measure<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=pulsedisplayer></a></br> <b>pulsedisplayer</b></br> <img src="screenshots/pulsedisplayer.png"> </br> <span style="display:inline-block;margin-left:50px;"> see what flags are on pulses<br/><br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=pulseflag></a></br> <b>pulseflag</b></br> <img src="screenshots/pulseflag.png"> </br> <span style="display:inline-block;margin-left:50px;"> set properties on pulses<br/><br/><b>flag</b>: property to add<br/><b>replace</b>: if disabled, the above flag is appended to the pulse's flags. if enabled, the pulse's flags are replaced by the above flag.<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=pulsegate></a></br> <b>pulsegate</b></br> <img src="screenshots/pulsegate.png"> </br> <span style="display:inline-block;margin-left:50px;"> control if pulses are allowed through<br/><br/><b>allow</b>: can pulses pass through?<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=pulsehocket></a></br> <b>pulsehocket</b></br> <img src="screenshots/pulsehocket.png"> </br> <span style="display:inline-block;margin-left:50px;"> sends pulses to randomized destinations<br/><br/><b>weight *</b>: chance that pulse goes to this destination<br/><b>*</b>: generate a new random seed<br/><b>seed</b>: number that determines the random sequence. send reset pulses to restart the deterministic random sequence.<br/><b><</b>: go to next seed<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=pulser></a></br> <b>pulser</b></br> <img src="screenshots/pulser.png"> </br> <span style="display:inline-block;margin-left:50px;"> send pulse messages at an interval<br/><br/><b>reset</b>: length of sequence before sending reset pulse<br/><b>interval</b>: rate to send pulses<br/><b>random</b>: tell pulsed modules to randomize their position<br/><b>t</b>: pulse interval in milliseconds<br/><b>offset</b>: pulse time offset, in fractions of the interval<br/><b>div</b>: measure division, when using "div" as the interval<br/><b>timemode</b>: when to send downbeat pulses, or set to "free" for pulses not locked to the transport<br/></br></br></br></br> </span> <a name=pulsesequence></a></br> <b>pulsesequence</b></br> <img src="screenshots/pulsesequence.png"> </br> <span style="display:inline-block;margin-left:50px;"> defines a looping sequence of pulses<br/><br/><b>length</b>: length of the sequence<br/><b>interval</b>: length of each step within the sequence<br/><b><</b>: shift sequence to the left<br/><b>></b>: shift sequence to the right<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <a name=pulsetrain></a></br> <b>pulsetrain</b></br> <img src="screenshots/pulsetrain.png"> </br> <span style="display:inline-block;margin-left:50px;"> defines a list of pulses to execute, once pulsed<br/><br/><b>length</b>: length of the sequence<br/><b>interval</b>: length of each step within the sequence<br/><br/>accepts: <font color=yellow>pulses</font> <br/></br></br></br></br> </span> <h2>effect chain</h2> <a name=basiceq></a></br> <b>basiceq</b></br> <img src="screenshots/basiceq.png"> </br> <span style="display:inline-block;margin-left:50px;"> simple multiband EQ<br/><br/><b>even</b>: reset EQ<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=biquad></a></br> <b>biquad</b></br> <img src="screenshots/biquad.png"> </br> <span style="display:inline-block;margin-left:50px;"> filter using biquad formula<br/><br/><b>Q</b>: resonance<br/><b>type</b>: filter type<br/><b>G</b>: gain<br/><b>F</b>: frequency cutoff<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=bitcrush></a></br> <b>bitcrush</b></br> <img src="screenshots/bitcrush.png"> </br> <span style="display:inline-block;margin-left:50px;"> reduce sample resolution and sample rate for lo-fi effects<br/><br/><b>crush</b>: sample resolution reduction<br/><b>downsamp</b>: sample rate reduction<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=butterworth></a></br> <b>butterworth</b></br> <img src="screenshots/butterworth.png"> </br> <span style="display:inline-block;margin-left:50px;"> filter using the butterworth formula<br/><br/><b>Q</b>: resonance<br/><b>F</b>: frequency cutoff<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=compressor></a></br> <b>compressor</b></br> <img src="screenshots/compressor.png"> </br> <span style="display:inline-block;margin-left:50px;"> try to keep volume at a certain level<br/><br/><b>ratio</b>: how much gain reduction to apply when the single passes the threshold<br/><b>lookahead</b>: how much time to "look ahead" to adjust the compression envelope. this necessarily introduces a delay into your output, which could be compensated for by running sequencers slightly early.<br/><b>drive</b>: rescale input to affect how much compression affects it<br/><b>mix</b>: amount of compression. lower this value for a "parallel compression" effect. you should use this mix slider instead of the effectchain's mix slider, to compensate for lookahead.<br/><b>attack</b>: speed to apply gain reduction<br/><b>threshold</b>: threshold where gain should start to be reduced<br/><b>release</b>: speed to remove gain reduction<br/><b>output</b>: makeup gain, to increase volume<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=dcremover></a></br> <b>dcremover</b></br> <img src="screenshots/dcremover.png"> </br> <span style="display:inline-block;margin-left:50px;"> high pass filter with a 10hz cutoff to remove DC offset, to keep signal from drifting away from zero<br/><br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=delay></a></br> <b>delay</b></br> <img src="screenshots/delay.png"> </br> <span style="display:inline-block;margin-left:50px;"> echoing delay<br/><br/><b>dry</b>: should the dry signal pass through, or just the delayed signal?<br/><b>short</b>: shortcut to shrink the range of the delay slider, to allow for audible-rate delays and comb filter sounds<br/><b>feedback</b>: should the output audio feed back into the delay?<br/><b>invert</b>: should the delayed audio have its signal inverted? this can give a different sound, and also cancel out DC offset to prevent it from accumulating with feedback.<br/><b>interval</b>: sets delay length to a musical duration<br/><b>delay</b>: delay in milliseconds<br/><b>amount</b>: amount of delay that returns<br/><b>input</b>: should we accept input into the delay?<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=distortion></a></br> <b>distortion</b></br> <img src="screenshots/distortion.png"> </br> <span style="display:inline-block;margin-left:50px;"> waveshaping distortion<br/><br/><b>preamp</b>: signal gain before feeding into distortion<br/><b>fuzz</b>: push input signal off-center to distort asymmetrically<br/><b>type</b>: style of distortion to apply<br/><b>clip</b>: cutoff point of distortion, lower values result in more extreme distortion<br/><b>center input</b>: remove dc offset from input signal to distort in a more controlled way<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=freeverb></a></br> <b>freeverb</b></br> <img src="screenshots/freeverb.png"> </br> <span style="display:inline-block;margin-left:50px;"> reverb using the "freeverb" algorithm<br/><br/><b>dry</b>: amount of untouched signal<br/><b>room size</b>: controls the length of the reverb, a higher value means longer reverb<br/><b>damp</b>: high frequency attenuation; a value of zero means all frequencies decay at the same rate, while higher settings will result in a faster decay of the high frequency range<br/><b>width</b>: stereo width of reverb<br/><b>wet</b>: amount of reverb signal<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=gainstage></a></br> <b>gainstage</b></br> <img src="screenshots/gainstage.png"> </br> <span style="display:inline-block;margin-left:50px;"> control volume within an effectchain<br/><br/><b>gain</b>: volume multiplier<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=gate></a></br> <b>gate</b></br> <img src="screenshots/gate.png"> </br> <span style="display:inline-block;margin-left:50px;"> only allow signal in when it's above a certain threshold. useful to eliminate line noise, or just as an effect.<br/><br/><b>release</b>: speed at which gate blends closed<br/><b>threshold</b>: volume threshold to open up the gate<br/><b>attack</b>: speed at which gate blends open<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=granulator></a></br> <b>granulator</b></br> <img src="screenshots/granulator.png"> </br> <span style="display:inline-block;margin-left:50px;"> granulate live input<br/><br/><b>dry</b>: amount of dry signal to allow through<br/><b>spd r</b>: randomization of grain speed<br/><b>g oct</b>: should we add octaves and fifths?<br/><b>pos r</b>: randomization of grain start point<br/><b>pos</b>: playback position within the buffer<br/><b>autocapture</b>: freeze input at this interval<br/><b>spa r</b>: randomization of time between grains<br/><b>width</b>: stereo width of grain placement<br/><b>overlap</b>: number of overlapping grains<br/><b>frz</b>: freeze the current recorded buffer<br/><b>speed</b>: speed of grain playback<br/><b>len ms</b>: length of each grain in milliseconds<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=muter></a></br> <b>muter</b></br> <img src="screenshots/muter.png"> </br> <span style="display:inline-block;margin-left:50px;"> mute an incoming signal<br/><br/><b>ms</b>: ramp time to mute/unmute signal<br/><b>pass</b>: when true, the signal is allowed through<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=noisify></a></br> <b>noisify</b></br> <img src="screenshots/noisify.png"> </br> <span style="display:inline-block;margin-left:50px;"> multiply input signal by white noise<br/><br/><b>width</b>: how frequently a new noise sample should be chosen<br/><b>amount</b>: amount of noise to apply<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=pitchshift></a></br> <b>pitchshift</b></br> <img src="screenshots/pitchshift.png"> </br> <span style="display:inline-block;margin-left:50px;"> shifts a signal's pitch<br/><br/><b>ratioselector</b>: shortcuts to useful pitch ratios<br/><b>ratio</b>: amount to pitchshift by (a value of 1 indicates no shift)<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=pumper></a></br> <b>pumper</b></br> <img src="screenshots/pumper.png"> </br> <span style="display:inline-block;margin-left:50px;"> dip the volume of a signal rhythmically, to emulate a "pumping sidechain" effect<br/><br/><b>length</b>: length of pump<br/><b>amount</b>: amount to lower volume<br/><b>interval</b>: the rate to pump<br/><b>curve</b>: how the volume returns<br/><b>attack</b>: how sharply the volume drops<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <a name=tremolo></a></br> <b>tremolo</b></br> <img src="screenshots/tremolo.png"> </br> <span style="display:inline-block;margin-left:50px;"> modulate signal's volume rhythmically<br/><br/><b>duty</b>: pulse width of LFO<br/><b>amount</b>: amount to lower volume<br/><b>interval</b>: speed of LFO<br/><b>osc</b>: LFO oscillator type<br/><b>offset</b>: offsets LFO phase<br/><br/>accepts: <font color=cyan>audio</font> <br/></br></br></br></br> </span> <h2>other</h2> <a name=abletonlink></a></br> <b>abletonlink</b></br> <img src="screenshots/abletonlink.png"> </br> <span style="display:inline-block;margin-left:50px;"> synchronizes transport with software and devices that support ableton link<br/><br/><b>reset next downbeat</b>: resets measure count on the next downbeat, to help synchronize to desired phase in session<br/><b>offset ms</b>: offset in milliseconds to tweak synchronization<br/></br></br></br></br> </span> <a name=clockin></a></br> <b>clockin</b></br> <img src="screenshots/clockin.png"> </br> <span style="display:inline-block;margin-left:50px;"> reads in clock pulses from external midi devices to control bespoke's transport<br/><br/><b>device</b>: device to receive from<br/><b>rounding</b>: precision to round incoming tempo data<br/><b>start offset ms</b>: offset in milliseconds to tweak synchronization between bespoke and gear<br/><b>smoothing</b>: how much to smooth incoming tempo<br/></br></br></br></br> </span> <a name=clockout></a></br> <b>clockout</b></br> <img src="screenshots/clockout.png"> </br> <span style="display:inline-block;margin-left:50px;"> sends out clock pulses to synchronize external midi devices<br/><br/><b>device</b>: device to target<br/><b>send start</b>: send a signal to reset the gear to the start of its sequence<br/><b>multiplier</b>: tempo multiplier for how the gear should respond to the signals<br/></br></br></br></br> </span> <a name=comment></a></br> <b>comment</b></br> <img src="screenshots/comment.png"> </br> <span style="display:inline-block;margin-left:50px;"> a box to display some text, to explain a section of a patch<br/><br/><b>comment</b>: type text here<br/></br></br></br></br> </span> <a name=eventcanvas></a></br> <b>eventcanvas</b></br> <img src="screenshots/eventcanvas.png"> </br> <span style="display:inline-block;margin-left:50px;"> schedule values to set over time<br/><br/><b>canvas</b>: canvas of events. canvas controls: -shift-click to add an event -hold shift and drag an event to duplicate -hold alt to drag an event without snapping -hold ctrl while dragging to snap to an interval -hold shift and scroll to zoom -hold alt and grab empty space to move slide the canvas view -hold ctrl and grab empty space to zoom the canvas view<br/><b>interval</b>: grid for snapping events to<br/><b>drag mode</b>: direction that elements can be dragged<br/><b>record</b>: record connected values as they change<br/><b>timeline</b>: control loop points<br/><b>clear</b>: delete all elements<br/><b>measures</b>: length of loop<br/><b>quantize</b>: quantizes events to grid<br/><b>view rows</b>: number of visible rows<br/><b>scrollh</b>: horizontal scrollbar<br/><b>delete</b>: delete highlighted elements<br/></br></br></br></br> </span> <a name=globalcontrols></a></br> <b>globalcontrols</b></br> <img src="screenshots/globalcontrols.png"> </br> <span style="display:inline-block;margin-left:50px;"> interface controls, intended to allow you to use midi controllers to navigate the canvas. controlling these sliders directly with the mouse is not recommended.<br/><br/><b>background r</b>: amount of red in background color<br/><b>scroll x</b>: emulate horizontal mouse scrolling<br/><b>lissajous g</b>: amount of green in background lissajous curve<br/><b>lissajous b</b>: amount of blue in background lissajous curve<br/><b>scroll y</b>: emulate vertical mouse scrolling<br/><b>zoom</b>: zoom level<br/><b>background b</b>: amount of blue in background color<br/><b>x pos</b>: horizontal panning position<br/><b>background g</b>: amount of green in background color<br/><b>lissajous r</b>: amount of red in background lissajous curve<br/><b>y pos</b>: vertical panning position<br/></br></br></br></br> </span> <a name=grid></a></br> <b>grid</b></br> <img src="screenshots/grid.png"> </br> <span style="display:inline-block;margin-left:50px;"> generic grid, to be used by "script" module, to assist in writing scripts that use grid-based midi controllers<br/><br/><b>grid</b>: patch a grid in here, from a "midicontroller" module<br/><b>momentary</b>: should clicks be treated as momentary inputs?<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=groupcontrol></a></br> <b>groupcontrol</b></br> <img src="screenshots/groupcontrol.png"> </br> <span style="display:inline-block;margin-left:50px;"> connect to several checkboxes, and control them all with one checkbox<br/><br/><b>group enabled</b>: controls the connected checkboxes<br/></br></br></br></br> </span> <a name=loopergranulator></a></br> <b>loopergranulator</b></br> <img src="screenshots/loopergranulator.png"> </br> <span style="display:inline-block;margin-left:50px;"> use with a "looper" module to play the contents with granular synthesis<br/><br/><b>spacing rand</b>: randomization of time between grains<br/><b>on</b>: use granular synthesis for looper playback<br/><b>octaves</b>: should we add octaves and fifths?<br/><b>speed rand</b>: randomization of grain speed<br/><b>overlap</b>: number of overlapping grains<br/><b>freeze</b>: stop advancing looper time<br/><b>width</b>: stereo width of grain placement<br/><b>loop pos</b>: playback position within loop<br/><b>pos rand</b>: randomization of grain start point<br/><b>speed</b>: speed of grain playback<br/><b>len ms</b>: length of each grain in milliseconds<br/></br></br></br></br> </span> <a name=multitrackrecorder></a></br> <b>multitrackrecorder</b></br> <img src="screenshots/multitrackrecorder.png"> </br> <span style="display:inline-block;margin-left:50px;"> record several synchronized tracks of audio, to write to disk for mixing in an external DAW<br/><br/><b>add track</b>: add an additional track<br/><b>clear</b>: clear the audio in the tracks<br/><b>bounce</b>: write the tracks to your recordings directory<br/><b>record</b>: record input to the tracks<br/></br></br></br></br> </span> <a name=notetoggle></a></br> <b>notetoggle</b></br> <img src="screenshots/notetoggle.png"> </br> <span style="display:inline-block;margin-left:50px;"> turn a control on or off depending on if there are any input notes<br/><br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=oscoutput></a></br> <b>oscoutput</b></br> <img src="screenshots/oscoutput.png"> </br> <span style="display:inline-block;margin-left:50px;"> send OSC messages when slider values change or when notes are received<br/><br/><b>note out address</b>: label to send input notes. the message will be sent in the format /bespoke/[label] [pitch] [velocity]<br/><b>slider*</b>: sends a value to the address. try patching a modulator into this, such as a leveltocv module to send audio levels.<br/><b>label*</b>: label to send slider value. the message will be sent in the format /bespoke/[label] [value]<br/><b>osc out address</b>: destination to send OSC messages to<br/><b>osc out port</b>: port to send OSC messages to<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=prefab></a></br> <b>prefab</b></br> <img src="screenshots/prefab.png"> </br> <span style="display:inline-block;margin-left:50px;"> create a collection of modules that can be loaded from the "prefabs" menu. drag and drop modules onto here to add them to the prefab. drag the grey cable to any modules you want to remove from the prefab.<br/><br/><b>load</b>: load a .pfb<br/><b>save</b>: save as a .pfb file<br/><b>disband</b>: free all modules from this prefab<br/></br></br></br></br> </span> <a name=push2control></a></br> <b>push2control</b></br> <img src="screenshots/push2control.png"> </br> <span style="display:inline-block;margin-left:50px;"> use an ableton push 2 to control bespoke's interface<br/><br/></br></br></br></br> </span> <a name=radiosequencer></a></br> <b>radiosequencer</b></br> <img src="screenshots/radiosequencer.png"> </br> <span style="display:inline-block;margin-left:50px;"> sequence to only enable one value at a time. patch it to the "enabled" checkbox on several modules to only enable one module at a time. works well in conjunction with "groupcontrol" module.<br/><br/><b>length</b>: length of sequence<br/><b>interval</b>: rate to advance<br/><b>grid</b>: patch a grid in here from a "midicontroller" module<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=samplebrowser></a></br> <b>samplebrowser</b></br> <img src="screenshots/samplebrowser.png"> </br> <span style="display:inline-block;margin-left:50px;"> browse your system for samples. drag samples from here to your desired targets (sampleplayer, drumplayer, seaofgrain, etc)<br/><br/><b> > </b>: next page<br/><b> < </b>: previous page<br/></br></br></br></br> </span> <a name=scale></a></br> <b>scale</b></br> <img src="screenshots/scale.png"> </br> <span style="display:inline-block;margin-left:50px;"> controls the global scale used by various modules<br/><br/><b>scale</b>: which set of notes to use<br/><b>tuning</b>: what frequency does the pitch defined in "note" represent?<br/><b>load KBM</b>: load KBM file to determine keyboard mapping<br/><b>PPO</b>: pitches per octave<br/><b>note</b>: the pitch that maps to the frequency defined in "tuning"<br/><b>load SCL</b>: load SCL file to determine scale<br/><b>intonation</b>: which method to use to tune the scale<br/><b>root</b>: root note of the scale<br/></br></br></br></br> </span> <a name=script></a></br> <b>script</b></br> <img src="screenshots/script.png"> </br> <span style="display:inline-block;margin-left:50px;"> python scripting for livecoding notes and module control<br/><br/><b>a</b>: variable for the script to use, can be modulation by other sources. access via me.get("a")<br/><b>load</b>: load selected script<br/><b>c</b>: variable for the script to use, can be modulation by other sources. access via me.get("c")<br/><b>b</b>: variable for the script to use, can be modulation by other sources. access via me.get("b")<br/><b>run</b>: click here to execute the code, or press ctrl-R<br/><b>d</b>: variable for the script to use, can be modulation by other sources. access via me.get("d")<br/><b>stop</b>: cancel any events scheduled by this script<br/><b>style</b>: choose a text theme, from script_styles.json<br/><b>code</b>: write code here. press ctrl-R to execute the code, or ctrl-shift-R to just execute the current block.<br/><b>save as</b>: save the current script<br/><b>loadscript</b>: choose a script from here, then press "load"<br/><b>?</b>: show scripting reference<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=scriptstatus></a></br> <b>scriptstatus</b></br> <img src="screenshots/scriptstatus.png"> </br> <span style="display:inline-block;margin-left:50px;"> shows everything in the current python scope, for debugging<br/><br/><b>reset all</b>: resets scope variables<br/></br></br></br></br> </span> <a name=selector></a></br> <b>selector</b></br> <img src="screenshots/selector.png"> </br> <span style="display:inline-block;margin-left:50px;"> radio button control to only enable one value at a time. patch it to the "enabled" checkbox on several modules to only enable one module at a time. works well in conjunction with "groupcontrol" module.<br/><br/><b>selector</b>: which value should be set to 1<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=snapshots></a></br> <b>snapshots</b></br> <img src="screenshots/snapshots.png"> </br> <span style="display:inline-block;margin-left:50px;"> save and restore sets of values. connect the grey circle to modules to affect all controls on that module. connect the purple circle to a control to affect only that control. shift-click on the grid to store a preset to that square, and click on a grid square to load that preset.<br/><br/><b>snapshot label</b>: assign a label to this snapshot<br/><b>auto-store on switch</b>: when switching to a new slot, automatically store state in the current slot<br/><b>clear</b>: clear all snapshots<br/><b>random</b>: randomize connected controls<br/><b>add</b>: snapshot the currently connected controls to the next available snapshot slot<br/><b>snapshot</b>: jump to a snapshot<br/><b>blend</b>: length of time in milliseconds over which to blend snapshot values<br/><b>store</b>: when clicking/selecting a snapshot, store into that slot (alternately: hold the shift key)<br/><b>delete</b>: when clicking/selecting a snapshot, delete that slot (alternately: hold the alt/option key)<br/><br/>accepts: <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=songbuilder></a></br> <b>songbuilder</b></br> <img src="screenshots/songbuilder.png"> </br> <span style="display:inline-block;margin-left:50px;"> large-scale organizer to arrange settings into scenes and then sequence them. this is bespoke's "song mode"<br/><br/><b>move left</b>: move this target left in the scene<br/><b>play from*</b>: play sequence from this step<br/><b>add target</b>: add a targeted control for scenes to affect<br/><b>stop</b>: stop the sequence<br/><b>activate first scene on stop</b>: when stopping, activate the first scene. it is recommended that you use the first scene as an "off" scene, and have it disable all song elements.<br/><b>pause</b>: hold the sequence on the current scene<br/><b>loop end</b>: loop step index that the loop ends<br/><b>move right</b>: move this target right in the scene<br/><b>value*</b>: value to use for target in this scene<br/><b>context*</b>: options for this scene<br/><b>scene*</b>: name of scene for this step<br/><b>type</b>: change the control display type for this target<br/><b>bars*</b>: length in bars that this scene should play for<br/><b>checkbox*</b>: value to use for target in this scene<br/><b>loop start</b>: loop step index to start the loop on<br/><b>name*</b>: name of this scene<br/><b>dropdown*</b>: value to use for target in this scene<br/><b>change quantize</b>: when a change should happen after pressing the play button on a scene. "switch" changes immediately, and "jump" changes immediately and also resets the global transport.<br/><b>play</b>: play the sequence<br/><b>contextmenu*</b>: options for this step<br/><b>go*</b>: play this scene<br/><b>use sequencer</b>: show scene sequencer<br/><b>loop</b>: enable a loop within the sequence<br/><br/>accepts: <font color=yellow>pulses</font> <font color=orange>notes</font> <br/></br></br></br></br> </span> <a name=timelinecontrol></a></br> <b>timelinecontrol</b></br> <img src="screenshots/timelinecontrol.png"> </br> <span style="display:inline-block;margin-left:50px;"> control global transport position<br/><br/><b>reset</b>: reset to beginning<br/><b>loop end</b>: measure end of loop<br/><b>loop start</b>: measure start of loop<br/><b>dock</b>: should we dock this module to the UI layer?<br/><b>length</b>: length of timeline display, in measures<br/><b>measure</b>: current position. click to jump around.<br/><b>loop</b>: should we have a looping section?<br/></br></br></br></br> </span> <a name=timerdisplay></a></br> <b>timerdisplay</b></br> <img src="screenshots/timerdisplay.png"> </br> <span style="display:inline-block;margin-left:50px;"> displays a timer to indicate how long a patch has been running<br/><br/><b>reset</b>: reset timer to zero<br/></br></br></br></br> </span> <a name=transport></a></br> <b>transport</b></br> <img src="screenshots/transport.png"> </br> <span style="display:inline-block;margin-left:50px;"> controls tempo and current time position<br/><br/><b>reset</b>: reset timeline to zero<br/><b> + </b>: increase tempo by one<br/><b> - </b>: decrease tempo by one<br/><b> < </b>: nudge current time backward<br/><b>tempo</b>: global tempo, in beats per minute<br/><b>swing</b>: where the halfway point of musical time within the swing interval should fall. a value of .5 represents no swing.<br/><b>timesigtop</b>: time signature top value<br/><b>timesigbottom</b>: time signature bottom value<br/><b>swing interval</b>: interval over which to apply swing<br/><b>play/pause</b>: stop all audio processing (shift-p)<br/><b> > </b>: nudge current time forward<br/></br></br></br></br> </span> <a name=valuestream></a></br> <b>valuestream</b></br> <img src="screenshots/valuestream.png"> </br> <span style="display:inline-block;margin-left:50px;"> displays a control's value over time. connect the cable to a UI control to see how it is changing.<br/><br/><b>speed</b>: how quickly display should scroll<br/></br></br></br></br> </span></main> </div> </body> </html> ```
/content/code_sandbox/autodoc/bespokesynth.com/docs/index.html
html
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
41,872
```css /*! * Bootstrap v3.3.2 (path_to_url */ html { font-family: sans-serif; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } body { margin: 0; } article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary { display: block; } audio, canvas, progress, video { display: inline-block; vertical-align: baseline; } audio:not([controls]) { display: none; height: 0; } [hidden], template { display: none; } a { background-color: transparent; } a:active, a:hover { outline: 0; } abbr[title] { border-bottom: 1px dotted; } b, strong { font-weight: bold; } dfn { font-style: italic; } h1 { margin: .67em 0; font-size: 2em; } mark { color: #000; background: #ff0; } small { font-size: 80%; } sub, sup { position: relative; font-size: 75%; line-height: 0; vertical-align: baseline; } sup { top: -.5em; } sub { bottom: -.25em; } img { border: 0; } svg:not(:root) { overflow: hidden; } figure { margin: 1em 40px; } hr { height: 0; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } pre { overflow: auto; } code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em; } button, input, optgroup, select, textarea { margin: 0; font: inherit; color: inherit; } button { overflow: visible; } button, select { text-transform: none; } button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } button[disabled], html input[disabled] { cursor: default; } button::-moz-focus-inner, input::-moz-focus-inner { padding: 0; border: 0; } input { line-height: normal; } input[type="checkbox"], input[type="radio"] { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 0; } input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { height: auto; } input[type="search"] { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; -webkit-appearance: textfield; } input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } fieldset { padding: .35em .625em .75em; margin: 0 2px; border: 1px solid #c0c0c0; } legend { padding: 0; border: 0; } textarea { overflow: auto; } optgroup { font-weight: bold; } table { border-spacing: 0; border-collapse: collapse; } td, th { padding: 0; } /*! Source: path_to_url */ @media print { *, *:before, *:after { color: #000 !important; text-shadow: none !important; background: transparent !important; -webkit-box-shadow: none !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } a[href^="#"]:after, a[href^="javascript:"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } select { background: #fff !important; } .navbar { display: none; } .btn > .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px solid #000; } .table { border-collapse: collapse !important; } .table td, .table th { background-color: #fff !important; } .table-bordered th, .table-bordered td { border: 1px solid #ddd !important; } } @font-face { font-family: 'Glyphicons Halflings'; src: url('../fonts/glyphicons-halflings-regular.eot'); src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); } .glyphicon { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .glyphicon-asterisk:before { content: "\2a"; } .glyphicon-plus:before { content: "\2b"; } .glyphicon-euro:before, .glyphicon-eur:before { content: "\20ac"; } .glyphicon-minus:before { content: "\2212"; } .glyphicon-cloud:before { content: "\2601"; } .glyphicon-envelope:before { content: "\2709"; } .glyphicon-pencil:before { content: "\270f"; } .glyphicon-glass:before { content: "\e001"; } .glyphicon-music:before { content: "\e002"; } .glyphicon-search:before { content: "\e003"; } .glyphicon-heart:before { content: "\e005"; } .glyphicon-star:before { content: "\e006"; } .glyphicon-star-empty:before { content: "\e007"; } .glyphicon-user:before { content: "\e008"; } .glyphicon-film:before { content: "\e009"; } .glyphicon-th-large:before { content: "\e010"; } .glyphicon-th:before { content: "\e011"; } .glyphicon-th-list:before { content: "\e012"; } .glyphicon-ok:before { content: "\e013"; } .glyphicon-remove:before { content: "\e014"; } .glyphicon-zoom-in:before { content: "\e015"; } .glyphicon-zoom-out:before { content: "\e016"; } .glyphicon-off:before { content: "\e017"; } .glyphicon-signal:before { content: "\e018"; } .glyphicon-cog:before { content: "\e019"; } .glyphicon-trash:before { content: "\e020"; } .glyphicon-home:before { content: "\e021"; } .glyphicon-file:before { content: "\e022"; } .glyphicon-time:before { content: "\e023"; } .glyphicon-road:before { content: "\e024"; } .glyphicon-download-alt:before { content: "\e025"; } .glyphicon-download:before { content: "\e026"; } .glyphicon-upload:before { content: "\e027"; } .glyphicon-inbox:before { content: "\e028"; } .glyphicon-play-circle:before { content: "\e029"; } .glyphicon-repeat:before { content: "\e030"; } .glyphicon-refresh:before { content: "\e031"; } .glyphicon-list-alt:before { content: "\e032"; } .glyphicon-lock:before { content: "\e033"; } .glyphicon-flag:before { content: "\e034"; } .glyphicon-headphones:before { content: "\e035"; } .glyphicon-volume-off:before { content: "\e036"; } .glyphicon-volume-down:before { content: "\e037"; } .glyphicon-volume-up:before { content: "\e038"; } .glyphicon-qrcode:before { content: "\e039"; } .glyphicon-barcode:before { content: "\e040"; } .glyphicon-tag:before { content: "\e041"; } .glyphicon-tags:before { content: "\e042"; } .glyphicon-book:before { content: "\e043"; } .glyphicon-bookmark:before { content: "\e044"; } .glyphicon-print:before { content: "\e045"; } .glyphicon-camera:before { content: "\e046"; } .glyphicon-font:before { content: "\e047"; } .glyphicon-bold:before { content: "\e048"; } .glyphicon-italic:before { content: "\e049"; } .glyphicon-text-height:before { content: "\e050"; } .glyphicon-text-width:before { content: "\e051"; } .glyphicon-align-left:before { content: "\e052"; } .glyphicon-align-center:before { content: "\e053"; } .glyphicon-align-right:before { content: "\e054"; } .glyphicon-align-justify:before { content: "\e055"; } .glyphicon-list:before { content: "\e056"; } .glyphicon-indent-left:before { content: "\e057"; } .glyphicon-indent-right:before { content: "\e058"; } .glyphicon-facetime-video:before { content: "\e059"; } .glyphicon-picture:before { content: "\e060"; } .glyphicon-map-marker:before { content: "\e062"; } .glyphicon-adjust:before { content: "\e063"; } .glyphicon-tint:before { content: "\e064"; } .glyphicon-edit:before { content: "\e065"; } .glyphicon-share:before { content: "\e066"; } .glyphicon-check:before { content: "\e067"; } .glyphicon-move:before { content: "\e068"; } .glyphicon-step-backward:before { content: "\e069"; } .glyphicon-fast-backward:before { content: "\e070"; } .glyphicon-backward:before { content: "\e071"; } .glyphicon-play:before { content: "\e072"; } .glyphicon-pause:before { content: "\e073"; } .glyphicon-stop:before { content: "\e074"; } .glyphicon-forward:before { content: "\e075"; } .glyphicon-fast-forward:before { content: "\e076"; } .glyphicon-step-forward:before { content: "\e077"; } .glyphicon-eject:before { content: "\e078"; } .glyphicon-chevron-left:before { content: "\e079"; } .glyphicon-chevron-right:before { content: "\e080"; } .glyphicon-plus-sign:before { content: "\e081"; } .glyphicon-minus-sign:before { content: "\e082"; } .glyphicon-remove-sign:before { content: "\e083"; } .glyphicon-ok-sign:before { content: "\e084"; } .glyphicon-question-sign:before { content: "\e085"; } .glyphicon-info-sign:before { content: "\e086"; } .glyphicon-screenshot:before { content: "\e087"; } .glyphicon-remove-circle:before { content: "\e088"; } .glyphicon-ok-circle:before { content: "\e089"; } .glyphicon-ban-circle:before { content: "\e090"; } .glyphicon-arrow-left:before { content: "\e091"; } .glyphicon-arrow-right:before { content: "\e092"; } .glyphicon-arrow-up:before { content: "\e093"; } .glyphicon-arrow-down:before { content: "\e094"; } .glyphicon-share-alt:before { content: "\e095"; } .glyphicon-resize-full:before { content: "\e096"; } .glyphicon-resize-small:before { content: "\e097"; } .glyphicon-exclamation-sign:before { content: "\e101"; } .glyphicon-gift:before { content: "\e102"; } .glyphicon-leaf:before { content: "\e103"; } .glyphicon-fire:before { content: "\e104"; } .glyphicon-eye-open:before { content: "\e105"; } .glyphicon-eye-close:before { content: "\e106"; } .glyphicon-warning-sign:before { content: "\e107"; } .glyphicon-plane:before { content: "\e108"; } .glyphicon-calendar:before { content: "\e109"; } .glyphicon-random:before { content: "\e110"; } .glyphicon-comment:before { content: "\e111"; } .glyphicon-magnet:before { content: "\e112"; } .glyphicon-chevron-up:before { content: "\e113"; } .glyphicon-chevron-down:before { content: "\e114"; } .glyphicon-retweet:before { content: "\e115"; } .glyphicon-shopping-cart:before { content: "\e116"; } .glyphicon-folder-close:before { content: "\e117"; } .glyphicon-folder-open:before { content: "\e118"; } .glyphicon-resize-vertical:before { content: "\e119"; } .glyphicon-resize-horizontal:before { content: "\e120"; } .glyphicon-hdd:before { content: "\e121"; } .glyphicon-bullhorn:before { content: "\e122"; } .glyphicon-bell:before { content: "\e123"; } .glyphicon-certificate:before { content: "\e124"; } .glyphicon-thumbs-up:before { content: "\e125"; } .glyphicon-thumbs-down:before { content: "\e126"; } .glyphicon-hand-right:before { content: "\e127"; } .glyphicon-hand-left:before { content: "\e128"; } .glyphicon-hand-up:before { content: "\e129"; } .glyphicon-hand-down:before { content: "\e130"; } .glyphicon-circle-arrow-right:before { content: "\e131"; } .glyphicon-circle-arrow-left:before { content: "\e132"; } .glyphicon-circle-arrow-up:before { content: "\e133"; } .glyphicon-circle-arrow-down:before { content: "\e134"; } .glyphicon-globe:before { content: "\e135"; } .glyphicon-wrench:before { content: "\e136"; } .glyphicon-tasks:before { content: "\e137"; } .glyphicon-filter:before { content: "\e138"; } .glyphicon-briefcase:before { content: "\e139"; } .glyphicon-fullscreen:before { content: "\e140"; } .glyphicon-dashboard:before { content: "\e141"; } .glyphicon-paperclip:before { content: "\e142"; } .glyphicon-heart-empty:before { content: "\e143"; } .glyphicon-link:before { content: "\e144"; } .glyphicon-phone:before { content: "\e145"; } .glyphicon-pushpin:before { content: "\e146"; } .glyphicon-usd:before { content: "\e148"; } .glyphicon-gbp:before { content: "\e149"; } .glyphicon-sort:before { content: "\e150"; } .glyphicon-sort-by-alphabet:before { content: "\e151"; } .glyphicon-sort-by-alphabet-alt:before { content: "\e152"; } .glyphicon-sort-by-order:before { content: "\e153"; } .glyphicon-sort-by-order-alt:before { content: "\e154"; } .glyphicon-sort-by-attributes:before { content: "\e155"; } .glyphicon-sort-by-attributes-alt:before { content: "\e156"; } .glyphicon-unchecked:before { content: "\e157"; } .glyphicon-expand:before { content: "\e158"; } .glyphicon-collapse-down:before { content: "\e159"; } .glyphicon-collapse-up:before { content: "\e160"; } .glyphicon-log-in:before { content: "\e161"; } .glyphicon-flash:before { content: "\e162"; } .glyphicon-log-out:before { content: "\e163"; } .glyphicon-new-window:before { content: "\e164"; } .glyphicon-record:before { content: "\e165"; } .glyphicon-save:before { content: "\e166"; } .glyphicon-open:before { content: "\e167"; } .glyphicon-saved:before { content: "\e168"; } .glyphicon-import:before { content: "\e169"; } .glyphicon-export:before { content: "\e170"; } .glyphicon-send:before { content: "\e171"; } .glyphicon-floppy-disk:before { content: "\e172"; } .glyphicon-floppy-saved:before { content: "\e173"; } .glyphicon-floppy-remove:before { content: "\e174"; } .glyphicon-floppy-save:before { content: "\e175"; } .glyphicon-floppy-open:before { content: "\e176"; } .glyphicon-credit-card:before { content: "\e177"; } .glyphicon-transfer:before { content: "\e178"; } .glyphicon-cutlery:before { content: "\e179"; } .glyphicon-header:before { content: "\e180"; } .glyphicon-compressed:before { content: "\e181"; } .glyphicon-earphone:before { content: "\e182"; } .glyphicon-phone-alt:before { content: "\e183"; } .glyphicon-tower:before { content: "\e184"; } .glyphicon-stats:before { content: "\e185"; } .glyphicon-sd-video:before { content: "\e186"; } .glyphicon-hd-video:before { content: "\e187"; } .glyphicon-subtitles:before { content: "\e188"; } .glyphicon-sound-stereo:before { content: "\e189"; } .glyphicon-sound-dolby:before { content: "\e190"; } .glyphicon-sound-5-1:before { content: "\e191"; } .glyphicon-sound-6-1:before { content: "\e192"; } .glyphicon-sound-7-1:before { content: "\e193"; } .glyphicon-copyright-mark:before { content: "\e194"; } .glyphicon-registration-mark:before { content: "\e195"; } .glyphicon-cloud-download:before { content: "\e197"; } .glyphicon-cloud-upload:before { content: "\e198"; } .glyphicon-tree-conifer:before { content: "\e199"; } .glyphicon-tree-deciduous:before { content: "\e200"; } .glyphicon-cd:before { content: "\e201"; } .glyphicon-save-file:before { content: "\e202"; } .glyphicon-open-file:before { content: "\e203"; } .glyphicon-level-up:before { content: "\e204"; } .glyphicon-copy:before { content: "\e205"; } .glyphicon-paste:before { content: "\e206"; } .glyphicon-alert:before { content: "\e209"; } .glyphicon-equalizer:before { content: "\e210"; } .glyphicon-king:before { content: "\e211"; } .glyphicon-queen:before { content: "\e212"; } .glyphicon-pawn:before { content: "\e213"; } .glyphicon-bishop:before { content: "\e214"; } .glyphicon-knight:before { content: "\e215"; } .glyphicon-baby-formula:before { content: "\e216"; } .glyphicon-tent:before { content: "\26fa"; } .glyphicon-blackboard:before { content: "\e218"; } .glyphicon-bed:before { content: "\e219"; } .glyphicon-apple:before { content: "\f8ff"; } .glyphicon-erase:before { content: "\e221"; } .glyphicon-hourglass:before { content: "\231b"; } .glyphicon-lamp:before { content: "\e223"; } .glyphicon-duplicate:before { content: "\e224"; } .glyphicon-piggy-bank:before { content: "\e225"; } .glyphicon-scissors:before { content: "\e226"; } .glyphicon-bitcoin:before { content: "\e227"; } .glyphicon-yen:before { content: "\00a5"; } .glyphicon-ruble:before { content: "\20bd"; } .glyphicon-scale:before { content: "\e230"; } .glyphicon-ice-lolly:before { content: "\e231"; } .glyphicon-ice-lolly-tasted:before { content: "\e232"; } .glyphicon-education:before { content: "\e233"; } .glyphicon-option-horizontal:before { content: "\e234"; } .glyphicon-option-vertical:before { content: "\e235"; } .glyphicon-menu-hamburger:before { content: "\e236"; } .glyphicon-modal-window:before { content: "\e237"; } .glyphicon-oil:before { content: "\e238"; } .glyphicon-grain:before { content: "\e239"; } .glyphicon-sunglasses:before { content: "\e240"; } .glyphicon-text-size:before { content: "\e241"; } .glyphicon-text-color:before { content: "\e242"; } .glyphicon-text-background:before { content: "\e243"; } .glyphicon-object-align-top:before { content: "\e244"; } .glyphicon-object-align-bottom:before { content: "\e245"; } .glyphicon-object-align-horizontal:before { content: "\e246"; } .glyphicon-object-align-left:before { content: "\e247"; } .glyphicon-object-align-vertical:before { content: "\e248"; } .glyphicon-object-align-right:before { content: "\e249"; } .glyphicon-triangle-right:before { content: "\e250"; } .glyphicon-triangle-left:before { content: "\e251"; } .glyphicon-triangle-bottom:before { content: "\e252"; } .glyphicon-triangle-top:before { content: "\e253"; } .glyphicon-console:before { content: "\e254"; } .glyphicon-superscript:before { content: "\e255"; } .glyphicon-subscript:before { content: "\e256"; } .glyphicon-menu-left:before { content: "\e257"; } .glyphicon-menu-right:before { content: "\e258"; } .glyphicon-menu-down:before { content: "\e259"; } .glyphicon-menu-up:before { content: "\e260"; } * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } html { font-size: 10px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.42857143; color: #333; background-color: #fff; } input, button, select, textarea { font-family: inherit; font-size: inherit; line-height: inherit; } a { color: #337ab7; text-decoration: none; } a:hover, a:focus { color: #23527c; text-decoration: underline; } a:focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } figure { margin: 0; } img { vertical-align: middle; } .img-responsive, .thumbnail > img, .thumbnail a > img, .carousel-inner > .item > img, .carousel-inner > .item > a > img { display: block; max-width: 100%; height: auto; } .img-rounded { border-radius: 6px; } .img-thumbnail { display: inline-block; max-width: 100%; height: auto; padding: 4px; line-height: 1.42857143; background-color: #fff; border: 1px solid #ddd; border-radius: 4px; -webkit-transition: all .2s ease-in-out; -o-transition: all .2s ease-in-out; transition: all .2s ease-in-out; } .img-circle { border-radius: 50%; } hr { margin-top: 20px; margin-bottom: 20px; border: 0; border-top: 1px solid #eee; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; } .sr-only-focusable:active, .sr-only-focusable:focus { position: static; width: auto; height: auto; margin: 0; overflow: visible; clip: auto; } h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 { font-family: inherit; font-weight: 500; line-height: 1.1; color: inherit; } h1 small, h2 small, h3 small, h4 small, h5 small, h6 small, .h1 small, .h2 small, .h3 small, .h4 small, .h5 small, .h6 small, h1 .small, h2 .small, h3 .small, h4 .small, h5 .small, h6 .small, .h1 .small, .h2 .small, .h3 .small, .h4 .small, .h5 .small, .h6 .small { font-weight: normal; line-height: 1; color: #777; } h1, .h1, h2, .h2, h3, .h3 { margin-top: 20px; margin-bottom: 10px; } h1 small, .h1 small, h2 small, .h2 small, h3 small, .h3 small, h1 .small, .h1 .small, h2 .small, .h2 .small, h3 .small, .h3 .small { font-size: 65%; } h4, .h4, h5, .h5, h6, .h6 { margin-top: 10px; margin-bottom: 10px; } h4 small, .h4 small, h5 small, .h5 small, h6 small, .h6 small, h4 .small, .h4 .small, h5 .small, .h5 .small, h6 .small, .h6 .small { font-size: 75%; } h1, .h1 { font-size: 36px; } h2, .h2 { font-size: 30px; } h3, .h3 { font-size: 24px; } h4, .h4 { font-size: 18px; } h5, .h5 { font-size: 14px; } h6, .h6 { font-size: 12px; } p { margin: 0 0 10px; } .lead { margin-bottom: 20px; font-size: 16px; font-weight: 300; line-height: 1.4; } @media (min-width: 768px) { .lead { font-size: 21px; } } small, .small { font-size: 85%; } mark, .mark { padding: .2em; background-color: #fcf8e3; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } .text-justify { text-align: justify; } .text-nowrap { white-space: nowrap; } .text-lowercase { text-transform: lowercase; } .text-uppercase { text-transform: uppercase; } .text-capitalize { text-transform: capitalize; } .text-muted { color: #777; } .text-primary { color: #337ab7; } a.text-primary:hover { color: #286090; } .text-success { color: #3c763d; } a.text-success:hover { color: #2b542c; } .text-info { color: #31708f; } a.text-info:hover { color: #245269; } .text-warning { color: #8a6d3b; } a.text-warning:hover { color: #66512c; } .text-danger { color: #a94442; } a.text-danger:hover { color: #843534; } .bg-primary { color: #fff; background-color: #337ab7; } a.bg-primary:hover { background-color: #286090; } .bg-success { background-color: #dff0d8; } a.bg-success:hover { background-color: #c1e2b3; } .bg-info { background-color: #d9edf7; } a.bg-info:hover { background-color: #afd9ee; } .bg-warning { background-color: #fcf8e3; } a.bg-warning:hover { background-color: #f7ecb5; } .bg-danger { background-color: #f2dede; } a.bg-danger:hover { background-color: #e4b9b9; } .page-header { padding-bottom: 9px; margin: 40px 0 20px; border-bottom: 1px solid #eee; } ul, ol { margin-top: 0; margin-bottom: 10px; } ul ul, ol ul, ul ol, ol ol { margin-bottom: 0; } .list-unstyled { padding-left: 0; list-style: none; } .list-inline { padding-left: 0; margin-left: -5px; list-style: none; } .list-inline > li { display: inline-block; padding-right: 5px; padding-left: 5px; } dl { margin-top: 0; margin-bottom: 20px; } dt, dd { line-height: 1.42857143; } dt { font-weight: bold; } dd { margin-left: 0; } @media (min-width: 768px) { .dl-horizontal dt { float: left; width: 160px; overflow: hidden; clear: left; text-align: right; text-overflow: ellipsis; white-space: nowrap; } .dl-horizontal dd { margin-left: 180px; } } abbr[title], abbr[data-original-title] { cursor: help; border-bottom: 1px dotted #777; } .initialism { font-size: 90%; text-transform: uppercase; } blockquote { padding: 10px 20px; margin: 0 0 20px; font-size: 17.5px; border-left: 5px solid #eee; } blockquote p:last-child, blockquote ul:last-child, blockquote ol:last-child { margin-bottom: 0; } blockquote footer, blockquote small, blockquote .small { display: block; font-size: 80%; line-height: 1.42857143; color: #777; } blockquote footer:before, blockquote small:before, blockquote .small:before { content: '\2014 \00A0'; } .blockquote-reverse, blockquote.pull-right { padding-right: 15px; padding-left: 0; text-align: right; border-right: 5px solid #eee; border-left: 0; } .blockquote-reverse footer:before, blockquote.pull-right footer:before, .blockquote-reverse small:before, blockquote.pull-right small:before, .blockquote-reverse .small:before, blockquote.pull-right .small:before { content: ''; } .blockquote-reverse footer:after, blockquote.pull-right footer:after, .blockquote-reverse small:after, blockquote.pull-right small:after, .blockquote-reverse .small:after, blockquote.pull-right .small:after { content: '\00A0 \2014'; } address { margin-bottom: 20px; font-style: normal; line-height: 1.42857143; } code, kbd, pre, samp { font-family: Menlo, Monaco, Consolas, "Courier New", monospace; } code { padding: 2px 4px; font-size: 90%; color: #c7254e; background-color: #f9f2f4; border-radius: 4px; } kbd { padding: 2px 4px; font-size: 90%; color: #fff; background-color: #333; border-radius: 3px; -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); } kbd kbd { padding: 0; font-size: 100%; font-weight: bold; -webkit-box-shadow: none; box-shadow: none; } pre { display: block; padding: 9.5px; margin: 0 0 10px; font-size: 13px; line-height: 1.42857143; color: #333; word-break: break-all; word-wrap: break-word; background-color: #f5f5f5; border: 1px solid #ccc; border-radius: 4px; } pre code { padding: 0; font-size: inherit; color: inherit; white-space: pre-wrap; background-color: transparent; border-radius: 0; } .pre-scrollable { max-height: 340px; overflow-y: scroll; } .container { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } @media (min-width: 768px) { .container { width: 750px; } } @media (min-width: 992px) { .container { width: 970px; } } @media (min-width: 1200px) { .container { width: 1170px; } } .container-fluid { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } .row { margin-right: -15px; margin-left: -15px; } .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 { position: relative; min-height: 1px; padding-right: 15px; padding-left: 15px; } .col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 { float: left; } .col-xs-12 { width: 100%; } .col-xs-11 { width: 91.66666667%; } .col-xs-10 { width: 83.33333333%; } .col-xs-9 { width: 75%; } .col-xs-8 { width: 66.66666667%; } .col-xs-7 { width: 58.33333333%; } .col-xs-6 { width: 50%; } .col-xs-5 { width: 41.66666667%; } .col-xs-4 { width: 33.33333333%; } .col-xs-3 { width: 25%; } .col-xs-2 { width: 16.66666667%; } .col-xs-1 { width: 8.33333333%; } .col-xs-pull-12 { right: 100%; } .col-xs-pull-11 { right: 91.66666667%; } .col-xs-pull-10 { right: 83.33333333%; } .col-xs-pull-9 { right: 75%; } .col-xs-pull-8 { right: 66.66666667%; } .col-xs-pull-7 { right: 58.33333333%; } .col-xs-pull-6 { right: 50%; } .col-xs-pull-5 { right: 41.66666667%; } .col-xs-pull-4 { right: 33.33333333%; } .col-xs-pull-3 { right: 25%; } .col-xs-pull-2 { right: 16.66666667%; } .col-xs-pull-1 { right: 8.33333333%; } .col-xs-pull-0 { right: auto; } .col-xs-push-12 { left: 100%; } .col-xs-push-11 { left: 91.66666667%; } .col-xs-push-10 { left: 83.33333333%; } .col-xs-push-9 { left: 75%; } .col-xs-push-8 { left: 66.66666667%; } .col-xs-push-7 { left: 58.33333333%; } .col-xs-push-6 { left: 50%; } .col-xs-push-5 { left: 41.66666667%; } .col-xs-push-4 { left: 33.33333333%; } .col-xs-push-3 { left: 25%; } .col-xs-push-2 { left: 16.66666667%; } .col-xs-push-1 { left: 8.33333333%; } .col-xs-push-0 { left: auto; } .col-xs-offset-12 { margin-left: 100%; } .col-xs-offset-11 { margin-left: 91.66666667%; } .col-xs-offset-10 { margin-left: 83.33333333%; } .col-xs-offset-9 { margin-left: 75%; } .col-xs-offset-8 { margin-left: 66.66666667%; } .col-xs-offset-7 { margin-left: 58.33333333%; } .col-xs-offset-6 { margin-left: 50%; } .col-xs-offset-5 { margin-left: 41.66666667%; } .col-xs-offset-4 { margin-left: 33.33333333%; } .col-xs-offset-3 { margin-left: 25%; } .col-xs-offset-2 { margin-left: 16.66666667%; } .col-xs-offset-1 { margin-left: 8.33333333%; } .col-xs-offset-0 { margin-left: 0; } @media (min-width: 768px) { .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 { float: left; } .col-sm-12 { width: 100%; } .col-sm-11 { width: 91.66666667%; } .col-sm-10 { width: 83.33333333%; } .col-sm-9 { width: 75%; } .col-sm-8 { width: 66.66666667%; } .col-sm-7 { width: 58.33333333%; } .col-sm-6 { width: 50%; } .col-sm-5 { width: 41.66666667%; } .col-sm-4 { width: 33.33333333%; } .col-sm-3 { width: 25%; } .col-sm-2 { width: 16.66666667%; } .col-sm-1 { width: 8.33333333%; } .col-sm-pull-12 { right: 100%; } .col-sm-pull-11 { right: 91.66666667%; } .col-sm-pull-10 { right: 83.33333333%; } .col-sm-pull-9 { right: 75%; } .col-sm-pull-8 { right: 66.66666667%; } .col-sm-pull-7 { right: 58.33333333%; } .col-sm-pull-6 { right: 50%; } .col-sm-pull-5 { right: 41.66666667%; } .col-sm-pull-4 { right: 33.33333333%; } .col-sm-pull-3 { right: 25%; } .col-sm-pull-2 { right: 16.66666667%; } .col-sm-pull-1 { right: 8.33333333%; } .col-sm-pull-0 { right: auto; } .col-sm-push-12 { left: 100%; } .col-sm-push-11 { left: 91.66666667%; } .col-sm-push-10 { left: 83.33333333%; } .col-sm-push-9 { left: 75%; } .col-sm-push-8 { left: 66.66666667%; } .col-sm-push-7 { left: 58.33333333%; } .col-sm-push-6 { left: 50%; } .col-sm-push-5 { left: 41.66666667%; } .col-sm-push-4 { left: 33.33333333%; } .col-sm-push-3 { left: 25%; } .col-sm-push-2 { left: 16.66666667%; } .col-sm-push-1 { left: 8.33333333%; } .col-sm-push-0 { left: auto; } .col-sm-offset-12 { margin-left: 100%; } .col-sm-offset-11 { margin-left: 91.66666667%; } .col-sm-offset-10 { margin-left: 83.33333333%; } .col-sm-offset-9 { margin-left: 75%; } .col-sm-offset-8 { margin-left: 66.66666667%; } .col-sm-offset-7 { margin-left: 58.33333333%; } .col-sm-offset-6 { margin-left: 50%; } .col-sm-offset-5 { margin-left: 41.66666667%; } .col-sm-offset-4 { margin-left: 33.33333333%; } .col-sm-offset-3 { margin-left: 25%; } .col-sm-offset-2 { margin-left: 16.66666667%; } .col-sm-offset-1 { margin-left: 8.33333333%; } .col-sm-offset-0 { margin-left: 0; } } @media (min-width: 992px) { .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 { float: left; } .col-md-12 { width: 100%; } .col-md-11 { width: 91.66666667%; } .col-md-10 { width: 83.33333333%; } .col-md-9 { width: 75%; } .col-md-8 { width: 66.66666667%; } .col-md-7 { width: 58.33333333%; } .col-md-6 { width: 50%; } .col-md-5 { width: 41.66666667%; } .col-md-4 { width: 33.33333333%; } .col-md-3 { width: 25%; } .col-md-2 { width: 16.66666667%; } .col-md-1 { width: 8.33333333%; } .col-md-pull-12 { right: 100%; } .col-md-pull-11 { right: 91.66666667%; } .col-md-pull-10 { right: 83.33333333%; } .col-md-pull-9 { right: 75%; } .col-md-pull-8 { right: 66.66666667%; } .col-md-pull-7 { right: 58.33333333%; } .col-md-pull-6 { right: 50%; } .col-md-pull-5 { right: 41.66666667%; } .col-md-pull-4 { right: 33.33333333%; } .col-md-pull-3 { right: 25%; } .col-md-pull-2 { right: 16.66666667%; } .col-md-pull-1 { right: 8.33333333%; } .col-md-pull-0 { right: auto; } .col-md-push-12 { left: 100%; } .col-md-push-11 { left: 91.66666667%; } .col-md-push-10 { left: 83.33333333%; } .col-md-push-9 { left: 75%; } .col-md-push-8 { left: 66.66666667%; } .col-md-push-7 { left: 58.33333333%; } .col-md-push-6 { left: 50%; } .col-md-push-5 { left: 41.66666667%; } .col-md-push-4 { left: 33.33333333%; } .col-md-push-3 { left: 25%; } .col-md-push-2 { left: 16.66666667%; } .col-md-push-1 { left: 8.33333333%; } .col-md-push-0 { left: auto; } .col-md-offset-12 { margin-left: 100%; } .col-md-offset-11 { margin-left: 91.66666667%; } .col-md-offset-10 { margin-left: 83.33333333%; } .col-md-offset-9 { margin-left: 75%; } .col-md-offset-8 { margin-left: 66.66666667%; } .col-md-offset-7 { margin-left: 58.33333333%; } .col-md-offset-6 { margin-left: 50%; } .col-md-offset-5 { margin-left: 41.66666667%; } .col-md-offset-4 { margin-left: 33.33333333%; } .col-md-offset-3 { margin-left: 25%; } .col-md-offset-2 { margin-left: 16.66666667%; } .col-md-offset-1 { margin-left: 8.33333333%; } .col-md-offset-0 { margin-left: 0; } } @media (min-width: 1200px) { .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 { float: left; } .col-lg-12 { width: 100%; } .col-lg-11 { width: 91.66666667%; } .col-lg-10 { width: 83.33333333%; } .col-lg-9 { width: 75%; } .col-lg-8 { width: 66.66666667%; } .col-lg-7 { width: 58.33333333%; } .col-lg-6 { width: 50%; } .col-lg-5 { width: 41.66666667%; } .col-lg-4 { width: 33.33333333%; } .col-lg-3 { width: 25%; } .col-lg-2 { width: 16.66666667%; } .col-lg-1 { width: 8.33333333%; } .col-lg-pull-12 { right: 100%; } .col-lg-pull-11 { right: 91.66666667%; } .col-lg-pull-10 { right: 83.33333333%; } .col-lg-pull-9 { right: 75%; } .col-lg-pull-8 { right: 66.66666667%; } .col-lg-pull-7 { right: 58.33333333%; } .col-lg-pull-6 { right: 50%; } .col-lg-pull-5 { right: 41.66666667%; } .col-lg-pull-4 { right: 33.33333333%; } .col-lg-pull-3 { right: 25%; } .col-lg-pull-2 { right: 16.66666667%; } .col-lg-pull-1 { right: 8.33333333%; } .col-lg-pull-0 { right: auto; } .col-lg-push-12 { left: 100%; } .col-lg-push-11 { left: 91.66666667%; } .col-lg-push-10 { left: 83.33333333%; } .col-lg-push-9 { left: 75%; } .col-lg-push-8 { left: 66.66666667%; } .col-lg-push-7 { left: 58.33333333%; } .col-lg-push-6 { left: 50%; } .col-lg-push-5 { left: 41.66666667%; } .col-lg-push-4 { left: 33.33333333%; } .col-lg-push-3 { left: 25%; } .col-lg-push-2 { left: 16.66666667%; } .col-lg-push-1 { left: 8.33333333%; } .col-lg-push-0 { left: auto; } .col-lg-offset-12 { margin-left: 100%; } .col-lg-offset-11 { margin-left: 91.66666667%; } .col-lg-offset-10 { margin-left: 83.33333333%; } .col-lg-offset-9 { margin-left: 75%; } .col-lg-offset-8 { margin-left: 66.66666667%; } .col-lg-offset-7 { margin-left: 58.33333333%; } .col-lg-offset-6 { margin-left: 50%; } .col-lg-offset-5 { margin-left: 41.66666667%; } .col-lg-offset-4 { margin-left: 33.33333333%; } .col-lg-offset-3 { margin-left: 25%; } .col-lg-offset-2 { margin-left: 16.66666667%; } .col-lg-offset-1 { margin-left: 8.33333333%; } .col-lg-offset-0 { margin-left: 0; } } table { background-color: transparent; } caption { padding-top: 8px; padding-bottom: 8px; color: #777; text-align: left; } th { text-align: left; } .table { width: 100%; max-width: 100%; margin-bottom: 20px; } .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td { padding: 8px; line-height: 1.42857143; vertical-align: top; border-top: 1px solid #ddd; } .table > thead > tr > th { vertical-align: bottom; border-bottom: 2px solid #ddd; } .table > caption + thead > tr:first-child > th, .table > colgroup + thead > tr:first-child > th, .table > thead:first-child > tr:first-child > th, .table > caption + thead > tr:first-child > td, .table > colgroup + thead > tr:first-child > td, .table > thead:first-child > tr:first-child > td { border-top: 0; } .table > tbody + tbody { border-top: 2px solid #ddd; } .table .table { background-color: #fff; } .table-condensed > thead > tr > th, .table-condensed > tbody > tr > th, .table-condensed > tfoot > tr > th, .table-condensed > thead > tr > td, .table-condensed > tbody > tr > td, .table-condensed > tfoot > tr > td { padding: 5px; } .table-bordered { border: 1px solid #ddd; } .table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td { border: 1px solid #ddd; } .table-bordered > thead > tr > th, .table-bordered > thead > tr > td { border-bottom-width: 2px; } .table-striped > tbody > tr:nth-of-type(odd) { background-color: #f9f9f9; } .table-hover > tbody > tr:hover { background-color: #f5f5f5; } table col[class*="col-"] { position: static; display: table-column; float: none; } table td[class*="col-"], table th[class*="col-"] { position: static; display: table-cell; float: none; } .table > thead > tr > td.active, .table > tbody > tr > td.active, .table > tfoot > tr > td.active, .table > thead > tr > th.active, .table > tbody > tr > th.active, .table > tfoot > tr > th.active, .table > thead > tr.active > td, .table > tbody > tr.active > td, .table > tfoot > tr.active > td, .table > thead > tr.active > th, .table > tbody > tr.active > th, .table > tfoot > tr.active > th { background-color: #f5f5f5; } .table-hover > tbody > tr > td.active:hover, .table-hover > tbody > tr > th.active:hover, .table-hover > tbody > tr.active:hover > td, .table-hover > tbody > tr:hover > .active, .table-hover > tbody > tr.active:hover > th { background-color: #e8e8e8; } .table > thead > tr > td.success, .table > tbody > tr > td.success, .table > tfoot > tr > td.success, .table > thead > tr > th.success, .table > tbody > tr > th.success, .table > tfoot > tr > th.success, .table > thead > tr.success > td, .table > tbody > tr.success > td, .table > tfoot > tr.success > td, .table > thead > tr.success > th, .table > tbody > tr.success > th, .table > tfoot > tr.success > th { background-color: #dff0d8; } .table-hover > tbody > tr > td.success:hover, .table-hover > tbody > tr > th.success:hover, .table-hover > tbody > tr.success:hover > td, .table-hover > tbody > tr:hover > .success, .table-hover > tbody > tr.success:hover > th { background-color: #d0e9c6; } .table > thead > tr > td.info, .table > tbody > tr > td.info, .table > tfoot > tr > td.info, .table > thead > tr > th.info, .table > tbody > tr > th.info, .table > tfoot > tr > th.info, .table > thead > tr.info > td, .table > tbody > tr.info > td, .table > tfoot > tr.info > td, .table > thead > tr.info > th, .table > tbody > tr.info > th, .table > tfoot > tr.info > th { background-color: #d9edf7; } .table-hover > tbody > tr > td.info:hover, .table-hover > tbody > tr > th.info:hover, .table-hover > tbody > tr.info:hover > td, .table-hover > tbody > tr:hover > .info, .table-hover > tbody > tr.info:hover > th { background-color: #c4e3f3; } .table > thead > tr > td.warning, .table > tbody > tr > td.warning, .table > tfoot > tr > td.warning, .table > thead > tr > th.warning, .table > tbody > tr > th.warning, .table > tfoot > tr > th.warning, .table > thead > tr.warning > td, .table > tbody > tr.warning > td, .table > tfoot > tr.warning > td, .table > thead > tr.warning > th, .table > tbody > tr.warning > th, .table > tfoot > tr.warning > th { background-color: #fcf8e3; } .table-hover > tbody > tr > td.warning:hover, .table-hover > tbody > tr > th.warning:hover, .table-hover > tbody > tr.warning:hover > td, .table-hover > tbody > tr:hover > .warning, .table-hover > tbody > tr.warning:hover > th { background-color: #faf2cc; } .table > thead > tr > td.danger, .table > tbody > tr > td.danger, .table > tfoot > tr > td.danger, .table > thead > tr > th.danger, .table > tbody > tr > th.danger, .table > tfoot > tr > th.danger, .table > thead > tr.danger > td, .table > tbody > tr.danger > td, .table > tfoot > tr.danger > td, .table > thead > tr.danger > th, .table > tbody > tr.danger > th, .table > tfoot > tr.danger > th { background-color: #f2dede; } .table-hover > tbody > tr > td.danger:hover, .table-hover > tbody > tr > th.danger:hover, .table-hover > tbody > tr.danger:hover > td, .table-hover > tbody > tr:hover > .danger, .table-hover > tbody > tr.danger:hover > th { background-color: #ebcccc; } .table-responsive { min-height: .01%; overflow-x: auto; } @media screen and (max-width: 767px) { .table-responsive { width: 100%; margin-bottom: 15px; overflow-y: hidden; -ms-overflow-style: -ms-autohiding-scrollbar; border: 1px solid #ddd; } .table-responsive > .table { margin-bottom: 0; } .table-responsive > .table > thead > tr > th, .table-responsive > .table > tbody > tr > th, .table-responsive > .table > tfoot > tr > th, .table-responsive > .table > thead > tr > td, .table-responsive > .table > tbody > tr > td, .table-responsive > .table > tfoot > tr > td { white-space: nowrap; } .table-responsive > .table-bordered { border: 0; } .table-responsive > .table-bordered > thead > tr > th:first-child, .table-responsive > .table-bordered > tbody > tr > th:first-child, .table-responsive > .table-bordered > tfoot > tr > th:first-child, .table-responsive > .table-bordered > thead > tr > td:first-child, .table-responsive > .table-bordered > tbody > tr > td:first-child, .table-responsive > .table-bordered > tfoot > tr > td:first-child { border-left: 0; } .table-responsive > .table-bordered > thead > tr > th:last-child, .table-responsive > .table-bordered > tbody > tr > th:last-child, .table-responsive > .table-bordered > tfoot > tr > th:last-child, .table-responsive > .table-bordered > thead > tr > td:last-child, .table-responsive > .table-bordered > tbody > tr > td:last-child, .table-responsive > .table-bordered > tfoot > tr > td:last-child { border-right: 0; } .table-responsive > .table-bordered > tbody > tr:last-child > th, .table-responsive > .table-bordered > tfoot > tr:last-child > th, .table-responsive > .table-bordered > tbody > tr:last-child > td, .table-responsive > .table-bordered > tfoot > tr:last-child > td { border-bottom: 0; } } fieldset { min-width: 0; padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: 20px; font-size: 21px; line-height: inherit; color: #333; border: 0; border-bottom: 1px solid #e5e5e5; } label { display: inline-block; max-width: 100%; margin-bottom: 5px; font-weight: bold; } input[type="search"] { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } input[type="radio"], input[type="checkbox"] { margin: 4px 0 0; margin-top: 1px \9; line-height: normal; } input[type="file"] { display: block; } input[type="range"] { display: block; width: 100%; } select[multiple], select[size] { height: auto; } input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } output { display: block; padding-top: 7px; font-size: 14px; line-height: 1.42857143; color: #555; } .form-control { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; color: #555; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s; -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; } .form-control:focus { border-color: #66afe9; outline: 0; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); } .form-control::-moz-placeholder { color: #999; opacity: 1; } .form-control:-ms-input-placeholder { color: #999; } .form-control::-webkit-input-placeholder { color: #999; } .form-control[disabled], .form-control[readonly], fieldset[disabled] .form-control { cursor: not-allowed; background-color: #eee; opacity: 1; } textarea.form-control { height: auto; } input[type="search"] { -webkit-appearance: none; } @media screen and (-webkit-min-device-pixel-ratio: 0) { input[type="date"], input[type="time"], input[type="datetime-local"], input[type="month"] { line-height: 34px; } input[type="date"].input-sm, input[type="time"].input-sm, input[type="datetime-local"].input-sm, input[type="month"].input-sm, .input-group-sm input[type="date"], .input-group-sm input[type="time"], .input-group-sm input[type="datetime-local"], .input-group-sm input[type="month"] { line-height: 30px; } input[type="date"].input-lg, input[type="time"].input-lg, input[type="datetime-local"].input-lg, input[type="month"].input-lg, .input-group-lg input[type="date"], .input-group-lg input[type="time"], .input-group-lg input[type="datetime-local"], .input-group-lg input[type="month"] { line-height: 46px; } } .form-group { margin-bottom: 15px; } .radio, .checkbox { position: relative; display: block; margin-top: 10px; margin-bottom: 10px; } .radio label, .checkbox label { min-height: 20px; padding-left: 20px; margin-bottom: 0; font-weight: normal; cursor: pointer; } .radio input[type="radio"], .radio-inline input[type="radio"], .checkbox input[type="checkbox"], .checkbox-inline input[type="checkbox"] { position: absolute; margin-top: 4px \9; margin-left: -20px; } .radio + .radio, .checkbox + .checkbox { margin-top: -5px; } .radio-inline, .checkbox-inline { display: inline-block; padding-left: 20px; margin-bottom: 0; font-weight: normal; vertical-align: middle; cursor: pointer; } .radio-inline + .radio-inline, .checkbox-inline + .checkbox-inline { margin-top: 0; margin-left: 10px; } input[type="radio"][disabled], input[type="checkbox"][disabled], input[type="radio"].disabled, input[type="checkbox"].disabled, fieldset[disabled] input[type="radio"], fieldset[disabled] input[type="checkbox"] { cursor: not-allowed; } .radio-inline.disabled, .checkbox-inline.disabled, fieldset[disabled] .radio-inline, fieldset[disabled] .checkbox-inline { cursor: not-allowed; } .radio.disabled label, .checkbox.disabled label, fieldset[disabled] .radio label, fieldset[disabled] .checkbox label { cursor: not-allowed; } .form-control-static { padding-top: 7px; padding-bottom: 7px; margin-bottom: 0; } .form-control-static.input-lg, .form-control-static.input-sm { padding-right: 0; padding-left: 0; } .input-sm { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } select.input-sm { height: 30px; line-height: 30px; } textarea.input-sm, select[multiple].input-sm { height: auto; } .form-group-sm .form-control { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } select.form-group-sm .form-control { height: 30px; line-height: 30px; } textarea.form-group-sm .form-control, select[multiple].form-group-sm .form-control { height: auto; } .form-group-sm .form-control-static { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; } .input-lg { height: 46px; padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } select.input-lg { height: 46px; line-height: 46px; } textarea.input-lg, select[multiple].input-lg { height: auto; } .form-group-lg .form-control { height: 46px; padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } select.form-group-lg .form-control { height: 46px; line-height: 46px; } textarea.form-group-lg .form-control, select[multiple].form-group-lg .form-control { height: auto; } .form-group-lg .form-control-static { height: 46px; padding: 10px 16px; font-size: 18px; line-height: 1.3333333; } .has-feedback { position: relative; } .has-feedback .form-control { padding-right: 42.5px; } .form-control-feedback { position: absolute; top: 0; right: 0; z-index: 2; display: block; width: 34px; height: 34px; line-height: 34px; text-align: center; pointer-events: none; } .input-lg + .form-control-feedback { width: 46px; height: 46px; line-height: 46px; } .input-sm + .form-control-feedback { width: 30px; height: 30px; line-height: 30px; } .has-success .help-block, .has-success .control-label, .has-success .radio, .has-success .checkbox, .has-success .radio-inline, .has-success .checkbox-inline, .has-success.radio label, .has-success.checkbox label, .has-success.radio-inline label, .has-success.checkbox-inline label { color: #3c763d; } .has-success .form-control { border-color: #3c763d; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); } .has-success .form-control:focus { border-color: #2b542c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; } .has-success .input-group-addon { color: #3c763d; background-color: #dff0d8; border-color: #3c763d; } .has-success .form-control-feedback { color: #3c763d; } .has-warning .help-block, .has-warning .control-label, .has-warning .radio, .has-warning .checkbox, .has-warning .radio-inline, .has-warning .checkbox-inline, .has-warning.radio label, .has-warning.checkbox label, .has-warning.radio-inline label, .has-warning.checkbox-inline label { color: #8a6d3b; } .has-warning .form-control { border-color: #8a6d3b; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); } .has-warning .form-control:focus { border-color: #66512c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; } .has-warning .input-group-addon { color: #8a6d3b; background-color: #fcf8e3; border-color: #8a6d3b; } .has-warning .form-control-feedback { color: #8a6d3b; } .has-error .help-block, .has-error .control-label, .has-error .radio, .has-error .checkbox, .has-error .radio-inline, .has-error .checkbox-inline, .has-error.radio label, .has-error.checkbox label, .has-error.radio-inline label, .has-error.checkbox-inline label { color: #a94442; } .has-error .form-control { border-color: #a94442; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); } .has-error .form-control:focus { border-color: #843534; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; } .has-error .input-group-addon { color: #a94442; background-color: #f2dede; border-color: #a94442; } .has-error .form-control-feedback { color: #a94442; } .has-feedback label ~ .form-control-feedback { top: 25px; } .has-feedback label.sr-only ~ .form-control-feedback { top: 0; } .help-block { display: block; margin-top: 5px; margin-bottom: 10px; color: #737373; } @media (min-width: 768px) { .form-inline .form-group { display: inline-block; margin-bottom: 0; vertical-align: middle; } .form-inline .form-control { display: inline-block; width: auto; vertical-align: middle; } .form-inline .form-control-static { display: inline-block; } .form-inline .input-group { display: inline-table; vertical-align: middle; } .form-inline .input-group .input-group-addon, .form-inline .input-group .input-group-btn, .form-inline .input-group .form-control { width: auto; } .form-inline .input-group > .form-control { width: 100%; } .form-inline .control-label { margin-bottom: 0; vertical-align: middle; } .form-inline .radio, .form-inline .checkbox { display: inline-block; margin-top: 0; margin-bottom: 0; vertical-align: middle; } .form-inline .radio label, .form-inline .checkbox label { padding-left: 0; } .form-inline .radio input[type="radio"], .form-inline .checkbox input[type="checkbox"] { position: relative; margin-left: 0; } .form-inline .has-feedback .form-control-feedback { top: 0; } } .form-horizontal .radio, .form-horizontal .checkbox, .form-horizontal .radio-inline, .form-horizontal .checkbox-inline { padding-top: 7px; margin-top: 0; margin-bottom: 0; } .form-horizontal .radio, .form-horizontal .checkbox { min-height: 27px; } .form-horizontal .form-group { margin-right: -15px; margin-left: -15px; } @media (min-width: 768px) { .form-horizontal .control-label { padding-top: 7px; margin-bottom: 0; text-align: right; } } .form-horizontal .has-feedback .form-control-feedback { right: 15px; } @media (min-width: 768px) { .form-horizontal .form-group-lg .control-label { padding-top: 14.333333px; } } @media (min-width: 768px) { .form-horizontal .form-group-sm .control-label { padding-top: 6px; } } .btn { display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 4px; } .btn:focus, .btn:active:focus, .btn.active:focus, .btn.focus, .btn:active.focus, .btn.active.focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .btn:hover, .btn:focus, .btn.focus { color: #333; text-decoration: none; } .btn:active, .btn.active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); } .btn.disabled, .btn[disabled], fieldset[disabled] .btn { pointer-events: none; cursor: not-allowed; filter: alpha(opacity=65); -webkit-box-shadow: none; box-shadow: none; opacity: .65; } .btn-default { color: #333; background-color: #fff; border-color: #ccc; } .btn-default:hover, .btn-default:focus, .btn-default.focus, .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { color: #333; background-color: #e6e6e6; border-color: #adadad; } .btn-default:active, .btn-default.active, .open > .dropdown-toggle.btn-default { background-image: none; } .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, .btn-default.disabled:hover, .btn-default[disabled]:hover, fieldset[disabled] .btn-default:hover, .btn-default.disabled:focus, .btn-default[disabled]:focus, fieldset[disabled] .btn-default:focus, .btn-default.disabled.focus, .btn-default[disabled].focus, fieldset[disabled] .btn-default.focus, .btn-default.disabled:active, .btn-default[disabled]:active, fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { background-color: #fff; border-color: #ccc; } .btn-default .badge { color: #fff; background-color: #333; } .btn-primary { color: #fff; background-color: #337ab7; border-color: #2e6da4; } .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { color: #fff; background-color: #286090; border-color: #204d74; } .btn-primary:active, .btn-primary.active, .open > .dropdown-toggle.btn-primary { background-image: none; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled.focus, .btn-primary[disabled].focus, fieldset[disabled] .btn-primary.focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { background-color: #337ab7; border-color: #2e6da4; } .btn-primary .badge { color: #337ab7; background-color: #fff; } .btn-success { color: #fff; background-color: #5cb85c; border-color: #4cae4c; } .btn-success:hover, .btn-success:focus, .btn-success.focus, .btn-success:active, .btn-success.active, .open > .dropdown-toggle.btn-success { color: #fff; background-color: #449d44; border-color: #398439; } .btn-success:active, .btn-success.active, .open > .dropdown-toggle.btn-success { background-image: none; } .btn-success.disabled, .btn-success[disabled], fieldset[disabled] .btn-success, .btn-success.disabled:hover, .btn-success[disabled]:hover, fieldset[disabled] .btn-success:hover, .btn-success.disabled:focus, .btn-success[disabled]:focus, fieldset[disabled] .btn-success:focus, .btn-success.disabled.focus, .btn-success[disabled].focus, fieldset[disabled] .btn-success.focus, .btn-success.disabled:active, .btn-success[disabled]:active, fieldset[disabled] .btn-success:active, .btn-success.disabled.active, .btn-success[disabled].active, fieldset[disabled] .btn-success.active { background-color: #5cb85c; border-color: #4cae4c; } .btn-success .badge { color: #5cb85c; background-color: #fff; } .btn-info { color: #fff; background-color: #5bc0de; border-color: #46b8da; } .btn-info:hover, .btn-info:focus, .btn-info.focus, .btn-info:active, .btn-info.active, .open > .dropdown-toggle.btn-info { color: #fff; background-color: #31b0d5; border-color: #269abc; } .btn-info:active, .btn-info.active, .open > .dropdown-toggle.btn-info { background-image: none; } .btn-info.disabled, .btn-info[disabled], fieldset[disabled] .btn-info, .btn-info.disabled:hover, .btn-info[disabled]:hover, fieldset[disabled] .btn-info:hover, .btn-info.disabled:focus, .btn-info[disabled]:focus, fieldset[disabled] .btn-info:focus, .btn-info.disabled.focus, .btn-info[disabled].focus, fieldset[disabled] .btn-info.focus, .btn-info.disabled:active, .btn-info[disabled]:active, fieldset[disabled] .btn-info:active, .btn-info.disabled.active, .btn-info[disabled].active, fieldset[disabled] .btn-info.active { background-color: #5bc0de; border-color: #46b8da; } .btn-info .badge { color: #5bc0de; background-color: #fff; } .btn-warning { color: #fff; background-color: #f0ad4e; border-color: #eea236; } .btn-warning:hover, .btn-warning:focus, .btn-warning.focus, .btn-warning:active, .btn-warning.active, .open > .dropdown-toggle.btn-warning { color: #fff; background-color: #ec971f; border-color: #d58512; } .btn-warning:active, .btn-warning.active, .open > .dropdown-toggle.btn-warning { background-image: none; } .btn-warning.disabled, .btn-warning[disabled], fieldset[disabled] .btn-warning, .btn-warning.disabled:hover, .btn-warning[disabled]:hover, fieldset[disabled] .btn-warning:hover, .btn-warning.disabled:focus, .btn-warning[disabled]:focus, fieldset[disabled] .btn-warning:focus, .btn-warning.disabled.focus, .btn-warning[disabled].focus, fieldset[disabled] .btn-warning.focus, .btn-warning.disabled:active, .btn-warning[disabled]:active, fieldset[disabled] .btn-warning:active, .btn-warning.disabled.active, .btn-warning[disabled].active, fieldset[disabled] .btn-warning.active { background-color: #f0ad4e; border-color: #eea236; } .btn-warning .badge { color: #f0ad4e; background-color: #fff; } .btn-danger { color: #fff; background-color: #d9534f; border-color: #d43f3a; } .btn-danger:hover, .btn-danger:focus, .btn-danger.focus, .btn-danger:active, .btn-danger.active, .open > .dropdown-toggle.btn-danger { color: #fff; background-color: #c9302c; border-color: #ac2925; } .btn-danger:active, .btn-danger.active, .open > .dropdown-toggle.btn-danger { background-image: none; } .btn-danger.disabled, .btn-danger[disabled], fieldset[disabled] .btn-danger, .btn-danger.disabled:hover, .btn-danger[disabled]:hover, fieldset[disabled] .btn-danger:hover, .btn-danger.disabled:focus, .btn-danger[disabled]:focus, fieldset[disabled] .btn-danger:focus, .btn-danger.disabled.focus, .btn-danger[disabled].focus, fieldset[disabled] .btn-danger.focus, .btn-danger.disabled:active, .btn-danger[disabled]:active, fieldset[disabled] .btn-danger:active, .btn-danger.disabled.active, .btn-danger[disabled].active, fieldset[disabled] .btn-danger.active { background-color: #d9534f; border-color: #d43f3a; } .btn-danger .badge { color: #d9534f; background-color: #fff; } .btn-link { font-weight: normal; color: #337ab7; border-radius: 0; } .btn-link, .btn-link:active, .btn-link.active, .btn-link[disabled], fieldset[disabled] .btn-link { background-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .btn-link, .btn-link:hover, .btn-link:focus, .btn-link:active { border-color: transparent; } .btn-link:hover, .btn-link:focus { color: #23527c; text-decoration: underline; background-color: transparent; } .btn-link[disabled]:hover, fieldset[disabled] .btn-link:hover, .btn-link[disabled]:focus, fieldset[disabled] .btn-link:focus { color: #777; text-decoration: none; } .btn-lg, .btn-group-lg > .btn { padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } .btn-sm, .btn-group-sm > .btn { padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .btn-xs, .btn-group-xs > .btn { padding: 1px 5px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .btn-block { display: block; width: 100%; } .btn-block + .btn-block { margin-top: 5px; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .fade { opacity: 0; -webkit-transition: opacity .15s linear; -o-transition: opacity .15s linear; transition: opacity .15s linear; } .fade.in { opacity: 1; } .collapse { display: none; visibility: hidden; } .collapse.in { display: block; visibility: visible; } tr.collapse.in { display: table-row; } tbody.collapse.in { display: table-row-group; } .collapsing { position: relative; height: 0; overflow: hidden; -webkit-transition-timing-function: ease; -o-transition-timing-function: ease; transition-timing-function: ease; -webkit-transition-duration: .35s; -o-transition-duration: .35s; transition-duration: .35s; -webkit-transition-property: height, visibility; -o-transition-property: height, visibility; transition-property: height, visibility; } .caret { display: inline-block; width: 0; height: 0; margin-left: 2px; vertical-align: middle; border-top: 4px solid; border-right: 4px solid transparent; border-left: 4px solid transparent; } .dropup, .dropdown { position: relative; } .dropdown-toggle:focus { outline: 0; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; font-size: 14px; text-align: left; list-style: none; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, .15); border-radius: 4px; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); box-shadow: 0 6px 12px rgba(0, 0, 0, .175); } .dropdown-menu.pull-right { right: 0; left: auto; } .dropdown-menu .divider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; } .dropdown-menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: 1.42857143; color: #333; white-space: nowrap; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { color: #262626; text-decoration: none; background-color: #f5f5f5; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: #fff; text-decoration: none; background-color: #337ab7; outline: 0; } .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: #777; } .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; cursor: not-allowed; background-color: transparent; background-image: none; filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .open > .dropdown-menu { display: block; } .open > a { outline: 0; } .dropdown-menu-right { right: 0; left: auto; } .dropdown-menu-left { right: auto; left: 0; } .dropdown-header { display: block; padding: 3px 20px; font-size: 12px; line-height: 1.42857143; color: #777; white-space: nowrap; } .dropdown-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 990; } .pull-right > .dropdown-menu { right: 0; left: auto; } .dropup .caret, .navbar-fixed-bottom .dropdown .caret { content: ""; border-top: 0; border-bottom: 4px solid; } .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 2px; } @media (min-width: 768px) { .navbar-right .dropdown-menu { right: 0; left: auto; } .navbar-right .dropdown-menu-left { right: auto; left: 0; } } .btn-group, .btn-group-vertical { position: relative; display: inline-block; vertical-align: middle; } .btn-group > .btn, .btn-group-vertical > .btn { position: relative; float: left; } .btn-group > .btn:hover, .btn-group-vertical > .btn:hover, .btn-group > .btn:focus, .btn-group-vertical > .btn:focus, .btn-group > .btn:active, .btn-group-vertical > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn.active { z-index: 2; } .btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group { margin-left: -1px; } .btn-toolbar { margin-left: -5px; } .btn-toolbar .btn-group, .btn-toolbar .input-group { float: left; } .btn-toolbar > .btn, .btn-toolbar > .btn-group, .btn-toolbar > .input-group { margin-left: 5px; } .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; } .btn-group > .btn:first-child { margin-left: 0; } .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { border-top-right-radius: 0; border-bottom-right-radius: 0; } .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { border-top-left-radius: 0; border-bottom-left-radius: 0; } .btn-group > .btn-group { float: left; } .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-top-right-radius: 0; border-bottom-right-radius: 0; } .btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { border-top-left-radius: 0; border-bottom-left-radius: 0; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn-group > .btn + .dropdown-toggle { padding-right: 8px; padding-left: 8px; } .btn-group > .btn-lg + .dropdown-toggle { padding-right: 12px; padding-left: 12px; } .btn-group.open .dropdown-toggle { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); } .btn-group.open .dropdown-toggle.btn-link { -webkit-box-shadow: none; box-shadow: none; } .btn .caret { margin-left: 0; } .btn-lg .caret { border-width: 5px 5px 0; border-bottom-width: 0; } .dropup .btn-lg .caret { border-width: 0 5px 5px; } .btn-group-vertical > .btn, .btn-group-vertical > .btn-group, .btn-group-vertical > .btn-group > .btn { display: block; float: none; width: 100%; max-width: 100%; } .btn-group-vertical > .btn-group > .btn { float: none; } .btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { margin-top: -1px; margin-left: 0; } .btn-group-vertical > .btn:not(:first-child):not(:last-child) { border-radius: 0; } .btn-group-vertical > .btn:first-child:not(:last-child) { border-top-right-radius: 4px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn:last-child:not(:first-child) { border-top-left-radius: 0; border-top-right-radius: 0; border-bottom-left-radius: 4px; } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { border-top-left-radius: 0; border-top-right-radius: 0; } .btn-group-justified { display: table; width: 100%; table-layout: fixed; border-collapse: separate; } .btn-group-justified > .btn, .btn-group-justified > .btn-group { display: table-cell; float: none; width: 1%; } .btn-group-justified > .btn-group .btn { width: 100%; } .btn-group-justified > .btn-group .dropdown-menu { left: auto; } [data-toggle="buttons"] > .btn input[type="radio"], [data-toggle="buttons"] > .btn-group > .btn input[type="radio"], [data-toggle="buttons"] > .btn input[type="checkbox"], [data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { position: absolute; clip: rect(0, 0, 0, 0); pointer-events: none; } .input-group { position: relative; display: table; border-collapse: separate; } .input-group[class*="col-"] { float: none; padding-right: 0; padding-left: 0; } .input-group .form-control { position: relative; z-index: 2; float: left; width: 100%; margin-bottom: 0; } .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { height: 46px; padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px; } select.input-group-lg > .form-control, select.input-group-lg > .input-group-addon, select.input-group-lg > .input-group-btn > .btn { height: 46px; line-height: 46px; } textarea.input-group-lg > .form-control, textarea.input-group-lg > .input-group-addon, textarea.input-group-lg > .input-group-btn > .btn, select[multiple].input-group-lg > .form-control, select[multiple].input-group-lg > .input-group-addon, select[multiple].input-group-lg > .input-group-btn > .btn { height: auto; } .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } select.input-group-sm > .form-control, select.input-group-sm > .input-group-addon, select.input-group-sm > .input-group-btn > .btn { height: 30px; line-height: 30px; } textarea.input-group-sm > .form-control, textarea.input-group-sm > .input-group-addon, textarea.input-group-sm > .input-group-btn > .btn, select[multiple].input-group-sm > .form-control, select[multiple].input-group-sm > .input-group-addon, select[multiple].input-group-sm > .input-group-btn > .btn { height: auto; } .input-group-addon, .input-group-btn, .input-group .form-control { display: table-cell; } .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child), .input-group .form-control:not(:first-child):not(:last-child) { border-radius: 0; } .input-group-addon, .input-group-btn { width: 1%; white-space: nowrap; vertical-align: middle; } .input-group-addon { padding: 6px 12px; font-size: 14px; font-weight: normal; line-height: 1; color: #555; text-align: center; background-color: #eee; border: 1px solid #ccc; border-radius: 4px; } .input-group-addon.input-sm { padding: 5px 10px; font-size: 12px; border-radius: 3px; } .input-group-addon.input-lg { padding: 10px 16px; font-size: 18px; border-radius: 6px; } .input-group-addon input[type="radio"], .input-group-addon input[type="checkbox"] { margin-top: 0; } .input-group .form-control:first-child, .input-group-addon:first-child, .input-group-btn:first-child > .btn, .input-group-btn:first-child > .btn-group > .btn, .input-group-btn:first-child > .dropdown-toggle, .input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle), .input-group-btn:last-child > .btn-group:not(:last-child) > .btn { border-top-right-radius: 0; border-bottom-right-radius: 0; } .input-group-addon:first-child { border-right: 0; } .input-group .form-control:last-child, .input-group-addon:last-child, .input-group-btn:last-child > .btn, .input-group-btn:last-child > .btn-group > .btn, .input-group-btn:last-child > .dropdown-toggle, .input-group-btn:first-child > .btn:not(:first-child), .input-group-btn:first-child > .btn-group:not(:first-child) > .btn { border-top-left-radius: 0; border-bottom-left-radius: 0; } .input-group-addon:last-child { border-left: 0; } .input-group-btn { position: relative; font-size: 0; white-space: nowrap; } .input-group-btn > .btn { position: relative; } .input-group-btn > .btn + .btn { margin-left: -1px; } .input-group-btn > .btn:hover, .input-group-btn > .btn:focus, .input-group-btn > .btn:active { z-index: 2; } .input-group-btn:first-child > .btn, .input-group-btn:first-child > .btn-group { margin-right: -1px; } .input-group-btn:last-child > .btn, .input-group-btn:last-child > .btn-group { margin-left: -1px; } .nav { padding-left: 0; margin-bottom: 0; list-style: none; } .nav > li { position: relative; display: block; } .nav > li > a { position: relative; display: block; padding: 10px 15px; } .nav > li > a:hover, .nav > li > a:focus { text-decoration: none; background-color: #eee; } .nav > li.disabled > a { color: #777; } .nav > li.disabled > a:hover, .nav > li.disabled > a:focus { color: #777; text-decoration: none; cursor: not-allowed; background-color: transparent; } .nav .open > a, .nav .open > a:hover, .nav .open > a:focus { background-color: #eee; border-color: #337ab7; } .nav .nav-divider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; } .nav > li > a > img { max-width: none; } .nav-tabs { border-bottom: 1px solid #ddd; } .nav-tabs > li { float: left; margin-bottom: -1px; } .nav-tabs > li > a { margin-right: 2px; line-height: 1.42857143; border: 1px solid transparent; border-radius: 4px 4px 0 0; } .nav-tabs > li > a:hover { border-color: #eee #eee #ddd; } .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus { color: #555; cursor: default; background-color: #fff; border: 1px solid #ddd; border-bottom-color: transparent; } .nav-tabs.nav-justified { width: 100%; border-bottom: 0; } .nav-tabs.nav-justified > li { float: none; } .nav-tabs.nav-justified > li > a { margin-bottom: 5px; text-align: center; } .nav-tabs.nav-justified > .dropdown .dropdown-menu { top: auto; left: auto; } @media (min-width: 768px) { .nav-tabs.nav-justified > li { display: table-cell; width: 1%; } .nav-tabs.nav-justified > li > a { margin-bottom: 0; } } .nav-tabs.nav-justified > li > a { margin-right: 0; border-radius: 4px; } .nav-tabs.nav-justified > .active > a, .nav-tabs.nav-justified > .active > a:hover, .nav-tabs.nav-justified > .active > a:focus { border: 1px solid #ddd; } @media (min-width: 768px) { .nav-tabs.nav-justified > li > a { border-bottom: 1px solid #ddd; border-radius: 4px 4px 0 0; } .nav-tabs.nav-justified > .active > a, .nav-tabs.nav-justified > .active > a:hover, .nav-tabs.nav-justified > .active > a:focus { border-bottom-color: #fff; } } .nav-pills > li { float: left; } .nav-pills > li > a { border-radius: 4px; } .nav-pills > li + li { margin-left: 2px; } .nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus { color: #fff; background-color: #337ab7; } .nav-stacked > li { float: none; } .nav-stacked > li + li { margin-top: 2px; margin-left: 0; } .nav-justified { width: 100%; } .nav-justified > li { float: none; } .nav-justified > li > a { margin-bottom: 5px; text-align: center; } .nav-justified > .dropdown .dropdown-menu { top: auto; left: auto; } @media (min-width: 768px) { .nav-justified > li { display: table-cell; width: 1%; } .nav-justified > li > a { margin-bottom: 0; } } .nav-tabs-justified { border-bottom: 0; } .nav-tabs-justified > li > a { margin-right: 0; border-radius: 4px; } .nav-tabs-justified > .active > a, .nav-tabs-justified > .active > a:hover, .nav-tabs-justified > .active > a:focus { border: 1px solid #ddd; } @media (min-width: 768px) { .nav-tabs-justified > li > a { border-bottom: 1px solid #ddd; border-radius: 4px 4px 0 0; } .nav-tabs-justified > .active > a, .nav-tabs-justified > .active > a:hover, .nav-tabs-justified > .active > a:focus { border-bottom-color: #fff; } } .tab-content > .tab-pane { display: none; visibility: hidden; } .tab-content > .active { display: block; visibility: visible; } .nav-tabs .dropdown-menu { margin-top: -1px; border-top-left-radius: 0; border-top-right-radius: 0; } .navbar { position: relative; min-height: 50px; margin-bottom: 20px; border: 1px solid transparent; } @media (min-width: 768px) { .navbar { border-radius: 4px; } } @media (min-width: 768px) { .navbar-header { float: left; } } .navbar-collapse { padding-right: 15px; padding-left: 15px; overflow-x: visible; -webkit-overflow-scrolling: touch; border-top: 1px solid transparent; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); } .navbar-collapse.in { overflow-y: auto; } @media (min-width: 768px) { .navbar-collapse { width: auto; border-top: 0; -webkit-box-shadow: none; box-shadow: none; } .navbar-collapse.collapse { display: block !important; height: auto !important; padding-bottom: 0; overflow: visible !important; visibility: visible !important; } .navbar-collapse.in { overflow-y: visible; } .navbar-fixed-top .navbar-collapse, .navbar-static-top .navbar-collapse, .navbar-fixed-bottom .navbar-collapse { padding-right: 0; padding-left: 0; } } .navbar-fixed-top .navbar-collapse, .navbar-fixed-bottom .navbar-collapse { max-height: 340px; } @media (max-device-width: 480px) and (orientation: landscape) { .navbar-fixed-top .navbar-collapse, .navbar-fixed-bottom .navbar-collapse { max-height: 200px; } } .container > .navbar-header, .container-fluid > .navbar-header, .container > .navbar-collapse, .container-fluid > .navbar-collapse { margin-right: -15px; margin-left: -15px; } @media (min-width: 768px) { .container > .navbar-header, .container-fluid > .navbar-header, .container > .navbar-collapse, .container-fluid > .navbar-collapse { margin-right: 0; margin-left: 0; } } .navbar-static-top { z-index: 1000; border-width: 0 0 1px; } @media (min-width: 768px) { .navbar-static-top { border-radius: 0; } } .navbar-fixed-top, .navbar-fixed-bottom { position: fixed; right: 0; left: 0; z-index: 1030; } @media (min-width: 768px) { .navbar-fixed-top, .navbar-fixed-bottom { border-radius: 0; } } .navbar-fixed-top { top: 0; border-width: 0 0 1px; } .navbar-fixed-bottom { bottom: 0; margin-bottom: 0; border-width: 1px 0 0; } .navbar-brand { float: left; height: 50px; padding: 15px 15px; font-size: 18px; line-height: 20px; } .navbar-brand:hover, .navbar-brand:focus { text-decoration: none; } .navbar-brand > img { display: block; } @media (min-width: 768px) { .navbar > .container .navbar-brand, .navbar > .container-fluid .navbar-brand { margin-left: -15px; } } .navbar-toggle { position: relative; float: right; padding: 9px 10px; margin-top: 8px; margin-right: 15px; margin-bottom: 8px; background-color: transparent; background-image: none; border: 1px solid transparent; border-radius: 4px; } .navbar-toggle:focus { outline: 0; } .navbar-toggle .icon-bar { display: block; width: 22px; height: 2px; border-radius: 1px; } .navbar-toggle .icon-bar + .icon-bar { margin-top: 4px; } @media (min-width: 768px) { .navbar-toggle { display: none; } } .navbar-nav { margin: 7.5px -15px; } .navbar-nav > li > a { padding-top: 10px; padding-bottom: 10px; line-height: 20px; } @media (max-width: 767px) { .navbar-nav .open .dropdown-menu { position: static; float: none; width: auto; margin-top: 0; background-color: transparent; border: 0; -webkit-box-shadow: none; box-shadow: none; } .navbar-nav .open .dropdown-menu > li > a, .navbar-nav .open .dropdown-menu .dropdown-header { padding: 5px 15px 5px 25px; } .navbar-nav .open .dropdown-menu > li > a { line-height: 20px; } .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-nav .open .dropdown-menu > li > a:focus { background-image: none; } } @media (min-width: 768px) { .navbar-nav { float: left; margin: 0; } .navbar-nav > li { float: left; } .navbar-nav > li > a { padding-top: 15px; padding-bottom: 15px; } } .navbar-form { padding: 10px 15px; margin-top: 8px; margin-right: -15px; margin-bottom: 8px; margin-left: -15px; border-top: 1px solid transparent; border-bottom: 1px solid transparent; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); } @media (min-width: 768px) { .navbar-form .form-group { display: inline-block; margin-bottom: 0; vertical-align: middle; } .navbar-form .form-control { display: inline-block; width: auto; vertical-align: middle; } .navbar-form .form-control-static { display: inline-block; } .navbar-form .input-group { display: inline-table; vertical-align: middle; } .navbar-form .input-group .input-group-addon, .navbar-form .input-group .input-group-btn, .navbar-form .input-group .form-control { width: auto; } .navbar-form .input-group > .form-control { width: 100%; } .navbar-form .control-label { margin-bottom: 0; vertical-align: middle; } .navbar-form .radio, .navbar-form .checkbox { display: inline-block; margin-top: 0; margin-bottom: 0; vertical-align: middle; } .navbar-form .radio label, .navbar-form .checkbox label { padding-left: 0; } .navbar-form .radio input[type="radio"], .navbar-form .checkbox input[type="checkbox"] { position: relative; margin-left: 0; } .navbar-form .has-feedback .form-control-feedback { top: 0; } } @media (max-width: 767px) { .navbar-form .form-group { margin-bottom: 5px; } .navbar-form .form-group:last-child { margin-bottom: 0; } } @media (min-width: 768px) { .navbar-form { width: auto; padding-top: 0; padding-bottom: 0; margin-right: 0; margin-left: 0; border: 0; -webkit-box-shadow: none; box-shadow: none; } } .navbar-nav > li > .dropdown-menu { margin-top: 0; border-top-left-radius: 0; border-top-right-radius: 0; } .navbar-fixed-bottom .navbar-nav > li > .dropdown-menu { margin-bottom: 0; border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .navbar-btn { margin-top: 8px; margin-bottom: 8px; } .navbar-btn.btn-sm { margin-top: 10px; margin-bottom: 10px; } .navbar-btn.btn-xs { margin-top: 14px; margin-bottom: 14px; } .navbar-text { margin-top: 15px; margin-bottom: 15px; } @media (min-width: 768px) { .navbar-text { float: left; margin-right: 15px; margin-left: 15px; } } @media (min-width: 768px) { .navbar-left { float: left !important; } .navbar-right { float: right !important; margin-right: -15px; } .navbar-right ~ .navbar-right { margin-right: 0; } } .navbar-default { background-color: #f8f8f8; border-color: #e7e7e7; } .navbar-default .navbar-brand { color: #777; } .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus { color: #5e5e5e; background-color: transparent; } .navbar-default .navbar-text { color: #777; } .navbar-default .navbar-nav > li > a { color: #777; } .navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus { color: #333; background-color: transparent; } .navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus { color: #555; background-color: #e7e7e7; } .navbar-default .navbar-nav > .disabled > a, .navbar-default .navbar-nav > .disabled > a:hover, .navbar-default .navbar-nav > .disabled > a:focus { color: #ccc; background-color: transparent; } .navbar-default .navbar-toggle { border-color: #ddd; } .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus { background-color: #ddd; } .navbar-default .navbar-toggle .icon-bar { background-color: #888; } .navbar-default .navbar-collapse, .navbar-default .navbar-form { border-color: #e7e7e7; } .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus { color: #555; background-color: #e7e7e7; } @media (max-width: 767px) { .navbar-default .navbar-nav .open .dropdown-menu > li > a { color: #777; } .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus { color: #333; background-color: transparent; } .navbar-default .navbar-nav .open .dropdown-menu > .active > a, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus { color: #555; background-color: #e7e7e7; } .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a, .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus { color: #ccc; background-color: transparent; } } .navbar-default .navbar-link { color: #777; } .navbar-default .navbar-link:hover { color: #333; } .navbar-default .btn-link { color: #777; } .navbar-default .btn-link:hover, .navbar-default .btn-link:focus { color: #333; } .navbar-default .btn-link[disabled]:hover, fieldset[disabled] .navbar-default .btn-link:hover, .navbar-default .btn-link[disabled]:focus, fieldset[disabled] .navbar-default .btn-link:focus { color: #ccc; } .navbar-inverse { background-color: #222; border-color: #080808; } .navbar-inverse .navbar-brand { color: #9d9d9d; } .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-brand:focus { color: #fff; background-color: transparent; } .navbar-inverse .navbar-text { color: #9d9d9d; } .navbar-inverse .navbar-nav > li > a { color: #9d9d9d; } .navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus { color: #fff; background-color: transparent; } .navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus { color: #fff; background-color: #080808; } .navbar-inverse .navbar-nav > .disabled > a, .navbar-inverse .navbar-nav > .disabled > a:hover, .navbar-inverse .navbar-nav > .disabled > a:focus { color: #444; background-color: transparent; } .navbar-inverse .navbar-toggle { border-color: #333; } .navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus { background-color: #333; } .navbar-inverse .navbar-toggle .icon-bar { background-color: #fff; } .navbar-inverse .navbar-collapse, .navbar-inverse .navbar-form { border-color: #101010; } .navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .open > a:hover, .navbar-inverse .navbar-nav > .open > a:focus { color: #fff; background-color: #080808; } @media (max-width: 767px) { .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header { border-color: #080808; } .navbar-inverse .navbar-nav .open .dropdown-menu .divider { background-color: #080808; } .navbar-inverse .navbar-nav .open .dropdown-menu > li > a { color: #9d9d9d; } .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus { color: #fff; background-color: transparent; } .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a, .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus { color: #fff; background-color: #080808; } .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a, .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover, .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus { color: #444; background-color: transparent; } } .navbar-inverse .navbar-link { color: #9d9d9d; } .navbar-inverse .navbar-link:hover { color: #fff; } .navbar-inverse .btn-link { color: #9d9d9d; } .navbar-inverse .btn-link:hover, .navbar-inverse .btn-link:focus { color: #fff; } .navbar-inverse .btn-link[disabled]:hover, fieldset[disabled] .navbar-inverse .btn-link:hover, .navbar-inverse .btn-link[disabled]:focus, fieldset[disabled] .navbar-inverse .btn-link:focus { color: #444; } .breadcrumb { padding: 8px 15px; margin-bottom: 20px; list-style: none; background-color: #f5f5f5; border-radius: 4px; } .breadcrumb > li { display: inline-block; } .breadcrumb > li + li:before { padding: 0 5px; color: #ccc; content: "/\00a0"; } .breadcrumb > .active { color: #777; } .pagination { display: inline-block; padding-left: 0; margin: 20px 0; border-radius: 4px; } .pagination > li { display: inline; } .pagination > li > a, .pagination > li > span { position: relative; float: left; padding: 6px 12px; margin-left: -1px; line-height: 1.42857143; color: #337ab7; text-decoration: none; background-color: #fff; border: 1px solid #ddd; } .pagination > li:first-child > a, .pagination > li:first-child > span { margin-left: 0; border-top-left-radius: 4px; border-bottom-left-radius: 4px; } .pagination > li:last-child > a, .pagination > li:last-child > span { border-top-right-radius: 4px; border-bottom-right-radius: 4px; } .pagination > li > a:hover, .pagination > li > span:hover, .pagination > li > a:focus, .pagination > li > span:focus { color: #23527c; background-color: #eee; border-color: #ddd; } .pagination > .active > a, .pagination > .active > span, .pagination > .active > a:hover, .pagination > .active > span:hover, .pagination > .active > a:focus, .pagination > .active > span:focus { z-index: 2; color: #fff; cursor: default; background-color: #337ab7; border-color: #337ab7; } .pagination > .disabled > span, .pagination > .disabled > span:hover, .pagination > .disabled > span:focus, .pagination > .disabled > a, .pagination > .disabled > a:hover, .pagination > .disabled > a:focus { color: #777; cursor: not-allowed; background-color: #fff; border-color: #ddd; } .pagination-lg > li > a, .pagination-lg > li > span { padding: 10px 16px; font-size: 18px; } .pagination-lg > li:first-child > a, .pagination-lg > li:first-child > span { border-top-left-radius: 6px; border-bottom-left-radius: 6px; } .pagination-lg > li:last-child > a, .pagination-lg > li:last-child > span { border-top-right-radius: 6px; border-bottom-right-radius: 6px; } .pagination-sm > li > a, .pagination-sm > li > span { padding: 5px 10px; font-size: 12px; } .pagination-sm > li:first-child > a, .pagination-sm > li:first-child > span { border-top-left-radius: 3px; border-bottom-left-radius: 3px; } .pagination-sm > li:last-child > a, .pagination-sm > li:last-child > span { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } .pager { padding-left: 0; margin: 20px 0; text-align: center; list-style: none; } .pager li { display: inline; } .pager li > a, .pager li > span { display: inline-block; padding: 5px 14px; background-color: #fff; border: 1px solid #ddd; border-radius: 15px; } .pager li > a:hover, .pager li > a:focus { text-decoration: none; background-color: #eee; } .pager .next > a, .pager .next > span { float: right; } .pager .previous > a, .pager .previous > span { float: left; } .pager .disabled > a, .pager .disabled > a:hover, .pager .disabled > a:focus, .pager .disabled > span { color: #777; cursor: not-allowed; background-color: #fff; } .label { display: inline; padding: .2em .6em .3em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; } a.label:hover, a.label:focus { color: #fff; text-decoration: none; cursor: pointer; } .label:empty { display: none; } .btn .label { position: relative; top: -1px; } .label-default { background-color: #777; } .label-default[href]:hover, .label-default[href]:focus { background-color: #5e5e5e; } .label-primary { background-color: #337ab7; } .label-primary[href]:hover, .label-primary[href]:focus { background-color: #286090; } .label-success { background-color: #5cb85c; } .label-success[href]:hover, .label-success[href]:focus { background-color: #449d44; } .label-info { background-color: #5bc0de; } .label-info[href]:hover, .label-info[href]:focus { background-color: #31b0d5; } .label-warning { background-color: #f0ad4e; } .label-warning[href]:hover, .label-warning[href]:focus { background-color: #ec971f; } .label-danger { background-color: #d9534f; } .label-danger[href]:hover, .label-danger[href]:focus { background-color: #c9302c; } .badge { display: inline-block; min-width: 10px; padding: 3px 7px; font-size: 12px; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; background-color: #777; border-radius: 10px; } .badge:empty { display: none; } .btn .badge { position: relative; top: -1px; } .btn-xs .badge { top: 0; padding: 1px 5px; } a.badge:hover, a.badge:focus { color: #fff; text-decoration: none; cursor: pointer; } .list-group-item.active > .badge, .nav-pills > .active > a > .badge { color: #337ab7; background-color: #fff; } .list-group-item > .badge { float: right; } .list-group-item > .badge + .badge { margin-right: 5px; } .nav-pills > li > a > .badge { margin-left: 3px; } .jumbotron { padding: 30px 15px; margin-bottom: 30px; color: inherit; background-color: #eee; } .jumbotron h1, .jumbotron .h1 { color: inherit; } .jumbotron p { margin-bottom: 15px; font-size: 21px; font-weight: 200; } .jumbotron > hr { border-top-color: #d5d5d5; } .container .jumbotron, .container-fluid .jumbotron { border-radius: 6px; } .jumbotron .container { max-width: 100%; } @media screen and (min-width: 768px) { .jumbotron { padding: 48px 0; } .container .jumbotron, .container-fluid .jumbotron { padding-right: 60px; padding-left: 60px; } .jumbotron h1, .jumbotron .h1 { font-size: 63px; } } .thumbnail { display: block; padding: 4px; margin-bottom: 20px; line-height: 1.42857143; background-color: #fff; border: 1px solid #ddd; border-radius: 4px; -webkit-transition: border .2s ease-in-out; -o-transition: border .2s ease-in-out; transition: border .2s ease-in-out; } .thumbnail > img, .thumbnail a > img { margin-right: auto; margin-left: auto; } a.thumbnail:hover, a.thumbnail:focus, a.thumbnail.active { border-color: #337ab7; } .thumbnail .caption { padding: 9px; color: #333; } .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } .alert h4 { margin-top: 0; color: inherit; } .alert .alert-link { font-weight: bold; } .alert > p, .alert > ul { margin-bottom: 0; } .alert > p + p { margin-top: 5px; } .alert-dismissable, .alert-dismissible { padding-right: 35px; } .alert-dismissable .close, .alert-dismissible .close { position: relative; top: -2px; right: -21px; color: inherit; } .alert-success { color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6; } .alert-success hr { border-top-color: #c9e2b3; } .alert-success .alert-link { color: #2b542c; } .alert-info { color: #31708f; background-color: #d9edf7; border-color: #bce8f1; } .alert-info hr { border-top-color: #a6e1ec; } .alert-info .alert-link { color: #245269; } .alert-warning { color: #8a6d3b; background-color: #fcf8e3; border-color: #faebcc; } .alert-warning hr { border-top-color: #f7e1b5; } .alert-warning .alert-link { color: #66512c; } .alert-danger { color: #a94442; background-color: #f2dede; border-color: #ebccd1; } .alert-danger hr { border-top-color: #e4b9c0; } .alert-danger .alert-link { color: #843534; } @-webkit-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-o-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } .progress { height: 20px; margin-bottom: 20px; overflow: hidden; background-color: #f5f5f5; border-radius: 4px; -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); } .progress-bar { float: left; width: 0; height: 100%; font-size: 12px; line-height: 20px; color: #fff; text-align: center; background-color: #337ab7; -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); -webkit-transition: width .6s ease; -o-transition: width .6s ease; transition: width .6s ease; } .progress-striped .progress-bar, .progress-bar-striped { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); -webkit-background-size: 40px 40px; background-size: 40px 40px; } .progress.active .progress-bar, .progress-bar.active { -webkit-animation: progress-bar-stripes 2s linear infinite; -o-animation: progress-bar-stripes 2s linear infinite; animation: progress-bar-stripes 2s linear infinite; } .progress-bar-success { background-color: #5cb85c; } .progress-striped .progress-bar-success { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } .progress-bar-info { background-color: #5bc0de; } .progress-striped .progress-bar-info { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } .progress-bar-warning { background-color: #f0ad4e; } .progress-striped .progress-bar-warning { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } .progress-bar-danger { background-color: #d9534f; } .progress-striped .progress-bar-danger { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); } .media { margin-top: 15px; } .media:first-child { margin-top: 0; } .media, .media-body { overflow: hidden; zoom: 1; } .media-body { width: 10000px; } .media-object { display: block; } .media-right, .media > .pull-right { padding-left: 10px; } .media-left, .media > .pull-left { padding-right: 10px; } .media-left, .media-right, .media-body { display: table-cell; vertical-align: top; } .media-middle { vertical-align: middle; } .media-bottom { vertical-align: bottom; } .media-heading { margin-top: 0; margin-bottom: 5px; } .media-list { padding-left: 0; list-style: none; } .list-group { padding-left: 0; margin-bottom: 20px; } .list-group-item { position: relative; display: block; padding: 10px 15px; margin-bottom: -1px; background-color: #fff; border: 1px solid #ddd; } .list-group-item:first-child { border-top-left-radius: 4px; border-top-right-radius: 4px; } .list-group-item:last-child { margin-bottom: 0; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; } a.list-group-item { color: #555; } a.list-group-item .list-group-item-heading { color: #333; } a.list-group-item:hover, a.list-group-item:focus { color: #555; text-decoration: none; background-color: #f5f5f5; } .list-group-item.disabled, .list-group-item.disabled:hover, .list-group-item.disabled:focus { color: #777; cursor: not-allowed; background-color: #eee; } .list-group-item.disabled .list-group-item-heading, .list-group-item.disabled:hover .list-group-item-heading, .list-group-item.disabled:focus .list-group-item-heading { color: inherit; } .list-group-item.disabled .list-group-item-text, .list-group-item.disabled:hover .list-group-item-text, .list-group-item.disabled:focus .list-group-item-text { color: #777; } .list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus { z-index: 2; color: #fff; background-color: #337ab7; border-color: #337ab7; } .list-group-item.active .list-group-item-heading, .list-group-item.active:hover .list-group-item-heading, .list-group-item.active:focus .list-group-item-heading, .list-group-item.active .list-group-item-heading > small, .list-group-item.active:hover .list-group-item-heading > small, .list-group-item.active:focus .list-group-item-heading > small, .list-group-item.active .list-group-item-heading > .small, .list-group-item.active:hover .list-group-item-heading > .small, .list-group-item.active:focus .list-group-item-heading > .small { color: inherit; } .list-group-item.active .list-group-item-text, .list-group-item.active:hover .list-group-item-text, .list-group-item.active:focus .list-group-item-text { color: #c7ddef; } .list-group-item-success { color: #3c763d; background-color: #dff0d8; } a.list-group-item-success { color: #3c763d; } a.list-group-item-success .list-group-item-heading { color: inherit; } a.list-group-item-success:hover, a.list-group-item-success:focus { color: #3c763d; background-color: #d0e9c6; } a.list-group-item-success.active, a.list-group-item-success.active:hover, a.list-group-item-success.active:focus { color: #fff; background-color: #3c763d; border-color: #3c763d; } .list-group-item-info { color: #31708f; background-color: #d9edf7; } a.list-group-item-info { color: #31708f; } a.list-group-item-info .list-group-item-heading { color: inherit; } a.list-group-item-info:hover, a.list-group-item-info:focus { color: #31708f; background-color: #c4e3f3; } a.list-group-item-info.active, a.list-group-item-info.active:hover, a.list-group-item-info.active:focus { color: #fff; background-color: #31708f; border-color: #31708f; } .list-group-item-warning { color: #8a6d3b; background-color: #fcf8e3; } a.list-group-item-warning { color: #8a6d3b; } a.list-group-item-warning .list-group-item-heading { color: inherit; } a.list-group-item-warning:hover, a.list-group-item-warning:focus { color: #8a6d3b; background-color: #faf2cc; } a.list-group-item-warning.active, a.list-group-item-warning.active:hover, a.list-group-item-warning.active:focus { color: #fff; background-color: #8a6d3b; border-color: #8a6d3b; } .list-group-item-danger { color: #a94442; background-color: #f2dede; } a.list-group-item-danger { color: #a94442; } a.list-group-item-danger .list-group-item-heading { color: inherit; } a.list-group-item-danger:hover, a.list-group-item-danger:focus { color: #a94442; background-color: #ebcccc; } a.list-group-item-danger.active, a.list-group-item-danger.active:hover, a.list-group-item-danger.active:focus { color: #fff; background-color: #a94442; border-color: #a94442; } .list-group-item-heading { margin-top: 0; margin-bottom: 5px; } .list-group-item-text { margin-bottom: 0; line-height: 1.3; } .panel { margin-bottom: 20px; background-color: #fff; border: 1px solid transparent; border-radius: 4px; -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05); box-shadow: 0 1px 1px rgba(0, 0, 0, .05); } .panel-body { padding: 15px; } .panel-heading { padding: 10px 15px; border-bottom: 1px solid transparent; border-top-left-radius: 3px; border-top-right-radius: 3px; } .panel-heading > .dropdown .dropdown-toggle { color: inherit; } .panel-title { margin-top: 0; margin-bottom: 0; font-size: 16px; color: inherit; } .panel-title > a, .panel-title > small, .panel-title > .small, .panel-title > small > a, .panel-title > .small > a { color: inherit; } .panel-footer { padding: 10px 15px; background-color: #f5f5f5; border-top: 1px solid #ddd; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .panel > .list-group, .panel > .panel-collapse > .list-group { margin-bottom: 0; } .panel > .list-group .list-group-item, .panel > .panel-collapse > .list-group .list-group-item { border-width: 1px 0; border-radius: 0; } .panel > .list-group:first-child .list-group-item:first-child, .panel > .panel-collapse > .list-group:first-child .list-group-item:first-child { border-top: 0; border-top-left-radius: 3px; border-top-right-radius: 3px; } .panel > .list-group:last-child .list-group-item:last-child, .panel > .panel-collapse > .list-group:last-child .list-group-item:last-child { border-bottom: 0; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .panel-heading + .list-group .list-group-item:first-child { border-top-width: 0; } .list-group + .panel-footer { border-top-width: 0; } .panel > .table, .panel > .table-responsive > .table, .panel > .panel-collapse > .table { margin-bottom: 0; } .panel > .table caption, .panel > .table-responsive > .table caption, .panel > .panel-collapse > .table caption { padding-right: 15px; padding-left: 15px; } .panel > .table:first-child, .panel > .table-responsive:first-child > .table:first-child { border-top-left-radius: 3px; border-top-right-radius: 3px; } .panel > .table:first-child > thead:first-child > tr:first-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child, .panel > .table:first-child > tbody:first-child > tr:first-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child { border-top-left-radius: 3px; border-top-right-radius: 3px; } .panel > .table:first-child > thead:first-child > tr:first-child td:first-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child, .panel > .table:first-child > tbody:first-child > tr:first-child td:first-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child, .panel > .table:first-child > thead:first-child > tr:first-child th:first-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child, .panel > .table:first-child > tbody:first-child > tr:first-child th:first-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child { border-top-left-radius: 3px; } .panel > .table:first-child > thead:first-child > tr:first-child td:last-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child, .panel > .table:first-child > tbody:first-child > tr:first-child td:last-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child, .panel > .table:first-child > thead:first-child > tr:first-child th:last-child, .panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child, .panel > .table:first-child > tbody:first-child > tr:first-child th:last-child, .panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child { border-top-right-radius: 3px; } .panel > .table:last-child, .panel > .table-responsive:last-child > .table:last-child { border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .panel > .table:last-child > tbody:last-child > tr:last-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child, .panel > .table:last-child > tfoot:last-child > tr:last-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child { border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .panel > .table:last-child > tbody:last-child > tr:last-child td:first-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child, .panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child, .panel > .table:last-child > tbody:last-child > tr:last-child th:first-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child, .panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child { border-bottom-left-radius: 3px; } .panel > .table:last-child > tbody:last-child > tr:last-child td:last-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child, .panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child, .panel > .table:last-child > tbody:last-child > tr:last-child th:last-child, .panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child, .panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child, .panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child { border-bottom-right-radius: 3px; } .panel > .panel-body + .table, .panel > .panel-body + .table-responsive, .panel > .table + .panel-body, .panel > .table-responsive + .panel-body { border-top: 1px solid #ddd; } .panel > .table > tbody:first-child > tr:first-child th, .panel > .table > tbody:first-child > tr:first-child td { border-top: 0; } .panel > .table-bordered, .panel > .table-responsive > .table-bordered { border: 0; } .panel > .table-bordered > thead > tr > th:first-child, .panel > .table-responsive > .table-bordered > thead > tr > th:first-child, .panel > .table-bordered > tbody > tr > th:first-child, .panel > .table-responsive > .table-bordered > tbody > tr > th:first-child, .panel > .table-bordered > tfoot > tr > th:first-child, .panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child, .panel > .table-bordered > thead > tr > td:first-child, .panel > .table-responsive > .table-bordered > thead > tr > td:first-child, .panel > .table-bordered > tbody > tr > td:first-child, .panel > .table-responsive > .table-bordered > tbody > tr > td:first-child, .panel > .table-bordered > tfoot > tr > td:first-child, .panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child { border-left: 0; } .panel > .table-bordered > thead > tr > th:last-child, .panel > .table-responsive > .table-bordered > thead > tr > th:last-child, .panel > .table-bordered > tbody > tr > th:last-child, .panel > .table-responsive > .table-bordered > tbody > tr > th:last-child, .panel > .table-bordered > tfoot > tr > th:last-child, .panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child, .panel > .table-bordered > thead > tr > td:last-child, .panel > .table-responsive > .table-bordered > thead > tr > td:last-child, .panel > .table-bordered > tbody > tr > td:last-child, .panel > .table-responsive > .table-bordered > tbody > tr > td:last-child, .panel > .table-bordered > tfoot > tr > td:last-child, .panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child { border-right: 0; } .panel > .table-bordered > thead > tr:first-child > td, .panel > .table-responsive > .table-bordered > thead > tr:first-child > td, .panel > .table-bordered > tbody > tr:first-child > td, .panel > .table-responsive > .table-bordered > tbody > tr:first-child > td, .panel > .table-bordered > thead > tr:first-child > th, .panel > .table-responsive > .table-bordered > thead > tr:first-child > th, .panel > .table-bordered > tbody > tr:first-child > th, .panel > .table-responsive > .table-bordered > tbody > tr:first-child > th { border-bottom: 0; } .panel > .table-bordered > tbody > tr:last-child > td, .panel > .table-responsive > .table-bordered > tbody > tr:last-child > td, .panel > .table-bordered > tfoot > tr:last-child > td, .panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td, .panel > .table-bordered > tbody > tr:last-child > th, .panel > .table-responsive > .table-bordered > tbody > tr:last-child > th, .panel > .table-bordered > tfoot > tr:last-child > th, .panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th { border-bottom: 0; } .panel > .table-responsive { margin-bottom: 0; border: 0; } .panel-group { margin-bottom: 20px; } .panel-group .panel { margin-bottom: 0; border-radius: 4px; } .panel-group .panel + .panel { margin-top: 5px; } .panel-group .panel-heading { border-bottom: 0; } .panel-group .panel-heading + .panel-collapse > .panel-body, .panel-group .panel-heading + .panel-collapse > .list-group { border-top: 1px solid #ddd; } .panel-group .panel-footer { border-top: 0; } .panel-group .panel-footer + .panel-collapse .panel-body { border-bottom: 1px solid #ddd; } .panel-default { border-color: #ddd; } .panel-default > .panel-heading { color: #333; background-color: #f5f5f5; border-color: #ddd; } .panel-default > .panel-heading + .panel-collapse > .panel-body { border-top-color: #ddd; } .panel-default > .panel-heading .badge { color: #f5f5f5; background-color: #333; } .panel-default > .panel-footer + .panel-collapse > .panel-body { border-bottom-color: #ddd; } .panel-primary { border-color: #337ab7; } .panel-primary > .panel-heading { color: #fff; background-color: #337ab7; border-color: #337ab7; } .panel-primary > .panel-heading + .panel-collapse > .panel-body { border-top-color: #337ab7; } .panel-primary > .panel-heading .badge { color: #337ab7; background-color: #fff; } .panel-primary > .panel-footer + .panel-collapse > .panel-body { border-bottom-color: #337ab7; } .panel-success { border-color: #d6e9c6; } .panel-success > .panel-heading { color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6; } .panel-success > .panel-heading + .panel-collapse > .panel-body { border-top-color: #d6e9c6; } .panel-success > .panel-heading .badge { color: #dff0d8; background-color: #3c763d; } .panel-success > .panel-footer + .panel-collapse > .panel-body { border-bottom-color: #d6e9c6; } .panel-info { border-color: #bce8f1; } .panel-info > .panel-heading { color: #31708f; background-color: #d9edf7; border-color: #bce8f1; } .panel-info > .panel-heading + .panel-collapse > .panel-body { border-top-color: #bce8f1; } .panel-info > .panel-heading .badge { color: #d9edf7; background-color: #31708f; } .panel-info > .panel-footer + .panel-collapse > .panel-body { border-bottom-color: #bce8f1; } .panel-warning { border-color: #faebcc; } .panel-warning > .panel-heading { color: #8a6d3b; background-color: #fcf8e3; border-color: #faebcc; } .panel-warning > .panel-heading + .panel-collapse > .panel-body { border-top-color: #faebcc; } .panel-warning > .panel-heading .badge { color: #fcf8e3; background-color: #8a6d3b; } .panel-warning > .panel-footer + .panel-collapse > .panel-body { border-bottom-color: #faebcc; } .panel-danger { border-color: #ebccd1; } .panel-danger > .panel-heading { color: #a94442; background-color: #f2dede; border-color: #ebccd1; } .panel-danger > .panel-heading + .panel-collapse > .panel-body { border-top-color: #ebccd1; } .panel-danger > .panel-heading .badge { color: #f2dede; background-color: #a94442; } .panel-danger > .panel-footer + .panel-collapse > .panel-body { border-bottom-color: #ebccd1; } .embed-responsive { position: relative; display: block; height: 0; padding: 0; overflow: hidden; } .embed-responsive .embed-responsive-item, .embed-responsive iframe, .embed-responsive embed, .embed-responsive object, .embed-responsive video { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; } .embed-responsive.embed-responsive-16by9 { padding-bottom: 56.25%; } .embed-responsive.embed-responsive-4by3 { padding-bottom: 75%; } .well { min-height: 20px; padding: 19px; margin-bottom: 20px; background-color: #f5f5f5; border: 1px solid #e3e3e3; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); } .well blockquote { border-color: #ddd; border-color: rgba(0, 0, 0, .15); } .well-lg { padding: 24px; border-radius: 6px; } .well-sm { padding: 9px; border-radius: 3px; } .close { float: right; font-size: 21px; font-weight: bold; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; filter: alpha(opacity=20); opacity: .2; } .close:hover, .close:focus { color: #000; text-decoration: none; cursor: pointer; filter: alpha(opacity=50); opacity: .5; } button.close { -webkit-appearance: none; padding: 0; cursor: pointer; background: transparent; border: 0; } .modal-open { overflow: hidden; } .modal { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; display: none; overflow: hidden; -webkit-overflow-scrolling: touch; outline: 0; } .modal.fade .modal-dialog { -webkit-transition: -webkit-transform .3s ease-out; -o-transition: -o-transform .3s ease-out; transition: transform .3s ease-out; -webkit-transform: translate(0, -25%); -ms-transform: translate(0, -25%); -o-transform: translate(0, -25%); transform: translate(0, -25%); } .modal.in .modal-dialog { -webkit-transform: translate(0, 0); -ms-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0); } .modal-open .modal { overflow-x: hidden; overflow-y: auto; } .modal-dialog { position: relative; width: auto; margin: 10px; } .modal-content { position: relative; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid #999; border: 1px solid rgba(0, 0, 0, .2); border-radius: 6px; outline: 0; -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5); box-shadow: 0 3px 9px rgba(0, 0, 0, .5); } .modal-backdrop { position: absolute; top: 0; right: 0; left: 0; background-color: #000; } .modal-backdrop.fade { filter: alpha(opacity=0); opacity: 0; } .modal-backdrop.in { filter: alpha(opacity=50); opacity: .5; } .modal-header { min-height: 16.42857143px; padding: 15px; border-bottom: 1px solid #e5e5e5; } .modal-header .close { margin-top: -2px; } .modal-title { margin: 0; line-height: 1.42857143; } .modal-body { position: relative; padding: 15px; } .modal-footer { padding: 15px; text-align: right; border-top: 1px solid #e5e5e5; } .modal-footer .btn + .btn { margin-bottom: 0; margin-left: 5px; } .modal-footer .btn-group .btn + .btn { margin-left: -1px; } .modal-footer .btn-block + .btn-block { margin-left: 0; } .modal-scrollbar-measure { position: absolute; top: -9999px; width: 50px; height: 50px; overflow: scroll; } @media (min-width: 768px) { .modal-dialog { width: 600px; margin: 30px auto; } .modal-content { -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5); box-shadow: 0 5px 15px rgba(0, 0, 0, .5); } .modal-sm { width: 300px; } } @media (min-width: 992px) { .modal-lg { width: 900px; } } .tooltip { position: absolute; z-index: 1070; display: block; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 12px; font-weight: normal; line-height: 1.4; visibility: visible; filter: alpha(opacity=0); opacity: 0; } .tooltip.in { filter: alpha(opacity=90); opacity: .9; } .tooltip.top { padding: 5px 0; margin-top: -3px; } .tooltip.right { padding: 0 5px; margin-left: 3px; } .tooltip.bottom { padding: 5px 0; margin-top: 3px; } .tooltip.left { padding: 0 5px; margin-left: -3px; } .tooltip-inner { max-width: 200px; padding: 3px 8px; color: #fff; text-align: center; text-decoration: none; background-color: #000; border-radius: 4px; } .tooltip-arrow { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .tooltip.top .tooltip-arrow { bottom: 0; left: 50%; margin-left: -5px; border-width: 5px 5px 0; border-top-color: #000; } .tooltip.top-left .tooltip-arrow { right: 5px; bottom: 0; margin-bottom: -5px; border-width: 5px 5px 0; border-top-color: #000; } .tooltip.top-right .tooltip-arrow { bottom: 0; left: 5px; margin-bottom: -5px; border-width: 5px 5px 0; border-top-color: #000; } .tooltip.right .tooltip-arrow { top: 50%; left: 0; margin-top: -5px; border-width: 5px 5px 5px 0; border-right-color: #000; } .tooltip.left .tooltip-arrow { top: 50%; right: 0; margin-top: -5px; border-width: 5px 0 5px 5px; border-left-color: #000; } .tooltip.bottom .tooltip-arrow { top: 0; left: 50%; margin-left: -5px; border-width: 0 5px 5px; border-bottom-color: #000; } .tooltip.bottom-left .tooltip-arrow { top: 0; right: 5px; margin-top: -5px; border-width: 0 5px 5px; border-bottom-color: #000; } .tooltip.bottom-right .tooltip-arrow { top: 0; left: 5px; margin-top: -5px; border-width: 0 5px 5px; border-bottom-color: #000; } .popover { position: absolute; top: 0; left: 0; z-index: 1060; display: none; max-width: 276px; padding: 1px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; font-weight: normal; line-height: 1.42857143; text-align: left; white-space: normal; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, .2); border-radius: 6px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2); box-shadow: 0 5px 10px rgba(0, 0, 0, .2); } .popover.top { margin-top: -10px; } .popover.right { margin-left: 10px; } .popover.bottom { margin-top: 10px; } .popover.left { margin-left: -10px; } .popover-title { padding: 8px 14px; margin: 0; font-size: 14px; background-color: #f7f7f7; border-bottom: 1px solid #ebebeb; border-radius: 5px 5px 0 0; } .popover-content { padding: 9px 14px; } .popover > .arrow, .popover > .arrow:after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover > .arrow { border-width: 11px; } .popover > .arrow:after { content: ""; border-width: 10px; } .popover.top > .arrow { bottom: -11px; left: 50%; margin-left: -11px; border-top-color: #999; border-top-color: rgba(0, 0, 0, .25); border-bottom-width: 0; } .popover.top > .arrow:after { bottom: 1px; margin-left: -10px; content: " "; border-top-color: #fff; border-bottom-width: 0; } .popover.right > .arrow { top: 50%; left: -11px; margin-top: -11px; border-right-color: #999; border-right-color: rgba(0, 0, 0, .25); border-left-width: 0; } .popover.right > .arrow:after { bottom: -10px; left: 1px; content: " "; border-right-color: #fff; border-left-width: 0; } .popover.bottom > .arrow { top: -11px; left: 50%; margin-left: -11px; border-top-width: 0; border-bottom-color: #999; border-bottom-color: rgba(0, 0, 0, .25); } .popover.bottom > .arrow:after { top: 1px; margin-left: -10px; content: " "; border-top-width: 0; border-bottom-color: #fff; } .popover.left > .arrow { top: 50%; right: -11px; margin-top: -11px; border-right-width: 0; border-left-color: #999; border-left-color: rgba(0, 0, 0, .25); } .popover.left > .arrow:after { right: 1px; bottom: -10px; content: " "; border-right-width: 0; border-left-color: #fff; } .carousel { position: relative; } .carousel-inner { position: relative; width: 100%; overflow: hidden; } .carousel-inner > .item { position: relative; display: none; -webkit-transition: .6s ease-in-out left; -o-transition: .6s ease-in-out left; transition: .6s ease-in-out left; } .carousel-inner > .item > img, .carousel-inner > .item > a > img { line-height: 1; } @media all and (transform-3d), (-webkit-transform-3d) { .carousel-inner > .item { -webkit-transition: -webkit-transform .6s ease-in-out; -o-transition: -o-transform .6s ease-in-out; transition: transform .6s ease-in-out; -webkit-backface-visibility: hidden; backface-visibility: hidden; -webkit-perspective: 1000; perspective: 1000; } .carousel-inner > .item.next, .carousel-inner > .item.active.right { left: 0; -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .carousel-inner > .item.prev, .carousel-inner > .item.active.left { left: 0; -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } .carousel-inner > .item.next.left, .carousel-inner > .item.prev.right, .carousel-inner > .item.active { left: 0; -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } } .carousel-inner > .active, .carousel-inner > .next, .carousel-inner > .prev { display: block; } .carousel-inner > .active { left: 0; } .carousel-inner > .next, .carousel-inner > .prev { position: absolute; top: 0; width: 100%; } .carousel-inner > .next { left: 100%; } .carousel-inner > .prev { left: -100%; } .carousel-inner > .next.left, .carousel-inner > .prev.right { left: 0; } .carousel-inner > .active.left { left: -100%; } .carousel-inner > .active.right { left: 100%; } .carousel-control { position: absolute; top: 0; bottom: 0; left: 0; width: 15%; font-size: 20px; color: #fff; text-align: center; text-shadow: 0 1px 2px rgba(0, 0, 0, .6); filter: alpha(opacity=50); opacity: .5; } .carousel-control.left { background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001))); background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1); background-repeat: repeat-x; } .carousel-control.right { right: 0; left: auto; background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5))); background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1); background-repeat: repeat-x; } .carousel-control:hover, .carousel-control:focus { color: #fff; text-decoration: none; filter: alpha(opacity=90); outline: 0; opacity: .9; } .carousel-control .icon-prev, .carousel-control .icon-next, .carousel-control .glyphicon-chevron-left, .carousel-control .glyphicon-chevron-right { position: absolute; top: 50%; z-index: 5; display: inline-block; } .carousel-control .icon-prev, .carousel-control .glyphicon-chevron-left { left: 50%; margin-left: -10px; } .carousel-control .icon-next, .carousel-control .glyphicon-chevron-right { right: 50%; margin-right: -10px; } .carousel-control .icon-prev, .carousel-control .icon-next { width: 20px; height: 20px; margin-top: -10px; font-family: serif; line-height: 1; } .carousel-control .icon-prev:before { content: '\2039'; } .carousel-control .icon-next:before { content: '\203a'; } .carousel-indicators { position: absolute; bottom: 10px; left: 50%; z-index: 15; width: 60%; padding-left: 0; margin-left: -30%; text-align: center; list-style: none; } .carousel-indicators li { display: inline-block; width: 10px; height: 10px; margin: 1px; text-indent: -999px; cursor: pointer; background-color: #000 \9; background-color: rgba(0, 0, 0, 0); border: 1px solid #fff; border-radius: 10px; } .carousel-indicators .active { width: 12px; height: 12px; margin: 0; background-color: #fff; } .carousel-caption { position: absolute; right: 15%; bottom: 20px; left: 15%; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: #fff; text-align: center; text-shadow: 0 1px 2px rgba(0, 0, 0, .6); } .carousel-caption .btn { text-shadow: none; } @media screen and (min-width: 768px) { .carousel-control .glyphicon-chevron-left, .carousel-control .glyphicon-chevron-right, .carousel-control .icon-prev, .carousel-control .icon-next { width: 30px; height: 30px; margin-top: -15px; font-size: 30px; } .carousel-control .glyphicon-chevron-left, .carousel-control .icon-prev { margin-left: -15px; } .carousel-control .glyphicon-chevron-right, .carousel-control .icon-next { margin-right: -15px; } .carousel-caption { right: 20%; left: 20%; padding-bottom: 30px; } .carousel-indicators { bottom: 20px; } } .clearfix:before, .clearfix:after, .dl-horizontal dd:before, .dl-horizontal dd:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after { display: table; content: " "; } .clearfix:after, .dl-horizontal dd:after, .container:after, .container-fluid:after, .row:after, .form-horizontal .form-group:after, .btn-toolbar:after, .btn-group-vertical > .btn-group:after, .nav:after, .navbar:after, .navbar-header:after, .navbar-collapse:after, .pager:after, .panel-body:after, .modal-footer:after { clear: both; } .center-block { display: block; margin-right: auto; margin-left: auto; } .pull-right { float: right !important; } .pull-left { float: left !important; } .hide { display: none !important; } .show { display: block !important; } .invisible { visibility: hidden; } .text-hide { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .hidden { display: none !important; visibility: hidden !important; } .affix { position: fixed; } @-ms-viewport { width: device-width; } .visible-xs, .visible-sm, .visible-md, .visible-lg { display: none !important; } .visible-xs-block, .visible-xs-inline, .visible-xs-inline-block, .visible-sm-block, .visible-sm-inline, .visible-sm-inline-block, .visible-md-block, .visible-md-inline, .visible-md-inline-block, .visible-lg-block, .visible-lg-inline, .visible-lg-inline-block { display: none !important; } @media (max-width: 767px) { .visible-xs { display: block !important; } table.visible-xs { display: table; } tr.visible-xs { display: table-row !important; } th.visible-xs, td.visible-xs { display: table-cell !important; } } @media (max-width: 767px) { .visible-xs-block { display: block !important; } } @media (max-width: 767px) { .visible-xs-inline { display: inline !important; } } @media (max-width: 767px) { .visible-xs-inline-block { display: inline-block !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-sm { display: block !important; } table.visible-sm { display: table; } tr.visible-sm { display: table-row !important; } th.visible-sm, td.visible-sm { display: table-cell !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-sm-block { display: block !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-sm-inline { display: inline !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-sm-inline-block { display: inline-block !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-md { display: block !important; } table.visible-md { display: table; } tr.visible-md { display: table-row !important; } th.visible-md, td.visible-md { display: table-cell !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-md-block { display: block !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-md-inline { display: inline !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-md-inline-block { display: inline-block !important; } } @media (min-width: 1200px) { .visible-lg { display: block !important; } table.visible-lg { display: table; } tr.visible-lg { display: table-row !important; } th.visible-lg, td.visible-lg { display: table-cell !important; } } @media (min-width: 1200px) { .visible-lg-block { display: block !important; } } @media (min-width: 1200px) { .visible-lg-inline { display: inline !important; } } @media (min-width: 1200px) { .visible-lg-inline-block { display: inline-block !important; } } @media (max-width: 767px) { .hidden-xs { display: none !important; } } @media (min-width: 768px) and (max-width: 991px) { .hidden-sm { display: none !important; } } @media (min-width: 992px) and (max-width: 1199px) { .hidden-md { display: none !important; } } @media (min-width: 1200px) { .hidden-lg { display: none !important; } } .visible-print { display: none !important; } @media print { .visible-print { display: block !important; } table.visible-print { display: table; } tr.visible-print { display: table-row !important; } th.visible-print, td.visible-print { display: table-cell !important; } } .visible-print-block { display: none !important; } @media print { .visible-print-block { display: block !important; } } .visible-print-inline { display: none !important; } @media print { .visible-print-inline { display: inline !important; } } .visible-print-inline-block { display: none !important; } @media print { .visible-print-inline-block { display: inline-block !important; } } @media print { .hidden-print { display: none !important; } } /*# sourceMappingURL=bootstrap.css.map */ ```
/content/code_sandbox/autodoc/bespokesynth.com/css/bootstrap.css
css
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
43,112
```javascript /*! * Start Bootstrap - Grayscale Bootstrap Theme (path_to_url * For details, see path_to_url */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); function init() { // Basic options for a simple Google Map // For more options see: path_to_url#MapOptions var mapOptions = { // How zoomed in you want the map to start at (always required) zoom: 15, // The latitude and longitude to center the map (always required) center: new google.maps.LatLng(40.6700, -73.9400), // New York // Disables the default Google Maps UI components disableDefaultUI: true, scrollwheel: false, draggable: false, // How you would like to style the map. // This is where you would paste any style found on Snazzy Maps. styles: [{ "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 18 }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 21 }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 }] }, { "elementType": "labels.text.fill", "stylers": [{ "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 }] }, { "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 19 }] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 }] }] }; // Get the HTML DOM element that will contain your map // We are using a div with id="map" seen below in the <body> var mapElement = document.getElementById('map'); // Create the Google Map using out element and options defined above var map = new google.maps.Map(mapElement, mapOptions); // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon var image = 'img/map-marker.png'; var myLatLng = new google.maps.LatLng(40.6700, -73.9400); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); } ```
/content/code_sandbox/autodoc/bespokesynth.com/js/grayscale.js
javascript
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,057
```javascript /*! * Bootstrap v3.3.2 (path_to_url */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } +function ($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.2 * path_to_url#transitions * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: path_to_url // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // path_to_url $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.2 * path_to_url#alerts * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.2' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.2 * path_to_url#buttons * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.2' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.2 * path_to_url#carousel * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.2' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.2 * path_to_url#collapse * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.2' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true, trigger: '[data-toggle="collapse"]' } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this }) Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.2 * path_to_url#dropdowns * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.2' Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if ((!isActive && e.which != 27) || (isActive && e.which == 27)) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.2 * path_to_url#modals * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$backdrop = this.isShown = null this.scrollbarWidth = 0 if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.2' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (that.options.backdrop) that.adjustBackdrop() that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .prependTo(this.$element) .on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { if (this.options.backdrop) this.adjustBackdrop() this.adjustDialog() } Modal.prototype.adjustBackdrop = function () { this.$backdrop .css('height', 0) .css('height', this.$element[0].scrollHeight) } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', '') } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.2 * path_to_url#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.2' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (self && self.$tip && self.$tip.is(':visible')) { self.hoverState = 'in' return } if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var $container = this.options.container ? $(this.options.container) : this.$element.parent() var containerDim = this.getPosition($container) placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) { this.arrow() .css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isHorizontal ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see path_to_url elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var elOffset = isBody ? { top: 0, left: 0 } : $element.offset() var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { return (this.$tip = this.$tip || $(this.options.template)) } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.2 * path_to_url#popovers * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.2' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.2 * path_to_url#scrollspy * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var process = $.proxy(this.process, this) this.$body = $('body') this.$scrollElement = $(element).is('body') ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', process) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.2' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var offsetMethod = 'offset' var offsetBase = 0 if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() var self = this this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.2 * path_to_url#tabs * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.VERSION = '3.3.2' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.2 * path_to_url#affix * ======================================================================== * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.2' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = $('body').height() if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery); ```
/content/code_sandbox/autodoc/bespokesynth.com/js/bootstrap.js
javascript
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
15,607
```javascript /* * jQuery Easing v1.3 - path_to_url * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - EASING EQUATIONS * * * All rights reserved. * * TERMS OF USE - jQuery Easing * * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInCubic:function(e,f,a,h,g){return h*(f/=g)*f*f+a},easeOutCubic:function(e,f,a,h,g){return h*((f=f/g-1)*f*f+1)+a},easeInOutCubic:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f+a}return h/2*((f-=2)*f*f+2)+a},easeInQuart:function(e,f,a,h,g){return h*(f/=g)*f*f*f+a},easeOutQuart:function(e,f,a,h,g){return -h*((f=f/g-1)*f*f*f-1)+a},easeInOutQuart:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f+a}return -h/2*((f-=2)*f*f*f-2)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInSine:function(e,f,a,h,g){return -h*Math.cos(f/g*(Math.PI/2))+h+a},easeOutSine:function(e,f,a,h,g){return h*Math.sin(f/g*(Math.PI/2))+a},easeInOutSine:function(e,f,a,h,g){return -h/2*(Math.cos(Math.PI*f/g)-1)+a},easeInExpo:function(e,f,a,h,g){return(f==0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f==0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInCirc:function(e,f,a,h,g){return -h*(Math.sqrt(1-(f/=g)*f)-1)+a},easeOutCirc:function(e,f,a,h,g){return h*Math.sqrt(1-(f=f/g-1)*f)+a},easeInOutCirc:function(e,f,a,h,g){if((f/=g/2)<1){return -h/2*(Math.sqrt(1-f*f)-1)+a}return h/2*(Math.sqrt(1-(f-=2)*f)+1)+a},easeInElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return -(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e},easeOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return g*Math.pow(2,-10*h)*Math.sin((h*k-i)*(2*Math.PI)/j)+l+e},easeInOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k/2)==2){return e+l}if(!j){j=k*(0.3*1.5)}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}if(h<1){return -0.5*(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e}return g*Math.pow(2,-10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j)*0.5+l+e},easeInBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*(f/=h)*f*((g+1)*f-g)+a},easeOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*((f=f/h-1)*f*((g+1)*f+g)+1)+a},easeInOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}if((f/=h/2)<1){return i/2*(f*f*(((g*=(1.525))+1)*f-g))+a}return i/2*((f-=2)*f*(((g*=(1.525))+1)*f+g)+2)+a},easeInBounce:function(e,f,a,h,g){return h-jQuery.easing.easeOutBounce(e,g-f,0,h,g)+a},easeOutBounce:function(e,f,a,h,g){if((f/=g)<(1/2.75)){return h*(7.5625*f*f)+a}else{if(f<(2/2.75)){return h*(7.5625*(f-=(1.5/2.75))*f+0.75)+a}else{if(f<(2.5/2.75)){return h*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return h*(7.5625*(f-=(2.625/2.75))*f+0.984375)+a}}}},easeInOutBounce:function(e,f,a,h,g){if(f<g/2){return jQuery.easing.easeInBounce(e,f*2,0,h,g)*0.5+a}return jQuery.easing.easeOutBounce(e,f*2-g,0,h,g)*0.5+h*0.5+a}}); ```
/content/code_sandbox/autodoc/bespokesynth.com/js/jquery.easing.min.js
javascript
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,944
```javascript /*! * Bootstrap v3.3.2 (path_to_url */ if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.2",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.2",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active"));a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.2",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a(this.options.trigger).filter('[href="#'+b.id+'"], [data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.2",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0,trigger:'[data-toggle="collapse"]'},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":a.extend({},e.data(),{trigger:this});c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=c(d),f={relatedTarget:this};e.hasClass("open")&&(e.trigger(b=a.Event("hide.bs.dropdown",f)),b.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f)))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.2",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27|32)/.test(b.which)&&!/input|textarea/i.test(b.target.tagName)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g&&27!=b.which||g&&27==b.which)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(b.target);38==b.which&&j>0&&j--,40==b.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="menu"]',g.prototype.keydown).on("keydown.bs.dropdown.data-api",'[role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.2",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.options.backdrop&&d.adjustBackdrop(),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in").attr("aria-hidden",!1),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$element.find(".modal-dialog").one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a('<div class="modal-backdrop '+e+'" />').prependTo(this.$element).on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.options.backdrop&&this.adjustBackdrop(),this.adjustDialog()},c.prototype.adjustBackdrop=function(){this.$backdrop.css("height",0).css("height",this.$element[0].scrollHeight)},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){this.bodyIsOverflowing=document.body.scrollHeight>document.documentElement.clientHeight,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.3.2",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c&&c.$tip&&c.$tip.is(":visible")?void(c.hoverState="in"):(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.options.container?a(this.options.container):this.$element.parent(),p=this.getPosition(o);h="bottom"==h&&k.bottom+m>p.bottom?"top":"top"==h&&k.top-m<p.top?"bottom":"right"==h&&k.right+l>p.width?"left":"left"==h&&k.left-l<p.left?"right":h,f.removeClass(n).addClass(h)}var q=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(q,h);var r=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",r).emulateTransitionEnd(c.TRANSITION_DURATION):r()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=this.tip(),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type)})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.2",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.2",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.2",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e() }var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.2",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=a("body").height();"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); ```
/content/code_sandbox/autodoc/bespokesynth.com/js/bootstrap.min.js
javascript
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
9,751
```javascript /*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m}); ```
/content/code_sandbox/autodoc/bespokesynth.com/js/jquery.js
javascript
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
32,167
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the from django.apps import AppConfig class PanelConfig(AppConfig): name = 'panel' verbose_name = "" ```
/content/code_sandbox/panel/apps.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
70
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the from djchoices import DjangoChoices, C class ContractType(DjangoChoices): STOCK = C(label='') FUTURE = C(label='') OPTION = C(label='') class ExchangeType(DjangoChoices): SHFE = C(value='SHFE', label='') DCE = C(value='DCE', label='') CZCE = C(value='CZCE', label='') CFFEX = C(value='CFFEX', label='') INE = C(value='INE', label='') GFEX = C(value='GFEX', label='') class SectionType(DjangoChoices): Stock = C(label='') Bond = C(label='') Metal = C(label='') Agricultural = C(label='') EnergyChemical = C(label='') BlackMaterial = C(label='') class SortType(DjangoChoices): Stock = C(label='') Bond = C(label='') Rare = C(label='') Metal = C(label='') EdibleOil = C(label='') Feed = C(label='') Cotton = C(label='') EnergyChemical = C(label='') BlackMaterial = C(label='') class AddressType(DjangoChoices): TRADE = C(label='') MARKET = C(label='') class OperatorType(DjangoChoices): TELECOM = C(label='') UNICOM = C(label='') class DirectionType(DjangoChoices): LONG = C(label='', value=b'0'[0]) SHORT = C(label='', value=b'1'[0]) class CombOffsetFlag(DjangoChoices): # Open = C(label='', value='0') Close = C(label='', value='1') ForceClose = C(label='', value='2') CloseToday = C(label='', value='3') CloseYesterday = C(label='', value='4') ForceOff = C(label='', value='5') LocalForceClose = C(label='', value='6') class OffsetFlag(DjangoChoices): # Open = C(label='', value=b'0'[0]) Close = C(label='', value=b'1'[0]) ForceClose = C(label='', value=b'2'[0]) CloseToday = C(label='', value=b'3'[0]) CloseYesterday = C(label='', value=b'4'[0]) ForceOff = C(label='', value=b'5'[0]) LocalForceClose = C(label='', value=b'6'[0]) class OrderStatus(DjangoChoices): # AllTraded = C(value=b'0'[0], label='') PartTradedQueueing = C(value=b'1'[0], label='') PartTradedNotQueueing = C(value=b'2'[0], label='') NoTradeQueueing = C(value=b'3'[0], label='') NoTradeNotQueueing = C(value=b'4'[0], label='') Canceled = C(value=b'5'[0], label='') Unknown = C(value=b'a'[0], label='') NotTouched = C(value=b'b'[0], label='') Touched = C(value=b'c'[0], label='') class OrderSubmitStatus(DjangoChoices): # InsertSubmitted = C(value=b'0'[0], label='') CancelSubmitted = C(value=b'1'[0], label='') ModifySubmitted = C(value=b'2'[0], label='') Accepted = C(value=b'3'[0], label='') InsertRejected = C(value=b'4'[0], label='') CancelRejected = C(value=b'5'[0], label='') ModifyRejected = C(value=b'6'[0], label='') DCE_NAME_CODE = { '': 'a', '': 'b', '': 'bb', '': 'c', '': 'cs', '': 'fb', '': 'i', '': 'j', '': 'jd', '': 'jm', '': 'l', '': 'm', '': 'p', '': 'pp', '': 'v', '': 'eb', '': 'eg', '': 'pg', '': 'lh', '': 'rr', '': 'y', } MONTH_CODE = { 1: "F", 2: "G", 3: "H", 4: "J", 5: "K", 6: "M", 7: "N", 8: "Q", 9: "U", 10: "V", 11: "X", 12: "Z" } KT_MARKET = { 'DL': 'DCE', 'DY': 'DCE', 'SQ': 'SHFE', 'SY': 'SHFE', 'ZJ': 'CFFEX', 'ZZ': 'CZCE', 'ZY': 'CZCE', } class SignalType(DjangoChoices): ROLL_CLOSE = C(label='') ROLL_OPEN = C(label='') BUY = C(label='') SELL_SHORT = C(label='') SELL = C(label='') BUY_COVER = C(label='') class PriorityType(DjangoChoices): LOW = C(label='', value=0) Normal = C(label='', value=1) High = C(label='', value=2) ```
/content/code_sandbox/panel/const.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
1,185
```python #!/usr/bin/env python # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the ```
/content/code_sandbox/test/__init__.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
47
```python #!/usr/bin/env python # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import sys import os import django if sys.platform == 'darwin': sys.path.append('/Users/jeffchen/Documents/gitdir/dashboard') elif sys.platform == 'win32': sys.path.append(r'E:\GitHub\dashboard') else: sys.path.append('/root/dashboard') os.environ["DJANGO_SETTINGS_MODULE"] = "dashboard.settings" os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" django.setup() import asynctest from trader.utils import * from datetime import datetime from trader.utils.read_config import config class APITest(asynctest.TestCase): def setUp(self): self.redis_client = redis.StrictRedis( host=config.get('REDIS', 'host', fallback='localhost'), db=config.getint('REDIS', 'db', fallback=1), decode_responses=True) self.trading_day = datetime.strptime(self.redis_client.get("LastTradingDay"), '%Y%m%d') def tearDown(self) -> None: self.redis_client.close() @asynctest.skipIf(True, 'no need') async def test_get_shfe_data(self): self.assertTrue(await update_from_shfe(self.trading_day)) @asynctest.skipIf(False, 'no need') async def test_get_dce_data(self): self.assertTrue(await update_from_dce(self.trading_day)) @asynctest.skipIf(True, 'no need') async def test_get_czce_data(self): self.assertTrue(await update_from_czce(self.trading_day)) @asynctest.skipIf(True, 'no need') async def test_get_cffex_data(self): self.assertTrue(await update_from_cffex(self.trading_day)) @asynctest.skipIf(True, 'no need') async def test_get_contracts_argument(self): self.assertTrue(await get_contracts_argument(self.trading_day)) @asynctest.skipIf(True, 'no need') async def test_get_all(self): print(f'tradingday: {self.trading_day}') tasks = [ update_from_shfe(self.trading_day), update_from_dce(self.trading_day), update_from_czce(self.trading_day), update_from_cffex(self.trading_day), get_contracts_argument(self.trading_day) ] result = await asyncio.gather(*tasks, return_exceptions=True) self.assertEqual(result, [True, True, True, True, True]) @asynctest.skipIf(True, 'no need') async def test_load_from_kt(self): self.assertTrue(load_kt_data(r'D:\test')) @asynctest.skipIf(True, 'no need') async def test_create_main(self): inst = Instrument.objects.get(product_code='eb') self.assertTrue(create_main(inst)) @asynctest.skipIf(True, 'no need') async def test_calc_profit(self): for trade in Trade.objects.filter(close_time__isnull=True): bar = DailyBar.objects.filter(code=trade.code).order_by('-time').first() trade.profit = (bar.close - trade.avg_entry_price) * trade.filled_shares * trade.instrument.volume_multiple if trade.direction == DirectionType.values[DirectionType.SHORT]: trade.profit *= -1 trade.save(update_fields=['profit']) self.assertTrue(True) ```
/content/code_sandbox/test/test_api.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
748
```python import sys import os import django if sys.platform == 'darwin': sys.path.append('/Users/jeffchen/Documents/gitdir/dashboard') elif sys.platform == 'win32': sys.path.append(r'E:\github\dashboard') else: sys.path.append('/root/gitee/dashboard') os.environ["DJANGO_SETTINGS_MODULE"] = "dashboard.settings" os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" django.setup() import asyncio import datetime import pytz from trader.utils import update_from_czce if __name__ == "__main__": try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) day = datetime.datetime.now().replace(tzinfo=pytz.FixedOffset(480)) day = day - datetime.timedelta(days=1) loop.run_until_complete(update_from_czce(day)) print("DONE!") except KeyboardInterrupt: pass ```
/content/code_sandbox/test/test.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
194
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import sys import os import django if sys.platform == 'darwin': sys.path.append('/Users/jeffchen/Documents/gitdir/dashboard') elif sys.platform == 'win32': sys.path.append(r'E:\github\dashboard') else: sys.path.append('/root/gitee/dashboard') os.environ["DJANGO_SETTINGS_MODULE"] = "dashboard.settings" os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" django.setup() import redis import logging from logging import handlers from trader.strategy.brother2 import TradeStrategy from trader.utils.read_config import config_file, app_dir, config class RedislHandler(logging.StreamHandler): def __init__(self, channel: str): super().__init__() self.redis_client = redis.StrictRedis( host=config.get('REDIS', 'host', fallback='localhost'), port=config.getint('REDIS', 'port', fallback=6379), db=config.getint('REDIS', 'db', fallback=0), decode_responses=True) self.channel = channel def emit(self, message: logging.LogRecord): content = str(message.msg) self.redis_client.publish(self.channel, content) if __name__ == '__main__': os.path.exists(app_dir.user_log_dir) or os.makedirs(app_dir.user_log_dir) log_file = os.path.join(app_dir.user_log_dir, 'trader.log') file_handler = handlers.RotatingFileHandler(log_file, encoding='utf-8', maxBytes=1024*1024, backupCount=1) general_formatter = logging.Formatter(config.get('LOG', 'format')) file_handler.setFormatter(general_formatter) file_handler.setLevel(config.get('LOG', 'file_level', fallback='DEBUG')) console_handler = logging.StreamHandler() console_handler.setFormatter(general_formatter) console_handler.setLevel('DEBUG') redis_handler = RedislHandler(config.get('MSG_CHANNEL', 'weixin_log')) redis_handler.setFormatter(config.get('LOG', 'weixin_format')) redis_handler.setLevel(config.get('LOG', 'flower_level', fallback='INFO')) logger = logging.getLogger() logger.setLevel('DEBUG') logger.addHandler(file_handler) logger.addHandler(console_handler) logger.addHandler(redis_handler) logger = logging.getLogger("main") pid_path = os.path.join(app_dir.user_cache_dir, 'trader.pid') if not os.path.exists(pid_path): if not os.path.exists(app_dir.user_cache_dir): os.makedirs(app_dir.user_cache_dir) with open(pid_path, 'w') as pid_file: pid_file.write(str(os.getpid())) print('Big Brother is watching you!') print('used config file:', config_file) print('log stored in:', app_dir.user_log_dir) print('pid file:', pid_path) TradeStrategy(name='2.2').run() ```
/content/code_sandbox/trader/main.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
643
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # version is a human-readable version number. # version_info is a four-tuple for programmatic comparison. The first # three numbers are the components of the version number. The fourth # is zero for an official release, positive for a development branch, # or negative for a release candidate or beta (after the base version # number has been incremented) version = "0.1" version_info = (0, 1, 0, 0) ```
/content/code_sandbox/trader/__init__.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
144
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import pandas as pd from pandas.io.sql import read_sql_query from django.db import models from django.db import connection from django.core.exceptions import EmptyResultSet from .const import * def to_df(queryset, index_col=None, parse_dates=None): """ :param queryset: django.db.models.query.QuerySet :param index_col: str or list of str, optional, default: None :param parse_dates: list or dict, default: None :return: pandas.core.frame.DataFrame """ try: query, params = queryset.query.sql_with_params() except EmptyResultSet: # Occurs when Django tries to create an expression for a # query which will certainly be empty # e.g. Book.objects.filter(author__in=[]) return pd.DataFrame() return read_sql_query(query, connection, params=params, index_col=index_col, parse_dates=parse_dates) class Autonumber(models.Model): id = models.AutoField(verbose_name='', primary_key=True) create_date = models.DateTimeField(verbose_name='', auto_now_add=True) class Address(models.Model): name = models.CharField(verbose_name='', max_length=64) url = models.CharField(verbose_name='', max_length=128) type = models.CharField(verbose_name='', max_length=16, choices=AddressType.choices) operator = models.CharField(verbose_name='', max_length=16, choices=OperatorType.choices) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}{}-{}'.format(self.name, self.get_operator_display(), self.get_type_display()) class Broker(models.Model): name = models.CharField(verbose_name='', max_length=64) contract_type = models.CharField(verbose_name='', max_length=32, choices=ContractType.choices) trade_address = models.ForeignKey(Address, verbose_name='', on_delete=models.CASCADE, related_name='trade_address') market_address = models.ForeignKey(Address, verbose_name='', on_delete=models.CASCADE, related_name='market_address') identify = models.CharField(verbose_name='', max_length=32) username = models.CharField(verbose_name='', max_length=32) password = models.CharField(verbose_name='', max_length=32) fake = models.DecimalField(verbose_name='', null=True, max_digits=12, decimal_places=2) cash = models.DecimalField(verbose_name='', null=True, max_digits=12, decimal_places=2) current = models.DecimalField(verbose_name='', null=True, max_digits=12, decimal_places=2) pre_balance = models.DecimalField(verbose_name='', null=True, max_digits=12, decimal_places=2) margin = models.DecimalField(verbose_name='', null=True, max_digits=12, decimal_places=2) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}-{}'.format(self.name, self.get_contract_type_display()) class Performance(models.Model): broker = models.ForeignKey(Broker, verbose_name='', on_delete=models.CASCADE) day = models.DateField(verbose_name='') capital = models.DecimalField(verbose_name='', max_digits=12, decimal_places=2) unit_count = models.IntegerField(verbose_name='', null=True) NAV = models.DecimalField(verbose_name='', max_digits=8, decimal_places=3, null=True) accumulated = models.DecimalField(verbose_name='', max_digits=8, decimal_places=3, null=True) dividend = models.DecimalField(verbose_name='', max_digits=12, decimal_places=2, null=True) used_margin = models.DecimalField(verbose_name='', null=True, max_digits=12, decimal_places=2) fake = models.DecimalField(verbose_name='', max_digits=12, decimal_places=2, null=True) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}-{}'.format(self.broker, self.NAV) class Strategy(models.Model): broker = models.ForeignKey(Broker, verbose_name='', on_delete=models.CASCADE) name = models.CharField(verbose_name='', max_length=64) instruments = models.ManyToManyField('Instrument', verbose_name='') force_opens = models.ManyToManyField('Instrument', verbose_name='', related_name='force_opens', blank=True) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}'.format(self.name) def get_instruments(self): return [inst for inst in self.instruments.all()] get_instruments.short_description = '' get_instruments.allow_tags = True def get_force_opens(self): return [inst for inst in self.force_opens.all()] get_force_opens.short_description = '' get_force_opens.allow_tags = True class Param(models.Model): strategy = models.ForeignKey(Strategy, verbose_name='', on_delete=models.CASCADE) code = models.CharField('', max_length=64) str_value = models.CharField('', max_length=128, null=True, blank=True) int_value = models.IntegerField('', null=True, blank=True) float_value = models.DecimalField('', null=True, max_digits=12, decimal_places=3, blank=True) update_time = models.DateTimeField('', auto_now=True) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}: {} = {}'.format( self.strategy, self.code, next((v for v in [self.str_value, self.int_value, self.float_value] if v is not None), '-')) class Instrument(models.Model): exchange = models.CharField('', max_length=8, choices=ExchangeType.choices) section = models.CharField('', max_length=48, null=True, blank=True, choices=SectionType.choices) sort = models.CharField('', max_length=48, null=True, blank=True, choices=SortType.choices) name = models.CharField('', max_length=32, null=True, blank=True) product_code = models.CharField('', max_length=16, unique=True) all_inst = models.CharField('', max_length=256, null=True, blank=True) main_code = models.CharField('', max_length=16, null=True, blank=True) last_main = models.CharField('', max_length=16, null=True, blank=True) change_time = models.DateTimeField('', null=True, blank=True) night_trade = models.BooleanField('', default=False) volume_multiple = models.IntegerField('', null=True, blank=True) price_tick = models.DecimalField('', max_digits=8, decimal_places=3, null=True, blank=True) margin_rate = models.DecimalField('', max_digits=6, decimal_places=5, null=True, blank=True) fee_money = models.DecimalField('', max_digits=7, decimal_places=6, null=True, blank=True) fee_volume = models.DecimalField('', max_digits=6, decimal_places=2, null=True, blank=True) up_limit_ratio = models.DecimalField('', max_digits=3, decimal_places=2, null=True, blank=True) down_limit_ratio = models.DecimalField('', max_digits=3, decimal_places=2, null=True, blank=True) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}.{}'.format(self.get_exchange_display(), self.name) class Signal(models.Model): strategy = models.ForeignKey(Strategy, verbose_name='', on_delete=models.CASCADE) instrument = models.ForeignKey(Instrument, verbose_name='', on_delete=models.CASCADE) code = models.CharField('', max_length=16, null=True) type = models.CharField('', max_length=16, choices=SignalType.choices) trigger_value = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True, blank=True) price = models.DecimalField('', max_digits=12, decimal_places=3, null=True, blank=True) volume = models.IntegerField('', null=True, blank=True) trigger_time = models.DateTimeField('') priority = models.IntegerField('', choices=PriorityType.choices, default=PriorityType.Normal) processed = models.BooleanField('', default=False, blank=True) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return f"{self.instrument}({self.code}){self.type}{self.volume}" \ f"{'()' if self.instrument.night_trade else ''}" class MainBar(models.Model): exchange = models.CharField('', max_length=8, choices=ExchangeType.choices) product_code = models.CharField('', max_length=8, null=True, db_index=True) code = models.CharField('', max_length=16, null=True, blank=True) time = models.DateField('', db_index=True) open = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') high = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') low = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') close = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') settlement = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True) volume = models.IntegerField('') open_interest = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') basis = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True) class Meta: verbose_name = 'K' verbose_name_plural = 'K' def __str__(self): return '{}.{}'.format(self.exchange, self.product_code) class DailyBar(models.Model): exchange = models.CharField('', max_length=8, choices=ExchangeType.choices) code = models.CharField('', max_length=16, null=True, db_index=True) expire_date = models.IntegerField('', null=True) time = models.DateField('', db_index=True) open = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') high = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') low = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') close = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') settlement = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True) volume = models.IntegerField('') open_interest = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') class Meta: verbose_name = 'K' verbose_name_plural = 'K' def __str__(self): return '{}.{}'.format(self.exchange, self.code) class Order(models.Model): broker = models.ForeignKey(Broker, verbose_name='', on_delete=models.CASCADE) strategy = models.ForeignKey(Strategy, verbose_name='', on_delete=models.SET_NULL, null=True, blank=True) order_ref = models.CharField('', max_length=13) instrument = models.ForeignKey(Instrument, verbose_name='', on_delete=models.CASCADE) code = models.CharField('', max_length=16, null=True, blank=True) front = models.IntegerField('') session = models.IntegerField('') price = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='') volume = models.IntegerField('', blank=True, null=True) direction = models.CharField('', max_length=8, choices=DirectionType.choices) offset_flag = models.CharField('', max_length=8, choices=OffsetFlag.choices) status = models.CharField('', max_length=16, choices=OrderStatus.choices) send_time = models.DateTimeField('') update_time = models.DateTimeField('') signal = models.OneToOneField(Signal, verbose_name='', on_delete=models.SET_NULL, null=True, blank=True) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}-{}'.format(self.instrument, self.get_offset_flag_display()) class Trade(models.Model): broker = models.ForeignKey(Broker, verbose_name='', on_delete=models.CASCADE) strategy = models.ForeignKey(Strategy, verbose_name='', on_delete=models.SET_NULL, null=True, blank=True) instrument = models.ForeignKey(Instrument, verbose_name='', on_delete=models.CASCADE) open_order = models.OneToOneField(Order, verbose_name='', on_delete=models.SET_NULL, related_name='open_order', null=True, blank=True) close_order = models.OneToOneField(Order, verbose_name='', on_delete=models.SET_NULL, related_name='close_order', null=True, blank=True) code = models.CharField('', max_length=16, null=True, blank=True) direction = models.CharField('', max_length=8, choices=DirectionType.choices) open_time = models.DateTimeField('') close_time = models.DateTimeField('', null=True, blank=True) shares = models.IntegerField('', null=True, blank=True) filled_shares = models.IntegerField('', null=True, blank=True) closed_shares = models.IntegerField('', null=True, blank=True) avg_entry_price = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True, blank=True) avg_exit_price = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True, blank=True) profit = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True, blank=True) frozen_margin = models.DecimalField(max_digits=12, decimal_places=3, verbose_name='', null=True, blank=True) cost = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='', null=True, blank=True) class Meta: verbose_name = '' verbose_name_plural = '' def __str__(self): return '{}{}{}'.format(self.instrument, self.direction, self.shares) ```
/content/code_sandbox/panel/models.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
2,876
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import logging from trader.utils.read_config import * def get_my_logger(logger_name='main'): logger = logging.getLogger(logger_name) if logger.handlers: return logger log_file = os.path.join(app_dir.user_log_dir, '{}.log'.format(logger_name)) if not os.path.exists(app_dir.user_log_dir): os.makedirs(app_dir.user_log_dir) formatter = logging.Formatter(config.get('LOG', 'format', fallback="%(asctime)s %(name)s [%(levelname)s] %(message)s")) file_handler = logging.FileHandler(log_file, encoding='utf-8') file_handler.setFormatter(formatter) console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logger.setLevel(config.get('LOG', 'level', fallback='ERROR')) logger.addHandler(file_handler) logger.addHandler(console_handler) return logger ```
/content/code_sandbox/trader/utils/my_logger.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
225
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import logging import ujson as json from decimal import Decimal import datetime import math import re import xml.etree.ElementTree as ET import asyncio import os from functools import reduce from itertools import combinations import pytz import aiohttp from django.db.models import Q, F, Max, Min from django.utils import timezone import redis from talib import ATR from tqdm import tqdm from panel.models import * from trader.utils import ApiStruct from trader.utils.read_config import config logger = logging.getLogger('utils') max_conn_shfe = asyncio.Semaphore(15) max_conn_dce = asyncio.Semaphore(5) max_conn_gfex = asyncio.Semaphore(5) max_conn_czce = asyncio.Semaphore(15) max_conn_cffex = asyncio.Semaphore(15) max_conn_sina = asyncio.Semaphore(15) cffex_ip = 'www.cffex.com.cn' # www.cffex.com.cn shfe_ip = 'www.shfe.com.cn' # www.shfe.com.cn czce_ip = 'www.czce.com.cn' # www.czce.com.cn dce_ip = 'www.dce.com.cn' # www.dce.com.cn gfex_ip = 'www.gfex.com.cn' IGNORE_INST_LIST = config.get('TRADE', 'ignore_inst').split(',') INE_INST_LIST = ['sc', 'bc', 'nr', 'lu'] ORDER_REF_SIGNAL_ID_START = -5 def str_to_number(s): try: if not isinstance(s, str): return s return int(s) except ValueError: return float(s) def price_round(x: Decimal, base: Decimal): """ IF0.2 1.3 -> 1.2, 1.5 -> 1.4 :param x: Decimal :param base: Decimal :return: float """ if not type(x) is Decimal: x = Decimal(x) if not type(base) is Decimal: base = Decimal(base) precision = 0 s = str(round(base, 3) % 1) s = s.rstrip('0').rstrip('.') if '.' in s else s p1, *p2 = s.split('.') if p2: precision = len(p2[0]) return round(base * round(x / base), precision) def get_next_id(): if not hasattr(get_next_id, "request_id"): get_next_id.request_id = 0 get_next_id.request_id = 1 if get_next_id.request_id == 65535 else get_next_id.request_id + 1 return get_next_id.request_id async def is_trading_day(day: datetime.datetime): s = redis.StrictRedis( host=config.get('REDIS', 'host', fallback='localhost'), db=config.getint('REDIS', 'db', fallback=0), decode_responses=True) return day, day.strftime('%Y%m%d') in (s.get('TradingDay'), s.get('LastTradingDay')) async def check_trading_day(day: datetime.datetime) -> (datetime.datetime, bool): async with aiohttp.ClientSession() as session: await max_conn_cffex.acquire() async with session.get( 'http://{}/fzjy/mrhq/{}/index.xml'.format(cffex_ip, day.strftime('%Y%m/%d')), allow_redirects=False) as response: max_conn_cffex.release() return day, response.status == 200 def get_expire_date(inst_code: str, day: datetime.datetime): expire_date = int(re.findall(r'\d+', inst_code)[0]) if expire_date < 1000: year_exact = math.floor(day.year % 100 / 10) if expire_date < 100 and day.year % 10 == 9: year_exact += 1 expire_date += year_exact * 1000 return expire_date async def update_from_shfe(day: datetime.datetime) -> bool: try: async with aiohttp.ClientSession() as session: day_str = day.strftime('%Y%m%d') await max_conn_shfe.acquire() async with session.get(f'http://{shfe_ip}/data/tradedata/future/dailydata/kx{day_str}.dat') as response: rst = await response.read() rst_json = json.loads(rst) max_conn_shfe.release() inst_name_dict = {} for inst_data in rst_json['o_curinstrument']: """ {"PRODUCTID":"cu_f ","PRODUCTGROUPID":"cu ","PRODUCTSORTNO":10,"PRODUCTNAME":" ", "DELIVERYMONTH":"2112","PRESETTLEMENTPRICE":69850,"OPENPRICE":69770,"HIGHESTPRICE":70280,"LOWESTPRICE":69600, "CLOSEPRICE":69900,"SETTLEMENTPRICE":69950,"ZD1_CHG":50,"ZD2_CHG":100,"VOLUME":19450,"TURNOVER":680294.525, "TASVOLUME":"","OPENINTEREST":19065,"OPENINTERESTCHG":-5585,"ORDERNO":0,"ORDERNO2":0} """ # error_data = inst_data if inst_data['DELIVERYMONTH'] == '' or inst_data['PRODUCTID'] == '': continue if '_f' not in inst_data['PRODUCTID']: continue # logger.info(f'inst_data: {inst_data}') code = inst_data['PRODUCTGROUPID'].strip() if code in IGNORE_INST_LIST: continue name = inst_data['PRODUCTNAME'].strip() if code not in inst_name_dict: inst_name_dict[code] = name exchange_str = ExchangeType.SHFE # if code in INE_INST_LIST: exchange_str = ExchangeType.INE DailyBar.objects.update_or_create( code=code + inst_data['DELIVERYMONTH'], exchange=exchange_str, time=day, defaults={ 'expire_date': inst_data['DELIVERYMONTH'], 'open': inst_data['OPENPRICE'] if inst_data['OPENPRICE'] else inst_data['CLOSEPRICE'], 'high': inst_data['HIGHESTPRICE'] if inst_data['HIGHESTPRICE'] else inst_data['CLOSEPRICE'], 'low': inst_data['LOWESTPRICE'] if inst_data['LOWESTPRICE'] else inst_data['CLOSEPRICE'], 'close': inst_data['CLOSEPRICE'], 'settlement': inst_data['SETTLEMENTPRICE'] if inst_data['SETTLEMENTPRICE'] else inst_data['PRESETTLEMENTPRICE'], 'volume': inst_data['VOLUME'] if inst_data['VOLUME'] else 0, 'open_interest': inst_data['OPENINTEREST'] if inst_data['OPENINTEREST'] else 0}) # for code, name in inst_name_dict.items(): Instrument.objects.filter(product_code=code).update(name=name) return True except Exception as e: logger.warning(f'update_from_shfe failed: {repr(e)}', exc_info=True) return False async def update_from_czce(day: datetime.datetime) -> bool: try: async with aiohttp.ClientSession() as session: day_str = day.strftime('%Y%m%d') async with session.get( f'http://{czce_ip}/cn/DFSStaticFiles/Future/{day.year}/{day_str}/FutureDataDaily.txt') as response: rst = await response.text() for lines in rst.split('\n')[1:-3]: if '' in lines or '' in lines or '' in lines: continue inst_data = [x.strip() for x in lines.split('|' if '|' in lines else ',')] """ [0'', 1'', 2'', 3'', 4'', 5'', 6'', 7'1', 8'2', 9'()', 10'', 11'', 12'()', 13''] ['CF601', '11,970.00', '11,970.00', '11,970.00', '11,800.00', '11,870.00', '11,905.00', '-100.00', '-65.00', '13,826', '59,140', '-10,760', '82,305.24', ''] """ # print(f'inst_data: {inst_data}') if re.findall('[A-Za-z]+', inst_data[0])[0] in IGNORE_INST_LIST: continue close = inst_data[5].replace(',', '') if Decimal(inst_data[5].replace(',', '')) > 0.1 \ else inst_data[6].replace(',', '') DailyBar.objects.update_or_create( code=inst_data[0], exchange=ExchangeType.CZCE, time=day, defaults={ 'expire_date': get_expire_date(inst_data[0], day), 'open': inst_data[2].replace(',', '') if Decimal(inst_data[2].replace(',', '')) > 0.1 else close, 'high': inst_data[3].replace(',', '') if Decimal(inst_data[3].replace(',', '')) > 0.1 else close, 'low': inst_data[4].replace(',', '') if Decimal(inst_data[4].replace(',', '')) > 0.1 else close, 'close': close, 'settlement': inst_data[6].replace(',', '') if Decimal(inst_data[6].replace(',', '')) > 0.1 else inst_data[1].replace(',', ''), 'volume': inst_data[9].replace(',', ''), 'open_interest': inst_data[10].replace(',', '')}) return True except Exception as e: logger.warning(f'update_from_czce failed: {repr(e)}', exc_info=True) return False async def update_from_dce(day: datetime.datetime) -> bool: try: async with aiohttp.ClientSession() as session: await max_conn_dce.acquire() async with session.post(f'http://{dce_ip}/publicweb/quotesdata/exportDayQuotesChData.html', data={ 'dayQuotes.variety': 'all', 'dayQuotes.trade_type': 0, 'exportFlag': 'txt', 'year': day.year, 'month': day.month-1, 'day': day.day}) as response: rst = await response.text() max_conn_dce.release() for lines in rst.split('\r\n')[3:-3]: if '' in lines or '' in lines: continue inst_data_raw = [x.strip() for x in lines.split('\t')] inst_data = [] for cell in inst_data_raw: if len(cell) > 0: inst_data.append(cell) """ [0'', 1'', 2'', 3'', 4'', 5'', 6'', 7'', 8'', 9'1', 10'', 11'', 12'', 13''] ['', '1611', '3,760', '3,760', '3,760', '3,760', '3,860', '3,760', '-100', '-100', '2', '0', '0', '7.52'] """ if '' in inst_data[0]: continue if DCE_NAME_CODE[inst_data[0]] in IGNORE_INST_LIST: continue expire_date = inst_data[1].removeprefix(DCE_NAME_CODE[inst_data[0]]) DailyBar.objects.update_or_create( code=inst_data[1], exchange=ExchangeType.DCE, time=day, defaults={ 'expire_date': expire_date, 'open': inst_data[2].replace(',', '') if inst_data[2] != '-' else inst_data[5].replace(',', ''), 'high': inst_data[3].replace(',', '') if inst_data[3] != '-' else inst_data[5].replace(',', ''), 'low': inst_data[4].replace(',', '') if inst_data[4] != '-' else inst_data[5].replace(',', ''), 'close': inst_data[5].replace(',', ''), 'settlement': inst_data[7].replace(',', '') if inst_data[7] != '-' else inst_data[6].replace(',', ''), 'volume': inst_data[10].replace(',', ''), 'open_interest': inst_data[11].replace(',', '')}) return True except Exception as e: logger.warning(f'update_from_dce failed: {repr(e)}', exc_info=True) return False async def update_from_gfex(day: datetime.datetime) -> bool: try: async with aiohttp.ClientSession() as session: await max_conn_gfex.acquire() for ids in ['lc', 'si']: async with session.post(f'http://{gfex_ip}/gfexweb/Quote/getQuote_ftr', data={'varietyid': ids}) as response: rst = await response.text() rst = json.loads(rst) max_conn_gfex.release() for inst_code, inst_data in rst['contractQuote'].items(): expire_date = inst_code.removeprefix(ids) DailyBar.objects.update_or_create( code=inst_code, exchange=ExchangeType.GFEX, time=day, defaults={ 'expire_date': expire_date, 'open': inst_data['openPrice'] if inst_data['openPrice'] != "--" else inst_data['closePrice'], 'high': inst_data['highPrice'] if inst_data['highPrice'] != "--" else inst_data['closePrice'], 'low': inst_data['lowPrice'] if inst_data['lowPrice'] != "--" else inst_data['closePrice'], 'close': inst_data['closePrice'], 'settlement': inst_data['clearPrice'], 'volume': inst_data['matchTotQty'] if inst_data['matchTotQty'] != "--" else 0, 'open_interest': inst_data['openInterest'] if inst_data['openInterest'] != "--" else 0}) except Exception as e: logger.warning(f'update_from_gfex failed: {repr(e)}', exc_info=True) return False return True async def update_from_cffex(day: datetime.datetime) -> bool: try: async with aiohttp.ClientSession() as session: await max_conn_cffex.acquire() async with session.get(f"http://{cffex_ip}/sj/hqsj/rtj/{day.strftime('%Y%m/%d')}/index.xml?id=7") as response: rst = await response.text() max_conn_cffex.release() tree = ET.fromstring(rst) for inst_data in tree: """ <dailydata> <instrumentid>IC2112</instrumentid> <tradingday>20211209</tradingday> <openprice>7272</openprice> <highestprice>7330</highestprice> <lowestprice>7264.4</lowestprice> <closeprice>7302.4</closeprice> <preopeninterest>107546</preopeninterest> <openinterest>101956</openinterest> <presettlementprice>7274.4</presettlementprice> <settlementpriceif>7314.2</settlementpriceif> <settlementprice>7314.2</settlementprice> <volume>51752</volume> <turnover>75570943720</turnover> <productid>IC</productid> <delta/> <expiredate>20211217</expiredate> </dailydata> """ # if len(inst_data.findtext('instrumentid').strip()) > 6: continue if inst_data.findtext('productid').strip() in IGNORE_INST_LIST: continue DailyBar.objects.update_or_create( code=inst_data.findtext('instrumentid').strip(), exchange=ExchangeType.CFFEX, time=day, defaults={ 'expire_date': inst_data.findtext('expiredate')[2:6], 'open': inst_data.findtext('openprice').replace(',', '') if inst_data.findtext( 'openprice') else inst_data.findtext('closeprice').replace(',', ''), 'high': inst_data.findtext('highestprice').replace(',', '') if inst_data.findtext( 'highestprice') else inst_data.findtext('closeprice').replace(',', ''), 'low': inst_data.findtext('lowestprice').replace(',', '') if inst_data.findtext( 'lowestprice') else inst_data.findtext('closeprice').replace(',', ''), 'close': inst_data.findtext('closeprice').replace(',', ''), 'settlement': inst_data.findtext('settlementprice').replace(',', '') if inst_data.findtext('settlementprice') else inst_data.findtext('presettlementprice').replace(',', ''), 'volume': inst_data.findtext('volume').replace(',', ''), 'open_interest': inst_data.findtext('openinterest').replace(',', '')}) return True except Exception as e: logger.warning(f'update_from_cffex failed: {repr(e)}', exc_info=True) return False def store_main_bar(inst: Instrument, bar: DailyBar): MainBar.objects.update_or_create( exchange=inst.exchange, product_code=inst.product_code, time=bar.time, defaults={ 'code': bar.code, 'open': bar.open, 'high': bar.high, 'low': bar.low, 'close': bar.close, 'settlement': bar.settlement, 'volume': bar.volume, 'open_interest': bar.open_interest}) def handle_rollover(inst: Instrument, new_bar: DailyBar): """ , =-, OHLC """ old_bar = DailyBar.objects.filter(exchange=inst.exchange, code=inst.last_main, time=new_bar.time).first() main_bar = MainBar.objects.get(exchange=inst.exchange, product_code=inst.product_code, time=new_bar.time) old_close = old_bar.close if old_bar else new_bar.close basis = new_bar.close - old_close main_bar.basis = basis basis = float(basis) main_bar.save(update_fields=['basis']) MainBar.objects.filter(exchange=inst.exchange, product_code=inst.product_code, time__lt=new_bar.time).update( open=F('open') + basis, high=F('high') + basis, low=F('low') + basis, close=F('close') + basis, settlement=F('settlement') + basis) def calc_main_inst(inst: Instrument, day: datetime.datetime): updated = False expire_date = get_expire_date(inst.main_code, day) if inst.main_code else day.strftime('%y%m') # 1: & (>1 & >1 or ) = check_bar = DailyBar.objects.filter( (Q(exchange=ExchangeType.CFFEX) | (Q(volume__gte=10000) & Q(open_interest__gte=10000))), exchange=inst.exchange, code__regex=f"^{inst.product_code}[0-9]+", expire_date__gte=expire_date, time=day.date()).order_by('-volume').first() # 2: 13 = if check_bar is None: check_bars = DailyBar.objects.raw( "SELECT a.* from panel_dailybar a INNER JOIN (SELECT time, max(volume) v FROM panel_dailybar " "WHERE CODE RLIKE %s and time<=%s GROUP BY time ORDER BY time DESC LIMIT 3) b " "WHERE a.time=b.time and a.volume=b.v ORDER BY a.time DESC LIMIT 3", [f"^{inst.product_code}[0-9]+", day]) check_bar = check_bars[0] if len(set(bar.code for bar in check_bars)) == 1 else None # 3: if check_bar is None: check_bar = DailyBar.objects.filter( exchange=inst.exchange, code__regex=f"^{inst.product_code}[0-9]+", expire_date__gte=expire_date, time=day.date()).order_by('-volume', '-open_interest', 'code').first() if check_bar is None: check_bar = DailyBar.objects.filter(code=inst.main_code).last() logger.error(f"calc_main_inst {inst} ") if inst.main_code is None: # inst.main_code = check_bar.code inst.change_time = day inst.save(update_fields=['main_code', 'change_time']) store_main_bar(inst, check_bar) else: # , if check_bar and inst.main_code != check_bar.code and check_bar.code > inst.main_code: inst.last_main = inst.main_code inst.main_code = check_bar.code inst.change_time = day inst.save(update_fields=['last_main', 'main_code', 'change_time']) store_main_bar(inst, check_bar) handle_rollover(inst, check_bar) updated = True else: store_main_bar(inst, check_bar) return inst.main_code, updated def create_main(inst: Instrument): print('processing ', inst.product_code) if inst.change_time is None: for day in DailyBar.objects.filter( # time__gte=datetime.datetime.strptime('20211211', '%Y%m%d'), exchange=inst.exchange, code__regex='^{}[0-9]+'.format(inst.product_code)).order_by( 'time').values_list('time', flat=True).distinct(): print(day, calc_main_inst(inst, timezone.make_aware(datetime.datetime.combine(day, datetime.time.min)))) else: for day in DailyBar.objects.filter( time__gt=inst.change_time, exchange=inst.exchange, code__regex='^{}[0-9]+'.format(inst.product_code)).order_by( 'time').values_list('time', flat=True).distinct(): print(day, calc_main_inst(inst, timezone.make_aware(datetime.datetime.combine(day, datetime.time.min)))) return True def create_main_all(): for inst in Instrument.objects.all(): create_main(inst) print('all done!') def is_auction_time(inst: Instrument, status: dict): if status['InstrumentStatus'] == ApiStruct.IS_AuctionOrdering: now = timezone.localtime() if inst.exchange == ExchangeType.CFFEX: return True # 20:55 if inst.night_trade and now.hour == 20: return True # 8:55 if not inst.night_trade and now.hour == 8: return True return False def calc_sma(price, period): return reduce(lambda x, y: ((period - 1) * x + y) / period, price) def calc_corr(day: datetime.datetime): price_dict = dict() begin_day = day.replace(year=day.year - 3) for code in Strategy.objects.get(name='2.0').instruments.all().order_by('id').values_list( 'product_code', flat=True): price_dict[code] = to_df(MainBar.objects.filter( time__gte=begin_day.date(), product_code=code).order_by('time').values_list('time', 'close'), index_col='time', parse_dates=['time']) price_dict[code].index = pd.DatetimeIndex(price_dict[code].time) price_dict[code]['price'] = price_dict[code].close.pct_change() return pd.DataFrame({k: v.price for k, v in price_dict.items()}).corr() def nCr(n, r): f = math.factorial return f(n) / f(r) / f(n-r) def find_best_score(n: int = 20): """ 5100.. """ corr_matrix = calc_corr(datetime.datetime.today()) code_list = Strategy.objects.get(name='2.0').instruments.all().order_by('id').values_list( 'product_code', flat=True) result = list() for code_list in tqdm(combinations(code_list, n), total=nCr(code_list.count(), n)): score_df = pd.DataFrame([corr_matrix.iloc[i, j] for i, j in combinations(code_list, 2)]) score = (round((1 - (score_df.abs() ** 2).mean()[0]) * 100, 3) - 50) * 2 result.append((score, ','.join(code_list))) result.sort(key=lambda tup: tup[0]) print(': ', result[-3:]) print(': ', result[:3]) def calc_history_signal(inst: Instrument, day: datetime.datetime, strategy: Strategy): break_n = strategy.param_set.get(code='BreakPeriod').int_value atr_n = strategy.param_set.get(code='AtrPeriod').int_value long_n = strategy.param_set.get(code='LongPeriod').int_value short_n = strategy.param_set.get(code='ShortPeriod').int_value stop_n = strategy.param_set.get(code='StopLoss').int_value df = to_df(MainBar.objects.filter( time__lte=day.date(), exchange=inst.exchange, product_code=inst.product_code).order_by('time').values_list( 'time', 'open', 'high', 'low', 'close', 'settlement'), index_col='time', parse_dates=['time']) df.index = pd.DatetimeIndex(df.time, tz=pytz.FixedOffset(480)) df['atr'] = ATR(df.high, df.low, df.close, timeperiod=atr_n) # df columns: 0:time,1:open,2:high,3:low,4:close,5:settlement,6:atr,7:short_trend,8:long_trend df['short_trend'] = df.close df['long_trend'] = df.close for idx in range(1, df.shape[0]): df.iloc[idx, 7] = (df.iloc[idx - 1, 7] * (short_n - 1) + df.iloc[idx, 4]) / short_n df.iloc[idx, 8] = (df.iloc[idx - 1, 8] * (long_n - 1) + df.iloc[idx, 4]) / long_n df['high_line'] = df.close.rolling(window=break_n).max() df['low_line'] = df.close.rolling(window=break_n).min() cur_pos = 0 last_trade = None for cur_idx in range(break_n+1, df.shape[0]): idx = cur_idx - 1 cur_date = df.index[cur_idx].to_pydatetime() prev_date = df.index[idx].to_pydatetime() if cur_pos == 0: if df.short_trend[idx] > df.long_trend[idx] and int(df.close[idx]) >= int(df.high_line[idx-1]): new_bar = MainBar.objects.filter( exchange=inst.exchange, product_code=inst.product_code, time=cur_date).first() Signal.objects.create( code=new_bar.code, trigger_value=df.atr[idx], strategy=strategy, instrument=inst, type=SignalType.BUY, processed=True, trigger_time=prev_date, price=new_bar.open, volume=1, priority=PriorityType.LOW) last_trade = Trade.objects.create( broker=strategy.broker, strategy=strategy, instrument=inst, code=new_bar.code, direction=DirectionType.values[DirectionType.LONG], open_time=cur_date, shares=1, filled_shares=1, avg_entry_price=new_bar.open) cur_pos = cur_idx elif df.short_trend[idx] < df.long_trend[idx] and int(df.close[idx]) < int(df.low_line[idx-1]): new_bar = MainBar.objects.filter( exchange=inst.exchange, product_code=inst.product_code, time=df.index[cur_idx].to_pydatetime().date()).first() Signal.objects.create( code=new_bar.code, trigger_value=df.atr[idx], strategy=strategy, instrument=inst, type=SignalType.SELL_SHORT, processed=True, trigger_time=prev_date, price=new_bar.open, volume=1, priority=PriorityType.LOW) last_trade = Trade.objects.create( broker=strategy.broker, strategy=strategy, instrument=inst, code=new_bar.code, direction=DirectionType.values[DirectionType.SHORT], open_time=cur_date, shares=1, filled_shares=1, avg_entry_price=new_bar.open) cur_pos = cur_idx * -1 elif cur_pos > 0 and prev_date > last_trade.open_time: hh = float(MainBar.objects.filter( exchange=inst.exchange, product_code=inst.product_code, time__gte=last_trade.open_time, time__lt=prev_date).aggregate(Max('high'))['high__max']) if df.close[idx] <= hh - df.atr[cur_pos-1] * stop_n: new_bar = MainBar.objects.filter( exchange=inst.exchange, product_code=inst.product_code, time=df.index[cur_idx].to_pydatetime().date()).first() Signal.objects.create( strategy=strategy, instrument=inst, type=SignalType.SELL, processed=True, code=new_bar.code, trigger_time=prev_date, price=new_bar.open, volume=1, priority=PriorityType.LOW) last_trade.avg_exit_price = new_bar.open last_trade.close_time = cur_date last_trade.closed_shares = 1 last_trade.profit = (new_bar.open - last_trade.avg_entry_price) * inst.volume_multiple last_trade.save() cur_pos = 0 elif cur_pos < 0 and prev_date > last_trade.open_time: ll = float(MainBar.objects.filter( exchange=inst.exchange, product_code=inst.product_code, time__gte=last_trade.open_time, time__lt=prev_date).aggregate(Min('low'))['low__min']) if df.close[idx] >= ll + df.atr[cur_pos * -1-1] * stop_n: new_bar = MainBar.objects.filter( exchange=inst.exchange, product_code=inst.product_code, time=df.index[cur_idx].to_pydatetime().date()).first() Signal.objects.create( code=new_bar.code, strategy=strategy, instrument=inst, type=SignalType.BUY_COVER, processed=True, trigger_time=prev_date, price=new_bar.open, volume=1, priority=PriorityType.LOW) last_trade.avg_exit_price = new_bar.open last_trade.close_time = cur_date last_trade.closed_shares = 1 last_trade.profit = (last_trade.avg_entry_price - new_bar.open) * inst.volume_multiple last_trade.save() cur_pos = 0 if cur_pos != 0 and cur_date.date() == day.date(): last_trade.avg_exit_price = df.open[cur_idx] last_trade.close_time = cur_date last_trade.closed_shares = 1 if last_trade.direction == DirectionType.values[DirectionType.LONG]: last_trade.profit = (last_trade.avg_entry_price - Decimal(df.open[cur_idx])) * \ inst.volume_multiple else: last_trade.profit = (Decimal(df.open[cur_idx]) - last_trade.avg_entry_price) * \ inst.volume_multiple last_trade.save() def calc_his_all(day: datetime.datetime): strategy = Strategy.objects.get(name='2.0') print(f'calc_his_all day: {day} stragety: {strategy}') for inst in strategy.instruments.all(): print('process', inst) last_day = Trade.objects.filter(instrument=inst, close_time__isnull=True).values_list( 'open_time', flat=True).first() if last_day is None: last_day = datetime.datetime.combine( MainBar.objects.filter(product_code=inst.product_code, time__lte=day).order_by( '-time').values_list('time', flat=True).first(), timezone.make_aware(datetime.time.min)) calc_history_signal(inst, last_day, strategy) def calc_his_up_limit(inst: Instrument, bar: DailyBar): ratio = inst.up_limit_ratio ratio = Decimal(round(ratio, 3)) price = price_round(bar.settlement * (Decimal(1) + ratio), inst.price_tick) return price - inst.price_tick def calc_his_down_limit(inst: Instrument, bar: DailyBar): ratio = inst.down_limit_ratio ratio = Decimal(round(ratio, 3)) price = price_round(bar.settlement * (Decimal(1) - ratio), inst.price_tick) return price + inst.price_tick async def clean_daily_bar(): day = timezone.make_aware(datetime.datetime.strptime('20100416', '%Y%m%d')) end = timezone.make_aware(datetime.datetime.strptime('20160118', '%Y%m%d')) tasks = [] while day <= end: tasks.append(is_trading_day(day)) day += datetime.timedelta(days=1) trading_days = [] for f in tqdm(asyncio.as_completed(tasks), total=len(tasks)): rst = await f trading_days.append(rst) tasks.clear() for day, trading in trading_days: if not trading: DailyBar.objects.filter(time=day.date()).delete() print('done!') def load_kt_data(directory: str = r'D:\test'): """PK99.txt 1210224,10944.000 ,10992.000 ,10758.000 ,10904.000 ,10702.000 ,42202 ,20897 ,PK2110 """ try: for filename in os.listdir(directory): if not filename.endswith(".txt"): continue code = filename.split('9', maxsplit=1)[0] inst = Instrument.objects.get(product_code=code) print('process', inst) cur_main = last_main = change_time = None insert_list = [] with open(os.path.join(directory, filename)) as f: for line in f: date, oo, hh, ll, cc, se, oi, vo, main_code = [part.strip() for part in line.split(',')] date = f'{int(date[:3])+1900}-{date[3:5]}-{date[5:7]}' date = timezone.make_aware(datetime.datetime.strptime(date, '%Y-%m-%d')) if cur_main != main_code: if last_main != main_code: last_main = cur_main cur_main = main_code change_time = date insert_list.append(MainBar( exchange=inst.exchange, product_code=code, code=main_code, time=date, open=oo, high=hh, low=ll, close=cc, settlement=se, open_interest=oi, volume=vo, basis=None)) MainBar.objects.bulk_create(insert_list) Instrument.objects.filter(product_code=code).update( last_main=last_main, main_code=cur_main, change_time=change_time) return True except Exception as e: logger.warning(f'load_kt_data failed: {repr(e)}', exc_info=True) return False # TODO: async def get_contracts_argument(day: datetime.datetime = None) -> bool: try: if day is None: day = timezone.localtime() day_str = day.strftime('%Y%m%d') redis_client = redis.StrictRedis( host=config.get('REDIS', 'host', fallback='localhost'), db=config.getint('REDIS', 'db', fallback=0), decode_responses=True) async with aiohttp.ClientSession() as session: # async with session.get( f'http://{shfe_ip}/data/busiparamdata/future/ContractDailyTradeArgument{day_str}.dat') as response: rst = await response.read() rst_json = json.loads(rst) for inst_data in rst_json['ContractDailyTradeArgument']: """ {"HDEGE_LONGMARGINRATIO":".10000000","HDEGE_SHORTMARGINRATIO":".10000000","INSTRUMENTID":"cu2201", "LOWER_VALUE":".08000000","PRICE_LIMITS":"","SPEC_LONGMARGINRATIO":".10000000","SPEC_SHORTMARGINRATIO":".10000000", "TRADINGDAY":"20211217","UPDATE_DATE":"2021-12-17 09:51:20","UPPER_VALUE":".08000000","id":124468118} """ # logger.info(f'inst_data: {inst_data}') code = re.findall('[A-Za-z]+', inst_data['INSTRUMENTID'])[0] if code in IGNORE_INST_LIST: continue exchange = ExchangeType.INE if code in INE_INST_LIST else ExchangeType.SHFE limit_ratio = str_to_number(inst_data['UPPER_VALUE']) redis_client.set(f"LIMITRATIO:{exchange}:{code}:{inst_data['INSTRUMENTID']}", limit_ratio) # async with session.post(f'http://{dce_ip}/publicweb/notificationtips/exportDayTradPara.html', data={'exportFlag': 'txt'}) as response: rst = await response.text() for lines in rst.split('\r\n')[3:400]: # if '' in lines: break inst_data_raw = [x.strip() for x in lines.split('\t')] inst_data = [] for cell in inst_data_raw: if len(cell) > 0: inst_data.append(cell) if len(inst_data) == 0: continue """ [0,1(),2/(),3(),4/(),5, 6,7] ['a2201','0.12','7,290','0.08','4,860','0.08','6,561','5,589','30,000','15,000'] """ code = re.findall('[A-Za-z]+', inst_data[0])[0] if code in IGNORE_INST_LIST: continue limit_ratio = str_to_number(inst_data[5]) redis_client.set(f"LIMITRATIO:{ExchangeType.DCE}:{code}:{inst_data[0]}", limit_ratio) # async with session.get(f'http://{czce_ip}/cn/DFSStaticFiles/Future/{day.year}/{day_str}/' f'FutureDataClearParams.txt') as response: rst = await response.text() for lines in rst.split('\n')[2:]: if not lines: continue inst_data = [x.strip() for x in lines.split('|' if '|' in lines else ',')] """ [0,1,2,3,4(%),5(%),6,7,8,9] ['AP201','8,148.00','N','0','10','9','5.00','0.00','20.00','200',''] """ code = re.findall('[A-Za-z]+', inst_data[0])[0] if code in IGNORE_INST_LIST: continue limit_ratio = str_to_number(inst_data[5][1:]) / 100 redis_client.set(f"LIMITRATIO:{ExchangeType.CZCE}:{code}:{inst_data[0]}", limit_ratio) # async with session.get(f"http://{cffex_ip}/sj/jycs/{day.strftime('%Y%m/%d')}/index.xml") as response: rst = await response.text() max_conn_cffex.release() tree = ET.fromstring(rst) for inst_data in tree: """ <INDEX> <TRADING_DAY>20211216</TRADING_DAY> <PRODUCT_ID>IC</PRODUCT_ID> <INSTRUMENT_ID>IC2112</INSTRUMENT_ID> <INSTRUMENT_MONTH>2112</INSTRUMENT_MONTH> <BASIS_PRICE>6072.8</BASIS_PRICE> <OPEN_DATE>20210419</OPEN_DATE> <END_TRADING_DAY>20211217</END_TRADING_DAY> <UPPER_VALUE>0.1</UPPER_VALUE> <LOWER_VALUE>0.1</LOWER_VALUE> <UPPERLIMITPRICE>8063.6</UPPERLIMITPRICE> <LOWERLIMITPRICE>6597.6</LOWERLIMITPRICE> <LONG_LIMIT>1200</LONG_LIMIT> </INDEX> """ inst_id = inst_data.findtext('INSTRUMENT_ID').strip() # if len(inst_id) > 6: continue code = inst_data.findtext('PRODUCT_ID').strip() if code in IGNORE_INST_LIST: continue limit_ratio = str_to_number(inst_data.findtext('UPPER_VALUE').strip()) redis_client.set(f"LIMITRATIO:{ExchangeType.CFFEX}:{code}:{inst_id}", limit_ratio) # for inst in Instrument.objects.all(): ratio = redis_client.get(f"LIMITRATIO:{inst.exchange}:{inst.product_code}:{inst.main_code}") if ratio: ratio = str_to_number(ratio) inst.up_limit_ratio = ratio inst.down_limit_ratio = ratio inst.save(update_fields=['up_limit_ratio', 'down_limit_ratio']) return True except Exception as e: logger.warning(f'get_contracts_argument failed: {repr(e)}', exc_info=True) return False ```
/content/code_sandbox/trader/utils/__init__.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
9,036
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the from abc import ABCMeta from functools import wraps def RegisterCallback(**out_kwargs): def _callback_handler(func): @wraps(func) def wrapper(self, *args, **kwargs): return func(self, *args, *kwargs) for key, value in out_kwargs.items(): setattr(wrapper, f'arg_{key}', value) setattr(wrapper, 'is_callback_function', True) return wrapper return _callback_handler class CallbackFunctionContainer(object, metaclass=ABCMeta): def __init__(self): self.callback_fun_args = dict() self._collect_all() def _collect_all(self): for fun_name in dir(self): fun = getattr(self, fun_name) if hasattr(fun, 'is_callback_function'): params = dict() for arg in dir(fun): if arg.startswith('arg_'): params[arg[4:]] = getattr(fun, arg) self.callback_fun_args[fun_name] = params ```
/content/code_sandbox/trader/utils/func_container.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
256
```python # coding=utf-8 import datetime class TickBar(object): def __init__(self, day, data, last_volume): """ pData, tick :param data: ApiStruct.DepthMarketData :return: """ self.instrument = data.InstrumentID self.bid_price = data.BidPrice1 self.bid_volume = data.BidVolume1 self.ask_price = data.AskPrice1 self.ask_volume = data.AskVolume1 self.holding = data.OpenInterest self.up_limit_price = data.UpperLimitPrice self.down_limit_price = data.LowerLimitPrice self.volume = data.Volume - last_volume self.price = data.LastPrice self.day_high = data.HighestPrice self.day_low = data.LowestPrice self.open = data.OpenPrice self.pre_close = data.PreClosePrice self.dateTime = datetime.datetime.strptime(day+data.UpdateTime, "%Y%m%d%H:%M:%S") self.dateTime = self.dateTime + datetime.timedelta(microseconds=datetime.datetime.now().microsecond) ```
/content/code_sandbox/trader/utils/tick.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
237
```python import sys import os import datetime import asyncio import pytz from tqdm import tqdm import django if sys.platform == 'darwin': sys.path.append('/Users/jeffchen/Documents/gitdir/dashboard') elif sys.platform == 'win32': sys.path.append(r'D:\UserData\Documents\GitHub\dashboard') else: sys.path.append('/home/cyh/bigbrother/dashboard') os.environ["DJANGO_SETTINGS_MODULE"] = "dashboard.settings" os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" django.setup() from trader.utils import is_trading_day, update_from_shfe, update_from_dce, update_from_czce, update_from_cffex, \ create_main_all, fetch_from_quandl_all, clean_daily_bar, load_kt_data, calc_his_all, check_trading_day from django.utils import timezone async def fetch_bar(): day_end = timezone.localtime() day_start = day_end - datetime.timedelta(days=365) tasks = [] while day_start <= day_end: tasks.append(check_trading_day(day_start)) day_start += datetime.timedelta(days=1) trading_days = [] for f in tqdm(asyncio.as_completed(tasks), total=len(tasks)): rst = await f trading_days.append(rst) tasks.clear() for day, trading in trading_days: if trading: tasks += [ asyncio.ensure_future(update_from_shfe(day)), asyncio.ensure_future(update_from_dce(day)), asyncio.ensure_future(update_from_czce(day)), asyncio.ensure_future(update_from_cffex(day)), ] print('task len=', len(tasks)) for f in tqdm(asyncio.as_completed(tasks), total=len(tasks)): await f async def fetch_bar2(): day_end = timezone.localtime() day_start = day_end - datetime.timedelta(days=365) while day_start <= day_end: day, trading = await check_trading_day(day_start) if trading: print('process ', day) tasks = [ asyncio.ensure_future(update_from_shfe(day)), asyncio.ensure_future(update_from_dce(day)), asyncio.ensure_future(update_from_czce(day)), asyncio.ensure_future(update_from_cffex(day)), ] await asyncio.wait(tasks) day_start += datetime.timedelta(days=1) print('all done!') # asyncio.get_event_loop().run_until_complete(fetch_bar2()) create_main_all() # fetch_from_quandl_all() # clean_dailybar() # load_kt_data() # calc_his_all(timezone.localtime()-datetime.timedelta(days=1)) ```
/content/code_sandbox/trader/utils/fetch_data.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
547
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import sys import os import xml.etree.ElementTree as ET import configparser from appdirs import AppDirs from trader import version as app_ver config_example = """# trader configuration file [MSG_CHANNEL] request_pattern = MSG:CTP:REQ:* request_format = MSG:CTP:REQ:{} trade_response_prefix = MSG:CTP:RSP:TRADE: trade_response_format = MSG:CTP:RSP:TRADE:{}:{} market_response_prefix = MSG:CTP:RSP:MARKET: market_response_format = MSG:CTP:RSP:MARKET:{}:{} weixin_log = MSG:LOG:WEIXIN [TRADE] command_timeout = 5 ignore_inst = WH,bb,JR,RI,RS,LR,PM,im [REDIS] host = 127.0.0.1 port = 6379 db = 0 encoding = utf-8 [MYSQL] host = 127.0.0.1 port = 3306 db = QuantDB user = quant password = 123456 [QuantDL] api_key = 123456 [Tushare] token = 123456 [LOG] level = DEBUG format = %(asctime)s %(name)s [%(levelname)s] %(message)s weixin_format = [%(levelname)s] %(message)s """ app_dir = AppDirs('trader') config_file = os.path.join(app_dir.user_config_dir, 'config.ini') if not os.path.exists(config_file): if not os.path.exists(app_dir.user_config_dir): os.makedirs(app_dir.user_config_dir) with open(config_file, 'wt') as f: f.write(config_example) print('create config file:', config_file) config = configparser.ConfigParser(interpolation=None) config.read(config_file) ctp_errors = {} ctp_xml_path = 'D:/github/trader/trader/utils/error.xml' if sys.platform == 'win32' \ else '/root/gitee/trader/trader/utils/error.xml' for error in ET.parse(ctp_xml_path).getroot(): ctp_errors[int(error.attrib['value'])] = error.attrib['prompt'] ```
/content/code_sandbox/trader/utils/read_config.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
515
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import redis import ujson as json import pytz import time import datetime import logging from collections import defaultdict from django.utils import timezone from croniter import croniter import asyncio from abc import abstractmethod, ABCMeta import aioredis from trader.utils.func_container import CallbackFunctionContainer from trader.utils.read_config import config logger = logging.getLogger('BaseModule') class BaseModule(CallbackFunctionContainer, metaclass=ABCMeta): def __init__(self): super().__init__() self.io_loop = asyncio.new_event_loop() asyncio.set_event_loop(self.io_loop) self.redis_client = aioredis.from_url( f"redis://{config.get('REDIS', 'host', fallback='localhost')}:" f"{config.getint('REDIS', 'port', fallback=6379)}/{config.getint('REDIS', 'db', fallback=0)}", decode_responses=True) self.raw_redis = redis.StrictRedis(host=config.get('REDIS', 'host', fallback='localhost'), port=config.getint('REDIS', 'port', fallback=6379), db=config.getint('REDIS', 'db', fallback=0), decode_responses=True) self.sub_client = self.redis_client.pubsub() self.initialized = False self.sub_tasks = list() self.sub_channels = list() self.channel_router = dict() self.crontab_router = defaultdict(dict) self.datetime = None self.time = None self.loop_time = None def _register_callback(self): self.datetime = timezone.localtime() self.time = time.time() self.loop_time = self.io_loop.time() for fun_name, args in self.callback_fun_args.items(): if 'crontab' in args: key = args['crontab'] self.crontab_router[key]['func'] = getattr(self, fun_name) self.crontab_router[key]['iter'] = croniter(args['crontab'], self.datetime) self.crontab_router[key]['handle'] = None elif 'channel' in args: self.channel_router[args['channel']] = getattr(self, fun_name) def _get_next(self, key): return self.loop_time + (self.crontab_router[key]['iter'].get_next() - self.time) def _call_next(self, key): if self.crontab_router[key]['handle'] is not None: self.crontab_router[key]['handle'].cancel() self.crontab_router[key]['handle'] = self.io_loop.call_at(self._get_next(key), self._call_next, key) self.io_loop.create_task(self.crontab_router[key]['func']()) async def install(self): try: self._register_callback() await self.sub_client.psubscribe(*self.channel_router.keys()) asyncio.run_coroutine_threadsafe(self._msg_reader(), self.io_loop) # self.io_loop.create_task(self._msg_reader()) for key, cron_dict in self.crontab_router.items(): if cron_dict['handle'] is not None: cron_dict['handle'].cancel() cron_dict['handle'] = self.io_loop.call_at(self._get_next(key), self._call_next, key) self.initialized = True logger.debug('%s plugin installed', type(self).__name__) except Exception as e: logger.error('%s plugin install failed: %s', type(self).__name__, repr(e), exc_info=True) async def uninstall(self): try: await self.sub_client.punsubscribe() # await asyncio.wait(self.sub_tasks, loop=self.io_loop) self.sub_tasks.clear() await self.sub_client.close() for key, cron_dict in self.crontab_router.items(): if self.crontab_router[key]['handle'] is not None: self.crontab_router[key]['handle'].cancel() self.crontab_router[key]['handle'] = None self.initialized = False logger.debug('%s plugin uninstalled', type(self).__name__) except Exception as e: logger.error('%s plugin uninstall failed: %s', type(self).__name__, repr(e), exc_info=True) async def _msg_reader(self): # {'type': 'pmessage', 'pattern': 'channel:*', 'channel': 'channel:1', 'data': 'Hello'} async for msg in self.sub_client.listen(): if msg['type'] == 'pmessage': channel = msg['channel'] pattern = msg['pattern'] data = json.loads(msg['data']) # logger.debug("%s channel[%s] Got Message:%s", type(self).__name__, channel, msg) self.io_loop.create_task(self.channel_router[pattern](channel, data)) elif msg['type'] == 'punsubscribe': break logger.debug('%s quit _msg_reader!', type(self).__name__) async def start(self): await self.install() async def stop(self): await self.uninstall() def run(self): try: self.io_loop.create_task(self.start()) self.io_loop.run_forever() except KeyboardInterrupt: self.io_loop.run_until_complete(self.stop()) except Exception as ee: logger.error(': %s', repr(ee), exc_info=True) self.io_loop.run_until_complete(self.stop()) finally: logger.debug('') ```
/content/code_sandbox/trader/strategy/__init__.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
1,182
```python # coding=utf-8 T = dict() T['TE_RESUME'] = 'int' # TERT_RESTART = 0 # TERT_RESUME = 1 # TERT_QUICK = 2 # T['TraderID'] = 'char[21]' # T['InvestorID'] = 'char[13]' # T['BrokerID'] = 'char[11]' # T['BrokerAbbr'] = 'char[9]' # T['BrokerName'] = 'char[81]' # T['ExchangeInstID'] = 'char[31]' # T['OrderRef'] = 'char[13]' # T['ParticipantID'] = 'char[11]' # T['UserID'] = 'char[16]' # T['Password'] = 'char[41]' # T['ClientID'] = 'char[11]' # T['InstrumentID'] = 'char[31]' # T['MarketID'] = 'char[31]' # T['ProductName'] = 'char[21]' # T['ExchangeID'] = 'char[9]' # T['ExchangeName'] = 'char[61]' # T['ExchangeAbbr'] = 'char[9]' # T['ExchangeFlag'] = 'char[2]' # T['MacAddress'] = 'char[21]' # Mac T['SystemID'] = 'char[21]' # T['ExchangeProperty'] = 'char' # EXP_Normal = '0' # EXP_GenOrderByTrade = '1' # T['Date'] = 'char[9]' # T['Time'] = 'char[9]' # T['LongTime'] = 'char[13]' # T['InstrumentName'] = 'char[21]' # T['SettlementGroupID'] = 'char[9]' # T['OrderSysID'] = 'char[21]' # T['TradeID'] = 'char[21]' # T['CommandType'] = 'char[65]' # DB T['IPAddress'] = 'char[16]' # IP T['IPPort'] = 'int' # IP T['ProductInfo'] = 'char[11]' # T['ProtocolInfo'] = 'char[11]' # T['BusinessUnit'] = 'char[21]' # T['DepositSeqNo'] = 'char[15]' # T['IdentifiedCardNo'] = 'char[51]' # T['IdCardType'] = 'char' # ICT_EID = '0' # ICT_IDCard = '1' # ICT_OfficerIDCard = '2' # ICT_PoliceIDCard = '3' # ICT_SoldierIDCard = '4' # ICT_HouseholdRegister = '5' # ICT_Passport = '6' # ICT_TaiwanCompatriotIDCard = '7' # ICT_HomeComingCard = '8' # ICT_TaxNo = 'A' # /ID ICT_HMMainlandTravelPermit = 'B' # ICT_TwMainlandTravelPermit = 'C' # ICT_SocialID = 'F' # ID ICT_LocalID = 'G' # ICT_BusinessRegistration = 'H' # ICT_HKMCIDCard = 'I' # ICT_AccountsPermits = 'J' # ICT_OtherCard = 'x' # T['OrderLocalID'] = 'char[13]' # T['UserName'] = 'char[81]' # T['PartyName'] = 'char[81]' # T['ErrorMsg'] = 'char[81]' # T['FieldName'] = 'char[2049]' # T['FieldContent'] = 'char[2049]' # T['SystemName'] = 'char[41]' # T['Content'] = 'char[501]' # T['InvestorRange'] = 'char' # IR_All = '1' # IR_Group = '2' # IR_Single = '3' # T['DepartmentRange'] = 'char' # DR_All = '1' # DR_Group = '2' # DR_Single = '3' # T['DataSyncStatus'] = 'char' # DS_Asynchronous = '1' # DS_Synchronizing = '2' # DS_Synchronized = '3' # T['BrokerDataSyncStatus'] = 'char' # BDS_Synchronized = '1' # BDS_Synchronizing = '2' # T['ExchangeConnectStatus'] = 'char' # ECS_NoConnection = '1' # ECS_QryInstrumentSent = '2' # ECS_GotInformation = '9' # T['TraderConnectStatus'] = 'char' # TCS_NotConnected = '1' # TCS_Connected = '2' # TCS_QryInstrumentSent = '3' # TCS_SubPrivateFlow = '4' # T['FunctionCode'] = 'char' # FC_DataAsync = '1' # FC_ForceUserLogout = '2' # FC_UserPasswordUpdate = '3' # FC_BrokerPasswordUpdate = '4' # FC_InvestorPasswordUpdate = '5' # FC_OrderInsert = '6' # FC_OrderAction = '7' # FC_SyncSystemData = '8' # FC_SyncBrokerData = '9' # FC_BachSyncBrokerData = 'A' # FC_SuperQuery = 'B' # FC_ParkedOrderInsert = 'C' # FC_ParkedOrderAction = 'D' # FC_SyncOTP = 'E' # FC_DeleteOrder = 'F' # T['BrokerFunctionCode'] = 'char' # BFC_ForceUserLogout = '1' # BFC_UserPasswordUpdate = '2' # BFC_SyncBrokerData = '3' # BFC_BachSyncBrokerData = '4' # BFC_OrderInsert = '5' # BFC_OrderAction = '6' # BFC_AllQuery = '7' # BFC_log = 'a' # // BFC_BaseQry = 'b' # BFC_TradeQry = 'c' # BFC_Trade = 'd' # BFC_Virement = 'e' # BFC_Risk = 'f' # BFC_Session = 'g' # / BFC_RiskNoticeCtl = 'h' # BFC_RiskNotice = 'i' # BFC_BrokerDeposit = 'j' # BFC_QueryFund = 'k' # BFC_QueryOrder = 'l' # BFC_QueryTrade = 'm' # BFC_QueryPosition = 'n' # BFC_QueryMarketData = 'o' # BFC_QueryUserEvent = 'p' # BFC_QueryRiskNotify = 'q' # BFC_QueryFundChange = 'r' # BFC_QueryInvestor = 's' # BFC_QueryTradingCode = 't' # BFC_ForceClose = 'u' # BFC_PressTest = 'v' # BFC_RemainCalc = 'w' # BFC_NetPositionInd = 'x' # BFC_RiskPredict = 'y' # BFC_DataExport = 'z' # BFC_RiskTargetSetup = 'A' # BFC_MarketDataWarn = 'B' # BFC_QryBizNotice = 'C' # BFC_CfgBizNotice = 'D' # BFC_SyncOTP = 'E' # BFC_SendBizNotice = 'F' # BFC_CfgRiskLevelStd = 'G' # BFC_TbCommand = 'H' # BFC_DeleteOrder = 'J' # BFC_ParkedOrderInsert = 'K' # BFC_ParkedOrderAction = 'L' # T['OrderActionStatus'] = 'char' # OAS_Submitted = 'a' # OAS_Accepted = 'b' # OAS_Rejected = 'c' # T['OrderStatus'] = 'char' # OST_AllTraded = '0' # OST_PartTradedQueueing = '1' # OST_PartTradedNotQueueing = '2' # OST_NoTradeQueueing = '3' # OST_NoTradeNotQueueing = '4' # OST_Canceled = '5' # OST_Unknown = 'a' # OST_NotTouched = 'b' # OST_Touched = 'c' # T['OrderSubmitStatus'] = 'char' # OSS_InsertSubmitted = '0' # OSS_CancelSubmitted = '1' # OSS_ModifySubmitted = '2' # OSS_Accepted = '3' # OSS_InsertRejected = '4' # OSS_CancelRejected = '5' # OSS_ModifyRejected = '6' # T['PositionDate'] = 'char' # PSD_Today = '1' # PSD_History = '2' # T['PositionDateType'] = 'char' # PDT_UseHistory = '1' # PDT_NoUseHistory = '2' # T['TradingRole'] = 'char' # ER_Broker = '1' # ER_Host = '2' # ER_Maker = '3' # T['ProductClass'] = 'char' # PC_Futures = '1' # PC_Options = '2' # PC_Combination = '3' # PC_Spot = '4' # PC_EFP = '5' # PC_SpotOption = '6' # T['InstLifePhase'] = 'char' # IP_NotStart = '0' # IP_Started = '1' # IP_Pause = '2' # IP_Expired = '3' # T['Direction'] = 'char' # D_Buy = '0' # D_Sell = '1' # T['PositionType'] = 'char' # PT_Net = '1' # PT_Gross = '2' # T['PosiDirection'] = 'char' # PD_Net = '1' # PD_Long = '2' # PD_Short = '3' # T['SysSettlementStatus'] = 'char' # SS_NonActive = '1' # SS_Startup = '2' # SS_Operating = '3' # SS_Settlement = '4' # SS_SettlementFinished = '5' # T['RatioAttr'] = 'char' # RA_Trade = '0' # RA_Settlement = '1' # T['HedgeFlag'] = 'char' # HF_Speculation = '1' # HF_Arbitrage = '2' # HF_Hedge = '3' # T['BillHedgeFlag'] = 'char' # BHF_Speculation = '1' # BHF_Arbitrage = '2' # BHF_Hedge = '3' # T['ClientIDType'] = 'char' # CIDT_Speculation = '1' # CIDT_Arbitrage = '2' # CIDT_Hedge = '3' # T['OrderPriceType'] = 'char' # OPT_AnyPrice = '1' # OPT_LimitPrice = '2' # OPT_BestPrice = '3' # OPT_LastPrice = '4' # OPT_LastPricePlusOneTicks = '5' # 1ticks OPT_LastPricePlusTwoTicks = '6' # 2ticks OPT_LastPricePlusThreeTicks = '7' # 3ticks OPT_AskPrice1 = '8' # OPT_AskPrice1PlusOneTicks = '9' # 1ticks OPT_AskPrice1PlusTwoTicks = 'A' # 2ticks OPT_AskPrice1PlusThreeTicks = 'B' # 3ticks OPT_BidPrice1 = 'C' # OPT_BidPrice1PlusOneTicks = 'D' # 1ticks OPT_BidPrice1PlusTwoTicks = 'E' # 2ticks OPT_BidPrice1PlusThreeTicks = 'F' # 3ticks OPT_FiveLevelPrice = 'G' # T['OffsetFlag'] = 'char' # OF_Open = '0' # OF_Close = '1' # OF_ForceClose = '2' # OF_CloseToday = '3' # OF_CloseYesterday = '4' # OF_ForceOff = '5' # OF_LocalForceClose = '6' # T['ForceCloseReason'] = 'char' # FCC_NotForceClose = '0' # FCC_LackDeposit = '1' # FCC_ClientOverPositionLimit = '2' # FCC_MemberOverPositionLimit = '3' # FCC_NotMultiple = '4' # FCC_Violation = '5' # FCC_Other = '6' # FCC_PersonDeliv = '7' # T['OrderType'] = 'char' # ORDT_Normal = '0' # ORDT_DeriveFromQuote = '1' # ORDT_DeriveFromCombination = '2' # ORDT_Combination = '3' # ORDT_ConditionalOrder = '4' # ORDT_Swap = '5' # T['TimeCondition'] = 'char' # TC_IOC = '1' # TC_GFS = '2' # TC_GFD = '3' # TC_GTD = '4' # TC_GTC = '5' # TC_GFA = '6' # T['VolumeCondition'] = 'char' # VC_AV = '1' # VC_MV = '2' # VC_CV = '3' # T['ContingentCondition'] = 'char' # CC_Immediately = '1' # CC_Touch = '2' # CC_TouchProfit = '3' # CC_ParkedOrder = '4' # CC_LastPriceGreaterThanStopPrice = '5' # CC_LastPriceGreaterEqualStopPrice = '6' # CC_LastPriceLesserThanStopPrice = '7' # CC_LastPriceLesserEqualStopPrice = '8' # CC_AskPriceGreaterThanStopPrice = '9' # CC_AskPriceGreaterEqualStopPrice = 'A' # CC_AskPriceLesserThanStopPrice = 'B' # CC_AskPriceLesserEqualStopPrice = 'C' # CC_BidPriceGreaterThanStopPrice = 'D' # CC_BidPriceGreaterEqualStopPrice = 'E' # CC_BidPriceLesserThanStopPrice = 'F' # CC_BidPriceLesserEqualStopPrice = 'H' # T['ActionFlag'] = 'char' # AF_Delete = '0' # AF_Modify = '3' # T['TradingRight'] = 'char' # TR_Allow = '0' # TR_CloseOnly = '1' # TR_Forbidden = '2' # T['OrderSource'] = 'char' # OSRC_Participant = '0' # OSRC_Administrator = '1' # T['TradeType'] = 'char' # TRDT_SplitCombination = '#' # , TRDT_Common = '0' # TRDT_OptionsExecution = '1' # TRDT_OTC = '2' # OTC TRDT_EFPDerived = '3' # TRDT_CombinationDerived = '4' # T['PriceSource'] = 'char' # PSRC_LastPrice = '0' # PSRC_Buy = '1' # PSRC_Sell = '2' # T['InstrumentStatus'] = 'char' # IS_BeforeTrading = '0' # IS_NoTrading = '1' # IS_Continous = '2' # IS_AuctionOrdering = '3' # IS_AuctionBalance = '4' # IS_AuctionMatch = '5' # IS_Closed = '6' # T['InstStatusEnterReason'] = 'char' # IER_Automatic = '1' # IER_Manual = '2' # IER_Fuse = '3' # T['OrderActionRef'] = 'int' # T['InstallCount'] = 'int' # T['InstallID'] = 'int' # T['ErrorID'] = 'int' # T['SettlementID'] = 'int' # T['Volume'] = 'int' # T['FrontID'] = 'int' # T['SessionID'] = 'int' # T['SequenceNo'] = 'int' # T['CommandNo'] = 'int' # DB T['Millisec'] = 'int' # T['VolumeMultiple'] = 'int' # T['TradingSegmentSN'] = 'int' # T['RequestID'] = 'int' # T['Year'] = 'int' # T['Month'] = 'int' # T['Bool'] = 'int' # T['Price'] = 'double' # T['CombOffsetFlag'] = 'char[5]' # T['CombHedgeFlag'] = 'char[5]' # T['Ratio'] = 'double' # T['Money'] = 'double' # T['LargeVolume'] = 'double' # T['SequenceSeries'] = 'short' # T['CommPhaseNo'] = 'short' # T['SequenceLabel'] = 'char[2]' # T['UnderlyingMultiple'] = 'double' # T['Priority'] = 'int' # T['ContractCode'] = 'char[41]' # T['City'] = 'char[51]' # T['IsStock'] = 'char[11]' # T['Channel'] = 'char[51]' # T['Address'] = 'char[101]' # T['ZipCode'] = 'char[7]' # T['Telephone'] = 'char[41]' # T['Fax'] = 'char[41]' # T['Mobile'] = 'char[41]' # T['EMail'] = 'char[41]' # T['Memo'] = 'char[161]' # T['CompanyCode'] = 'char[51]' # T['Website'] = 'char[51]' # T['TaxNo'] = 'char[31]' # T['BatchStatus'] = 'char' # BS_NoUpload = '1' # BS_Uploaded = '2' # BS_Failed = '3' # T['PropertyID'] = 'char[33]' # T['PropertyName'] = 'char[65]' # T['AgentID'] = 'char[13]' # T['AgentName'] = 'char[41]' # T['AgentGroupID'] = 'char[13]' # T['AgentGroupName'] = 'char[41]' # T['ReturnStyle'] = 'char' # RS_All = '1' # RS_ByProduct = '2' # T['ReturnPattern'] = 'char' # RP_ByVolume = '1' # RP_ByFeeOnHand = '2' # T['ReturnLevel'] = 'char' # RL_Level1 = '1' # 1 RL_Level2 = '2' # 2 RL_Level3 = '3' # 3 RL_Level4 = '4' # 4 RL_Level5 = '5' # 5 RL_Level6 = '6' # 6 RL_Level7 = '7' # 7 RL_Level8 = '8' # 8 RL_Level9 = '9' # 9 T['ReturnStandard'] = 'char' # RSD_ByPeriod = '1' # RSD_ByStandard = '2' # T['MortgageType'] = 'char' # MT_Out = '0' # MT_In = '1' # T['InvestorSettlementParamID'] = 'char' # ISPI_MortgageRatio = '4' # ISPI_MarginWay = '5' # ISPI_BillDeposit = '9' # T['ExchangeSettlementParamID'] = 'char' # ESPI_MortgageRatio = '1' # ESPI_OtherFundItem = '2' # ESPI_OtherFundImport = '3' # ESPI_CFFEXMinPrepa = '6' # ESPI_CZCESettlementType = '7' # ESPI_ExchDelivFeeMode = '9' # ESPI_DelivFeeMode = '0' # ESPI_CZCEComMarginType = 'A' # ESPI_DceComMarginType = 'B' # ESPI_OptOutDisCountRate = 'a' # ESPI_OptMiniGuarantee = 'b' # T['SystemParamID'] = 'char' # SPI_InvestorIDMinLength = '1' # SPI_AccountIDMinLength = '2' # SPI_UserRightLogon = '3' # SPI_SettlementBillTrade = '4' # SPI_TradingCode = '5' # SPI_CheckFund = '6' # SPI_CommModelRight = '7' # SPI_MarginModelRight = '9' # SPI_IsStandardActive = '8' # SPI_UploadSettlementFile = 'U' # SPI_DownloadCSRCFile = 'D' # SPI_SettlementBillFile = 'S' # SPI_CSRCOthersFile = 'C' # SPI_InvestorPhoto = 'P' # SPI_CSRCData = 'R' # SPI_InvestorPwdModel = 'I' # SPI_CFFEXInvestorSettleFile = 'F' # SPI_InvestorIDType = 'a' # SPI_FreezeMaxReMain = 'r' # SPI_IsSync = 'A' # SPI_RelieveOpenLimit = 'O' # SPI_IsStandardFreeze = 'X' # SPI_CZCENormalProductHedge = 'B' # T['TradeParamID'] = 'char' # TPID_EncryptionStandard = 'E' # TPID_RiskMode = 'R' # TPID_RiskModeGlobal = 'G' # 0- 1- TPID_modeEncode = 'P' # TPID_tickMode = 'T' # TPID_SingleUserSessionMaxNum = 'S' # TPID_LoginFailMaxNum = 'L' # TPID_IsAuthForce = 'A' # TPID_IsPosiFreeze = 'F' # TPID_IsPosiLimit = 'M' # TPID_ForQuoteTimeInterval = 'Q' # T['SettlementParamValue'] = 'char[256]' # T['CounterID'] = 'char[33]' # T['InvestorGroupName'] = 'char[41]' # T['BrandCode'] = 'char[257]' # T['Warehouse'] = 'char[257]' # T['ProductDate'] = 'char[41]' # T['Grade'] = 'char[41]' # T['Classify'] = 'char[41]' # T['Position'] = 'char[41]' # T['Yieldly'] = 'char[41]' # T['Weight'] = 'char[41]' # T['SubEntryFundNo'] = 'int' # T['FileID'] = 'char' # FI_SettlementFund = 'F' # FI_Trade = 'T' # FI_InvestorPosition = 'P' # FI_SubEntryFund = 'O' # FI_CZCECombinationPos = 'C' # FI_CSRCData = 'R' # FI_CZCEClose = 'L' # FI_CZCENoClose = 'N' # FI_PositionDtl = 'D' # FI_OptionStrike = 'S' # FI_SettlementPriceComparison = 'M' # FI_NonTradePosChange = 'B' # T['FileName'] = 'char[257]' # T['FileType'] = 'char' # FUT_Settlement = '0' # FUT_Check = '1' # T['FileFormat'] = 'char' # FFT_Txt = '0' # (.txt) FFT_Zip = '1' # (.zip) FFT_DBF = '2' # DBF(.dbf) T['FileUploadStatus'] = 'char' # FUS_SucceedUpload = '1' # FUS_FailedUpload = '2' # FUS_SucceedLoad = '3' # FUS_PartSucceedLoad = '4' # FUS_FailedLoad = '5' # T['TransferDirection'] = 'char' # TD_Out = '0' # TD_In = '1' # T['UploadMode'] = 'char[21]' # T['AccountID'] = 'char[13]' # T['BankFlag'] = 'char[4]' # T['BankAccount'] = 'char[41]' # T['OpenName'] = 'char[61]' # T['OpenBank'] = 'char[101]' # T['BankName'] = 'char[101]' # T['PublishPath'] = 'char[257]' # T['OperatorID'] = 'char[65]' # T['MonthCount'] = 'int' # T['AdvanceMonthArray'] = 'char[13]' # T['DateExpr'] = 'char[1025]' # T['InstrumentIDExpr'] = 'char[41]' # T['InstrumentNameExpr'] = 'char[41]' # T['SpecialCreateRule'] = 'char' # SC_NoSpecialRule = '0' # SC_NoSpringFestival = '1' # T['BasisPriceType'] = 'char' # IPT_LastSettlement = '1' # IPT_LaseClose = '2' # T['ProductLifePhase'] = 'char' # PLP_Active = '1' # PLP_NonActive = '2' # PLP_Canceled = '3' # T['DeliveryMode'] = 'char' # DM_CashDeliv = '1' # DM_CommodityDeliv = '2' # T['LogLevel'] = 'char[33]' # T['ProcessName'] = 'char[257]' # T['OperationMemo'] = 'char[1025]' # T['FundIOType'] = 'char' # FIOT_FundIO = '1' # FIOT_Transfer = '2' # FIOT_SwapCurrency = '3' # T['FundType'] = 'char' # FT_Deposite = '1' # FT_ItemFund = '2' # FT_Company = '3' # FT_InnerTransfer = '4' # T['FundDirection'] = 'char' # FD_In = '1' # FD_Out = '2' # T['FundStatus'] = 'char' # FS_Record = '1' # FS_Check = '2' # FS_Charge = '3' # T['BillNo'] = 'char[15]' # T['BillName'] = 'char[33]' # T['PublishStatus'] = 'char' # PS_None = '1' # PS_Publishing = '2' # PS_Published = '3' # T['EnumValueID'] = 'char[65]' # T['EnumValueType'] = 'char[33]' # T['EnumValueLabel'] = 'char[65]' # T['EnumValueResult'] = 'char[33]' # T['SystemStatus'] = 'char' # ES_NonActive = '1' # ES_Startup = '2' # ES_Initialize = '3' # ES_Initialized = '4' # ES_Close = '5' # ES_Closed = '6' # ES_Settlement = '7' # T['SettlementStatus'] = 'char' # STS_Initialize = '0' # STS_Settlementing = '1' # STS_Settlemented = '2' # STS_Finished = '3' # T['RangeIntType'] = 'char[33]' # T['RangeIntFrom'] = 'char[33]' # T['RangeIntTo'] = 'char[33]' # T['FunctionID'] = 'char[25]' # T['FunctionValueCode'] = 'char[257]' # T['FunctionName'] = 'char[65]' # T['RoleID'] = 'char[11]' # T['RoleName'] = 'char[41]' # T['Description'] = 'char[401]' # T['CombineID'] = 'char[25]' # T['CombineType'] = 'char[25]' # T['InvestorType'] = 'char' # CT_Person = '0' # CT_Company = '1' # CT_Fund = '2' # CT_SpecialOrgan = '3' # CT_Asset = '4' # T['BrokerType'] = 'char' # BT_Trade = '0' # BT_TradeSettle = '1' # T['RiskLevel'] = 'char' # FAS_Low = '1' # FAS_Normal = '2' # FAS_Focus = '3' # FAS_Risk = '4' # T['FeeAcceptStyle'] = 'char' # FAS_ByTrade = '1' # FAS_ByDeliv = '2' # FAS_None = '3' # FAS_FixFee = '4' # T['PasswordType'] = 'char' # PWDT_Trade = '1' # PWDT_Account = '2' # T['Algorithm'] = 'char' # AG_All = '1' # AG_OnlyLost = '2' # AG_OnlyGain = '3' # AG_None = '4' # T['IncludeCloseProfit'] = 'char' # ICP_Include = '0' # ICP_NotInclude = '2' # T['AllWithoutTrade'] = 'char' # AWT_Enable = '0' # AWT_Disable = '2' # AWT_NoHoldEnable = '3' # T['Comment'] = 'char[31]' # T['Version'] = 'char[4]' # T['TradeCode'] = 'char[7]' # T['TradeDate'] = 'char[9]' # T['TradeTime'] = 'char[9]' # T['TradeSerial'] = 'char[9]' # T['TradeSerialNo'] = 'int' # T['FutureID'] = 'char[11]' # T['BankID'] = 'char[4]' # T['BankBrchID'] = 'char[5]' # T['BankBranchID'] = 'char[11]' # T['OperNo'] = 'char[17]' # T['DeviceID'] = 'char[3]' # T['RecordNum'] = 'char[7]' # T['FutureAccount'] = 'char[22]' # T['FuturePwdFlag'] = 'char' # FPWD_UnCheck = '0' # FPWD_Check = '1' # T['TransferType'] = 'char' # TT_BankToFuture = '0' # TT_FutureToBank = '1' # T['FutureAccPwd'] = 'char[17]' # T['CurrencyCode'] = 'char[4]' # T['RetCode'] = 'char[5]' # T['RetInfo'] = 'char[129]' # T['TradeAmt'] = 'char[20]' # T['UseAmt'] = 'char[20]' # T['FetchAmt'] = 'char[20]' # T['TransferValidFlag'] = 'char' # TVF_Invalid = '0' # TVF_Valid = '1' # TVF_Reverse = '2' # T['CertCode'] = 'char[21]' # T['Reason'] = 'char' # RN_CD = '0' # RN_ZT = '1' # RN_QT = '2' # T['FundProjectID'] = 'char[5]' # T['Sex'] = 'char' # SEX_None = '0' # SEX_Man = '1' # SEX_Woman = '2' # T['Profession'] = 'char[101]' # T['National'] = 'char[31]' # T['Province'] = 'char[51]' # T['Region'] = 'char[16]' # T['Country'] = 'char[16]' # T['CompanyType'] = 'char[16]' # T['BusinessScope'] = 'char[1001]' # T['CapitalCurrency'] = 'char[4]' # T['UserType'] = 'char' # UT_Investor = '0' # UT_Operator = '1' # UT_SuperUser = '2' # T['RateType'] = 'char' # RATETYPE_MarginRate = '2' # T['NoteType'] = 'char' # NOTETYPE_TradeSettleBill = '1' # NOTETYPE_TradeSettleMonth = '2' # NOTETYPE_CallMarginNotes = '3' # NOTETYPE_ForceCloseNotes = '4' # NOTETYPE_TradeNotes = '5' # NOTETYPE_DelivNotes = '6' # T['SettlementStyle'] = 'char' # SBS_Day = '1' # SBS_Volume = '2' # T['BrokerDNS'] = 'char[256]' # T['Sentence'] = 'char[501]' # T['SettlementBillType'] = 'char' # ST_Day = '0' # ST_Month = '1' # T['UserRightType'] = 'char' # URT_Logon = '1' # URT_Transfer = '2' # URT_EMail = '3' # URT_Fax = '4' # URT_ConditionOrder = '5' # T['MarginPriceType'] = 'char' # MPT_PreSettlementPrice = '1' # MPT_SettlementPrice = '2' # MPT_AveragePrice = '3' # MPT_OpenPrice = '4' # T['BillGenStatus'] = 'char' # BGS_None = '0' # BGS_NoGenerated = '1' # BGS_Generated = '2' # T['AlgoType'] = 'char' # AT_HandlePositionAlgo = '1' # AT_FindMarginRateAlgo = '2' # T['HandlePositionAlgoID'] = 'char' # HPA_Base = '1' # HPA_DCE = '2' # HPA_CZCE = '3' # T['FindMarginRateAlgoID'] = 'char' # FMRA_Base = '1' # FMRA_DCE = '2' # FMRA_CZCE = '3' # T['HandleTradingAccountAlgoID'] = 'char' # HTAA_Base = '1' # HTAA_DCE = '2' # HTAA_CZCE = '3' # T['PersonType'] = 'char' # PST_Order = '1' # PST_Open = '2' # PST_Fund = '3' # PST_Settlement = '4' # PST_Company = '5' # PST_Corporation = '6' # PST_LinkMan = '7' # PST_Ledger = '8' # PST_Trustee = '9' # PST_TrusteeCorporation = 'A' # PST_TrusteeOpen = 'B' # PST_TrusteeContact = 'C' # PST_ForeignerRefer = 'D' # PST_CorporationRefer = 'E' # T['QueryInvestorRange'] = 'char' # QIR_All = '1' # QIR_Group = '2' # QIR_Single = '3' # T['InvestorRiskStatus'] = 'char' # IRS_Normal = '1' # IRS_Warn = '2' # IRS_Call = '3' # IRS_Force = '4' # IRS_Exception = '5' # T['LegID'] = 'int' # T['LegMultiple'] = 'int' # T['ImplyLevel'] = 'int' # T['ClearAccount'] = 'char[33]' # T['OrganNO'] = 'char[6]' # T['ClearbarchID'] = 'char[6]' # T['UserEventType'] = 'char' # UET_Login = '1' # UET_Logout = '2' # UET_Trading = '3' # UET_TradingError = '4' # UET_UpdatePassword = '5' # UET_Authenticate = '6' # UET_Other = '9' # T['UserEventInfo'] = 'char[1025]' # T['CloseStyle'] = 'char' # ICS_Close = '0' # ICS_CloseToday = '1' # T['StatMode'] = 'char' # SM_Non = '0' # ---- SM_Instrument = '1' # SM_Product = '2' # SM_Investor = '3' # T['ParkedOrderStatus'] = 'char' # PAOS_NotSend = '1' # PAOS_Send = '2' # PAOS_Deleted = '3' # T['ParkedOrderID'] = 'char[13]' # T['ParkedOrderActionID'] = 'char[13]' # T['VirDealStatus'] = 'char' # VDS_Dealing = '1' # VDS_DeaclSucceed = '2' # T['OrgSystemID'] = 'char' # ORGS_Standard = '0' # ORGS_ESunny = '1' # ORGS_KingStarV6 = '2' # V6 T['VirTradeStatus'] = 'char' # VTS_NaturalDeal = '0' # VTS_SucceedEnd = '1' # VTS_FailedEND = '2' # VTS_Exception = '3' # VTS_ManualDeal = '4' # VTS_MesException = '5' # VTS_SysException = '6' # T['VirBankAccType'] = 'char' # VBAT_BankBook = '1' # VBAT_BankCard = '2' # VBAT_CreditCard = '3' # T['VirementStatus'] = 'char' # VMS_Natural = '0' # VMS_Canceled = '9' # T['VirementAvailAbility'] = 'char' # VAA_NoAvailAbility = '0' # VAA_AvailAbility = '1' # VAA_Repeal = '2' # T['VirementTradeCode'] = 'char[7]' # VTC_BankBankToFuture = '102001' # VTC_BankFutureToBank = '102002' # VTC_FutureBankToFuture = '202001' # VTC_FutureFutureToBank = '202002' # T['PhotoTypeName'] = 'char[41]' # T['PhotoTypeID'] = 'char[5]' # T['PhotoName'] = 'char[161]' # T['TopicID'] = 'int' # T['ReportTypeID'] = 'char[3]' # T['CharacterID'] = 'char[5]' # T['AMLParamID'] = 'char[21]' # T['AMLInvestorType'] = 'char[3]' # T['AMLIdCardType'] = 'char[3]' # T['AMLTradeDirect'] = 'char[3]' # T['AMLTradeModel'] = 'char[3]' # T['AMLParamID'] = 'char[21]' # T['AMLOpParamValue'] = 'double' # T['AMLCustomerCardType'] = 'char[81]' # / T['AMLInstitutionName'] = 'char[65]' # T['AMLDistrictID'] = 'char[7]' # T['AMLRelationShip'] = 'char[3]' # T['AMLInstitutionType'] = 'char[3]' # T['AMLInstitutionID'] = 'char[13]' # T['AMLAccountType'] = 'char[5]' # T['AMLTradingType'] = 'char[7]' # T['AMLTransactClass'] = 'char[7]' # T['AMLCapitalIO'] = 'char[3]' # T['AMLSite'] = 'char[10]' # T['AMLCapitalPurpose'] = 'char[129]' # T['AMLReportType'] = 'char[2]' # T['AMLSerialNo'] = 'char[5]' # T['AMLStatus'] = 'char[2]' # T['AMLGenStatus'] = 'char' # Aml GEN_Program = '0' # GEN_HandWork = '1' # T['AMLSeqCode'] = 'char[65]' # T['AMLFileName'] = 'char[257]' # AML T['AMLMoney'] = 'double' # T['AMLFileAmount'] = 'int' # T['CFMMCKey'] = 'char[21]' # () T['CFMMCToken'] = 'char[21]' # () T['CFMMCKeyKind'] = 'char' # () CFMMCKK_REQUEST = 'R' # CFMMCKK_AUTO = 'A' # CFMMC CFMMCKK_MANUAL = 'M' # CFMMC T['AMLReportName'] = 'char[81]' # T['IndividualName'] = 'char[51]' # T['CurrencyID'] = 'char[4]' # T['CustNumber'] = 'char[36]' # T['OrganCode'] = 'char[36]' # T['OrganName'] = 'char[71]' # T['SuperOrganCode'] = 'char[12]' # , T['SubBranchID'] = 'char[31]' # T['SubBranchName'] = 'char[71]' # T['BranchNetCode'] = 'char[31]' # T['BranchNetName'] = 'char[71]' # T['OrganFlag'] = 'char[2]' # T['BankCodingForFuture'] = 'char[33]' # T['BankReturnCode'] = 'char[7]' # T['PlateReturnCode'] = 'char[5]' # T['BankSubBranchID'] = 'char[31]' # T['FutureBranchID'] = 'char[31]' # T['ReturnCode'] = 'char[7]' # T['OperatorCode'] = 'char[17]' # T['ClearDepID'] = 'char[6]' # T['ClearBrchID'] = 'char[6]' # T['ClearName'] = 'char[71]' # T['BankAccountName'] = 'char[71]' # T['InvDepID'] = 'char[6]' # T['InvBrchID'] = 'char[6]' # T['MessageFormatVersion'] = 'char[36]' # T['Digest'] = 'char[36]' # T['AuthenticData'] = 'char[129]' # T['PasswordKey'] = 'char[129]' # T['FutureAccountName'] = 'char[129]' # T['MobilePhone'] = 'char[21]' # T['FutureMainKey'] = 'char[129]' # T['FutureWorkKey'] = 'char[129]' # T['FutureTransKey'] = 'char[129]' # T['BankMainKey'] = 'char[129]' # T['BankWorkKey'] = 'char[129]' # T['BankTransKey'] = 'char[129]' # T['BankServerDescription'] = 'char[129]' # T['AddInfo'] = 'char[129]' # T['DescrInfoForReturnCode'] = 'char[129]' # T['CountryCode'] = 'char[21]' # T['Serial'] = 'int' # T['PlateSerial'] = 'int' # T['BankSerial'] = 'char[13]' # T['CorrectSerial'] = 'int' # T['FutureSerial'] = 'int' # T['ApplicationID'] = 'int' # T['BankProxyID'] = 'int' # T['FBTCoreID'] = 'int' # T['ServerPort'] = 'int' # T['RepealedTimes'] = 'int' # T['RepealTimeInterval'] = 'int' # T['TotalTimes'] = 'int' # T['FBTRequestID'] = 'int' # ID T['TID'] = 'int' # ID T['TradeAmount'] = 'double' # T['CustFee'] = 'double' # T['FutureFee'] = 'double' # T['SingleMaxAmt'] = 'double' # T['SingleMinAmt'] = 'double' # T['TotalAmt'] = 'double' # T['CertificationType'] = 'char' # CFT_IDCard = '0' # CFT_Passport = '1' # CFT_OfficerIDCard = '2' # CFT_SoldierIDCard = '3' # CFT_HomeComingCard = '4' # CFT_HouseholdRegister = '5' # CFT_InstitutionCodeCard = '7' # CFT_OtherCard = 'x' # CFT_SuperDepAgree = 'a' # T['FileBusinessCode'] = 'char' # FBC_Others = '0' # FBC_TransferDetails = '1' # FBC_CustAccStatus = '2' # FBC_AccountTradeDetails = '3' # FBC_FutureAccountChangeInfoDetails = '4' # FBC_CustMoneyDetail = '5' # FBC_CustCancelAccountInfo = '6' # FBC_CustMoneyResult = '7' # FBC_OthersExceptionResult = '8' # FBC_CustInterestNetMoneyDetails = '9' # FBC_CustMoneySendAndReceiveDetails = 'a' # FBC_CorporationMoneyTotal = 'b' # FBC_MainbodyMoneyTotal = 'c' # FBC_MainPartMonitorData = 'd' # FBC_PreparationMoney = 'e' # FBC_BankMoneyMonitorData = 'f' # T['CashExchangeCode'] = 'char' # CEC_Exchange = '1' # CEC_Cash = '2' # T['YesNoIndicator'] = 'char' # YNI_Yes = '0' # YNI_No = '1' # T['BanlanceType'] = 'char' # BLT_CurrentMoney = '0' # BLT_UsableMoney = '1' # BLT_FetchableMoney = '2' # BLT_FreezeMoney = '3' # T['Gender'] = 'char' # GD_Unknown = '0' # GD_Male = '1' # GD_Female = '2' # T['FeePayFlag'] = 'char' # FPF_BEN = '0' # FPF_OUR = '1' # FPF_SHA = '2' # T['PassWordKeyType'] = 'char' # PWKT_ExchangeKey = '0' # PWKT_PassWordKey = '1' # PWKT_MACKey = '2' # MAC PWKT_MessageKey = '3' # T['FBTPassWordType'] = 'char' # PWT_Query = '0' # PWT_Fetch = '1' # PWT_Transfer = '2' # PWT_Trade = '3' # T['FBTEncryMode'] = 'char' # EM_NoEncry = '0' # EM_DES = '1' # DES EM_3DES = '2' # 3DES T['BankRepealFlag'] = 'char' # BRF_BankNotNeedRepeal = '0' # BRF_BankWaitingRepeal = '1' # BRF_BankBeenRepealed = '2' # T['BrokerRepealFlag'] = 'char' # BRORF_BrokerNotNeedRepeal = '0' # BRORF_BrokerWaitingRepeal = '1' # BRORF_BrokerBeenRepealed = '2' # T['InstitutionType'] = 'char' # TS_Bank = '0' # TS_Future = '1' # TS_Store = '2' # T['LastFragment'] = 'char' # LF_Yes = '0' # LF_No = '1' # T['BankAccStatus'] = 'char' # BAS_Normal = '0' # BAS_Freeze = '1' # BAS_ReportLoss = '2' # T['MoneyAccountStatus'] = 'char' # MAS_Normal = '0' # MAS_Cancel = '1' # T['ManageStatus'] = 'char' # MSS_Point = '0' # MSS_PrePoint = '1' # MSS_CancelPoint = '2' # T['SystemType'] = 'char' # SYT_FutureBankTransfer = '0' # SYT_StockBankTransfer = '1' # SYT_TheThirdPartStore = '2' # T['TxnEndFlag'] = 'char' # TEF_NormalProcessing = '0' # TEF_Success = '1' # TEF_Failed = '2' # TEF_Abnormal = '3' # TEF_ManualProcessedForException = '4' # TEF_CommuFailedNeedManualProcess = '5' # TEF_SysErrorNeedManualProcess = '6' # T['ProcessStatus'] = 'char' # PSS_NotProcess = '0' # PSS_StartProcess = '1' # PSS_Finished = '2' # T['CustType'] = 'char' # CUSTT_Person = '0' # CUSTT_Institution = '1' # T['FBTTransferDirection'] = 'char' # FBTTD_FromBankToFuture = '1' # FBTTD_FromFutureToBank = '2' # T['OpenOrDestroy'] = 'char' # OOD_Open = '1' # OOD_Destroy = '0' # T['AvailabilityFlag'] = 'char' # AVAF_Invalid = '0' # AVAF_Valid = '1' # AVAF_Repeal = '2' # T['OrganType'] = 'char' # OT_Bank = '1' # OT_Future = '2' # OT_PlateForm = '9' # T['OrganLevel'] = 'char' # OL_HeadQuarters = '1' # OL_Branch = '2' # T['ProtocalID'] = 'char' # PID_FutureProtocal = '0' # PID_ICBCProtocal = '1' # PID_ABCProtocal = '2' # PID_CBCProtocal = '3' # PID_CCBProtocal = '4' # PID_BOCOMProtocal = '5' # PID_FBTPlateFormProtocal = 'X' # T['ConnectMode'] = 'char' # CM_ShortConnect = '0' # CM_LongConnect = '1' # T['SyncMode'] = 'char' # SRM_ASync = '0' # SRM_Sync = '1' # T['BankAccType'] = 'char' # BAT_BankBook = '1' # BAT_SavingCard = '2' # BAT_CreditCard = '3' # T['FutureAccType'] = 'char' # FAT_BankBook = '1' # FAT_SavingCard = '2' # FAT_CreditCard = '3' # T['OrganStatus'] = 'char' # OS_Ready = '0' # OS_CheckIn = '1' # OS_CheckOut = '2' # OS_CheckFileArrived = '3' # OS_CheckDetail = '4' # OS_DayEndClean = '5' # OS_Invalid = '9' # T['CCBFeeMode'] = 'char' # CCBFM_ByAmount = '1' # CCBFM_ByMonth = '2' # T['CommApiType'] = 'char' # API CAPIT_Client = '1' # CAPIT_Server = '2' # CAPIT_UserApi = '3' # UserApi T['ServiceID'] = 'int' # T['ServiceLineNo'] = 'int' # T['ServiceName'] = 'char[61]' # T['LinkStatus'] = 'char' # LS_Connected = '1' # LS_Disconnected = '2' # T['CommApiPointer'] = 'int' # API T['PwdFlag'] = 'char' # BPWDF_NoCheck = '0' # BPWDF_BlankCheck = '1' # BPWDF_EncryptCheck = '2' # T['SecuAccType'] = 'char' # SAT_AccountID = '1' # SAT_CardID = '2' # SAT_SHStockholderID = '3' # SAT_SZStockholderID = '4' # T['TransferStatus'] = 'char' # TRFS_Normal = '0' # TRFS_Repealed = '1' # T['SponsorType'] = 'char' # SPTYPE_Broker = '0' # SPTYPE_Bank = '1' # T['ReqRspType'] = 'char' # REQRSP_Request = '0' # REQRSP_Response = '1' # T['FBTUserEventType'] = 'char' # FBTUET_SignIn = '0' # FBTUET_FromBankToFuture = '1' # FBTUET_FromFutureToBank = '2' # FBTUET_OpenAccount = '3' # FBTUET_CancelAccount = '4' # FBTUET_ChangeAccount = '5' # FBTUET_RepealFromBankToFuture = '6' # FBTUET_RepealFromFutureToBank = '7' # FBTUET_QueryBankAccount = '8' # FBTUET_QueryFutureAccount = '9' # FBTUET_SignOut = 'A' # FBTUET_SyncKey = 'B' # FBTUET_Other = 'Z' # T['BankIDByBank'] = 'char[21]' # T['BankOperNo'] = 'char[4]' # T['BankCustNo'] = 'char[21]' # T['DBOPSeqNo'] = 'int' # T['TableName'] = 'char[61]' # FBT T['PKName'] = 'char[201]' # FBT T['PKValue'] = 'char[501]' # FBT T['DBOperation'] = 'char' # DBOP_Insert = '0' # DBOP_Update = '1' # DBOP_Delete = '2' # T['SyncFlag'] = 'char' # SYNF_Yes = '0' # SYNF_No = '1' # T['TargetID'] = 'char[4]' # T['SyncType'] = 'char' # SYNT_OneOffSync = '0' # SYNT_TimerSync = '1' # SYNT_TimerFullSync = '2' # T['FBETime'] = 'char[7]' # T['FBEBankNo'] = 'char[13]' # T['FBECertNo'] = 'char[13]' # T['ExDirection'] = 'char' # FBEDIR_Settlement = '0' # FBEDIR_Sale = '1' # T['FBEBankAccount'] = 'char[33]' # T['FBEBankAccountName'] = 'char[61]' # T['FBEAmt'] = 'double' # T['FBEBusinessType'] = 'char[3]' # T['FBEPostScript'] = 'char[61]' # T['FBERemark'] = 'char[71]' # T['ExRate'] = 'double' # T['FBEResultFlag'] = 'char' # FBERES_Success = '0' # FBERES_InsufficientBalance = '1' # FBERES_UnknownTrading = '8' # FBERES_Fail = 'x' # T['FBERtnMsg'] = 'char[61]' # T['FBEExtendMsg'] = 'char[61]' # T['FBEBusinessSerial'] = 'char[31]' # T['FBESystemSerial'] = 'char[21]' # T['FBETotalExCnt'] = 'int' # T['FBEExchStatus'] = 'char' # FBEES_Normal = '0' # FBEES_ReExchange = '1' # T['FBEFileFlag'] = 'char' # FBEFG_DataPackage = '0' # FBEFG_File = '1' # T['FBEAlreadyTrade'] = 'char' # FBEAT_NotTrade = '0' # FBEAT_Trade = '1' # T['FBEOpenBank'] = 'char[61]' # T['FBEUserEventType'] = 'char' # FBEUET_SignIn = '0' # FBEUET_Exchange = '1' # FBEUET_ReExchange = '2' # FBEUET_QueryBankAccount = '3' # FBEUET_QueryExchDetial = '4' # FBEUET_QueryExchSummary = '5' # FBEUET_QueryExchRate = '6' # FBEUET_CheckBankAccount = '7' # FBEUET_SignOut = '8' # FBEUET_Other = 'Z' # T['FBEFileName'] = 'char[21]' # T['FBEBatchSerial'] = 'char[21]' # T['FBEReqFlag'] = 'char' # FBERF_UnProcessed = '0' # FBERF_WaitSend = '1' # FBERF_SendSuccess = '2' # FBERF_SendFailed = '3' # FBERF_WaitReSend = '4' # T['NotifyClass'] = 'char' # NC_NOERROR = '0' # NC_Warn = '1' # NC_Call = '2' # NC_Force = '3' # NC_CHUANCANG = '4' # NC_Exception = '5' # T['RiskNofityInfo'] = 'char[257]' # T['ForceCloseSceneId'] = 'char[24]' # T['ForceCloseType'] = 'char' # FCT_Manual = '0' # FCT_Single = '1' # FCT_Group = '2' # T['InstrumentIDs'] = 'char[101]' # ,+,cu+zn T['RiskNotifyMethod'] = 'char' # RNM_System = '0' # RNM_SMS = '1' # RNM_EMail = '2' # RNM_Manual = '3' # T['RiskNotifyStatus'] = 'char' # RNS_NotGen = '0' # RNS_Generated = '1' # RNS_SendError = '2' # RNS_SendOk = '3' # RNS_Received = '4' # RNS_Confirmed = '5' # T['RiskUserEvent'] = 'char' # RUE_ExportData = '0' # T['ParamID'] = 'int' # T['ParamName'] = 'char[41]' # T['ParamValue'] = 'char[41]' # T['ConditionalOrderSortType'] = 'char' # COST_LastPriceAsc = '0' # COST_LastPriceDesc = '1' # COST_AskPriceAsc = '2' # COST_AskPriceDesc = '3' # COST_BidPriceAsc = '4' # COST_BidPriceDesc = '5' # T['SendType'] = 'char' # UOAST_NoSend = '0' # UOAST_Sended = '1' # UOAST_Generated = '2' # UOAST_SendFail = '3' # UOAST_Success = '4' # UOAST_Fail = '5' # UOAST_Cancel = '6' # T['ClientIDStatus'] = 'char' # UOACS_NoApply = '1' # UOACS_Submited = '2' # UOACS_Sended = '3' # UOACS_Success = '4' # UOACS_Refuse = '5' # UOACS_Cancel = '6' # T['IndustryID'] = 'char[17]' # T['QuestionID'] = 'char[5]' # T['QuestionContent'] = 'char[41]' # T['OptionID'] = 'char[13]' # T['OptionContent'] = 'char[61]' # T['QuestionType'] = 'char' # QT_Radio = '1' # QT_Option = '2' # QT_Blank = '3' # T['ProcessID'] = 'char[33]' # T['SeqNo'] = 'int' # T['UOAProcessStatus'] = 'char[3]' # T['ProcessType'] = 'char[3]' # T['BusinessType'] = 'char' # BT_Request = '1' # BT_Response = '2' # BT_Notice = '3' # T['CfmmcReturnCode'] = 'char' # CRC_Success = '0' # CRC_Working = '1' # CRC_InfoFail = '2' # CRC_IDCardFail = '3' # CRC_OtherFail = '4' # T['ExReturnCode'] = 'int' # T['ClientType'] = 'char' # CfMMCCT_All = '0' # CfMMCCT_Person = '1' # CfMMCCT_Company = '2' # CfMMCCT_Other = '3' # CfMMCCT_SpecialOrgan = '4' # CfMMCCT_Asset = '5' # T['ExchangeIDType'] = 'char' # EIDT_SHFE = 'S' # EIDT_CZCE = 'Z' # EIDT_DCE = 'D' # EIDT_CFFEX = 'J' # EIDT_INE = 'N' # T['ExClientIDType'] = 'char' # ECIDT_Hedge = '1' # ECIDT_Arbitrage = '2' # ECIDT_Speculation = '3' # T['ClientClassify'] = 'char[11]' # T['UOAOrganType'] = 'char[11]' # T['UOACountryCode'] = 'char[11]' # T['AreaCode'] = 'char[11]' # T['FuturesID'] = 'char[21]' # T['CffmcDate'] = 'char[11]' # T['CffmcTime'] = 'char[11]' # T['NocID'] = 'char[21]' # T['UpdateFlag'] = 'char' # UF_NoUpdate = '0' # UF_Success = '1' # UF_Fail = '2' # UF_TCSuccess = '3' # UF_TCFail = '4' # UF_Cancel = '5' # T['ApplyOperateID'] = 'char' # AOID_OpenInvestor = '1' # AOID_ModifyIDCard = '2' # AOID_ModifyNoIDCard = '3' # AOID_ApplyTradingCode = '4' # AOID_CancelTradingCode = '5' # AOID_CancelInvestor = '6' # AOID_FreezeAccount = '8' # AOID_ActiveFreezeAccount = '9' # T['ApplyStatusID'] = 'char' # ASID_NoComplete = '1' # ASID_Submited = '2' # ASID_Checked = '3' # ASID_Refused = '4' # ASID_Deleted = '5' # T['SendMethod'] = 'char' # UOASM_ByAPI = '1' # UOASM_ByFile = '2' # T['EventType'] = 'char[33]' # T['EventMode'] = 'char' # EvM_ADD = '1' # EvM_UPDATE = '2' # EvM_DELETE = '3' # EvM_CHECK = '4' # EvM_COPY = '5' # EvM_CANCEL = '6' # EvM_Reverse = '7' # T['UOAAutoSend'] = 'char' # UOAA_ASR = '1' # UOAA_ASNR = '2' # UOAA_NSAR = '3' # UOAA_NSR = '4' # T['QueryDepth'] = 'int' # T['DataCenterID'] = 'int' # T['FlowID'] = 'char' # ID EvM_InvestorGroupFlow = '1' # EvM_InvestorRate = '2' # EvM_InvestorCommRateModel = '3' # T['CheckLevel'] = 'char' # CL_Zero = '0' # CL_One = '1' # CL_Two = '2' # T['CheckNo'] = 'int' # T['CheckStatus'] = 'char' # CHS_Init = '0' # CHS_Checking = '1' # CHS_Checked = '2' # CHS_Refuse = '3' # CHS_Cancel = '4' # T['UsedStatus'] = 'char' # CHU_Unused = '0' # CHU_Used = '1' # CHU_Fail = '2' # T['RateTemplateName'] = 'char[61]' # T['PropertyString'] = 'char[2049]' # T['BankAcountOrigin'] = 'char' # BAO_ByAccProperty = '0' # BAO_ByFBTransfer = '1' # T['MonthBillTradeSum'] = 'char' # MBTS_ByInstrument = '0' # MBTS_ByDayInsPrc = '1' # MBTS_ByDayIns = '2' # T['FBTTradeCodeEnum'] = 'char[7]' # FTC_BankLaunchBankToBroker = '102001' # FTC_BrokerLaunchBankToBroker = '202001' # FTC_BankLaunchBrokerToBank = '102002' # FTC_BrokerLaunchBrokerToBank = '202002' # T['RateTemplateID'] = 'char[9]' # T['RiskRate'] = 'char[21]' # T['Timestamp'] = 'int' # T['InvestorIDRuleName'] = 'char[61]' # T['InvestorIDRuleExpr'] = 'char[513]' # T['LastDrift'] = 'int' # OTP T['LastSuccess'] = 'int' # OTP T['AuthKey'] = 'char[41]' # T['SerialNumber'] = 'char[17]' # T['OTPType'] = 'char' # OTP_NONE = '0' # OTP_TOTP = '1' # T['OTPVendorsID'] = 'char[2]' # T['OTPVendorsName'] = 'char[61]' # T['OTPStatus'] = 'char' # OTPS_Unused = '0' # OTPS_Used = '1' # OTPS_Disuse = '2' # T['BrokerUserType'] = 'char' # BUT_Investor = '1' # BUT_BrokerUser = '2' # T['FutureType'] = 'char' # FUTT_Commodity = '1' # FUTT_Financial = '2' # T['FundEventType'] = 'char' # FET_Restriction = '0' # FET_TodayRestriction = '1' # FET_Transfer = '2' # FET_Credit = '3' # FET_InvestorWithdrawAlm = '4' # FET_BankRestriction = '5' # FET_Accountregister = '6' # FET_ExchangeFundIO = '7' # FET_InvestorFundIO = '8' # T['AccountSourceType'] = 'char' # AST_FBTransfer = '0' # AST_ManualEntry = '1' # T['CodeSourceType'] = 'char' # CST_UnifyAccount = '0' # () CST_ManualEntry = '1' # () T['UserRange'] = 'char' # UR_All = '0' # UR_Single = '1' # T['TimeSpan'] = 'char[9]' # T['ImportSequenceID'] = 'char[17]' # T['ByGroup'] = 'char' # BG_Investor = '2' # BG_Group = '1' # T['TradeSumStatMode'] = 'char' # TSSM_Instrument = '1' # TSSM_Product = '2' # TSSM_Exchange = '3' # T['ComType'] = 'int' # T['UserProductID'] = 'char[33]' # T['UserProductName'] = 'char[65]' # T['UserProductMemo'] = 'char[129]' # T['CSRCCancelFlag'] = 'char[2]' # T['CSRCDate'] = 'char[11]' # T['CSRCInvestorName'] = 'char[201]' # T['CSRCOpenInvestorName'] = 'char[101]' # T['CSRCInvestorID'] = 'char[13]' # T['CSRCIdentifiedCardNo'] = 'char[51]' # T['CSRCClientID'] = 'char[11]' # T['CSRCBankFlag'] = 'char[3]' # T['CSRCBankAccount'] = 'char[23]' # T['CSRCOpenName'] = 'char[401]' # T['CSRCMemo'] = 'char[101]' # T['CSRCTime'] = 'char[11]' # T['CSRCTradeID'] = 'char[21]' # T['CSRCExchangeInstID'] = 'char[31]' # T['CSRCMortgageName'] = 'char[7]' # T['CSRCReason'] = 'char[3]' # T['IsSettlement'] = 'char[2]' # T['CSRCMoney'] = 'double' # T['CSRCPrice'] = 'double' # T['CSRCOptionsType'] = 'char[2]' # T['CSRCStrikePrice'] = 'double' # T['CSRCTargetProductID'] = 'char[3]' # T['CSRCTargetInstrID'] = 'char[31]' # T['CommModelName'] = 'char[161]' # T['CommModelMemo'] = 'char[1025]' # T['ExprSetMode'] = 'char' # ESM_Relative = '1' # ESM_Typical = '2' # T['RateInvestorRange'] = 'char' # RIR_All = '1' # RIR_Model = '2' # RIR_Single = '3' # T['AgentBrokerID'] = 'char[13]' # T['DRIdentityID'] = 'int' # T['DRIdentityName'] = 'char[65]' # T['DBLinkID'] = 'char[31]' # DBLink T['SyncDataStatus'] = 'char' # SDS_Initialize = '0' # SDS_Settlementing = '1' # SDS_Settlemented = '2' # T['TradeSource'] = 'char' # TSRC_NORMAL = '0' # TSRC_QUERY = '1' # T['FlexStatMode'] = 'char' # FSM_Product = '1' # FSM_Exchange = '2' # FSM_All = '3' # T['ByInvestorRange'] = 'char' # BIR_Property = '1' # BIR_All = '2' # T['SRiskRate'] = 'char[21]' # T['SequenceNo12'] = 'int' # T['PropertyInvestorRange'] = 'char' # PIR_All = '1' # PIR_Property = '2' # PIR_Single = '3' # T['FileStatus'] = 'char' # FIS_NoCreate = '0' # FIS_Created = '1' # FIS_Failed = '2' # T['FileGenStyle'] = 'char' # FGS_FileTransmit = '0' # FGS_FileGen = '1' # T['SysOperMode'] = 'char' # SoM_Add = '1' # SoM_Update = '2' # SoM_Delete = '3' # SoM_Copy = '4' # SoM_AcTive = '5' # SoM_CanCel = '6' # SoM_ReSet = '7' # T['SysOperType'] = 'char' # SoT_UpdatePassword = '0' # SoT_UserDepartment = '1' # SoT_RoleManager = '2' # SoT_RoleFunction = '3' # SoT_BaseParam = '4' # SoT_SetUserID = '5' # SoT_SetUserRole = '6' # SoT_UserIpRestriction = '7' # IP SoT_DepartmentManager = '8' # SoT_DepartmentCopy = '9' # SoT_Tradingcode = 'A' # SoT_InvestorStatus = 'B' # SoT_InvestorAuthority = 'C' # SoT_PropertySet = 'D' # SoT_ReSetInvestorPasswd = 'E' # SoT_InvestorPersonalityInfo = 'F' # T['CSRCDataQueyType'] = 'char' # CSRCQ_Current = '0' # CSRCQ_History = '1' # T['FreezeStatus'] = 'char' # FRS_Normal = '1' # FRS_Freeze = '0' # T['StandardStatus'] = 'char' # STST_Standard = '0' # STST_NonStandard = '1' # T['CSRCFreezeStatus'] = 'char[2]' # T['RightParamType'] = 'char' # RPT_Freeze = '1' # RPT_FreezeActive = '2' # RPT_OpenLimit = '3' # RPT_RelieveOpenLimit = '4' # T['RightTemplateID'] = 'char[9]' # T['RightTemplateName'] = 'char[61]' # T['DataStatus'] = 'char' # AMLDS_Normal = '0' # AMLDS_Deleted = '1' # T['AMLCheckStatus'] = 'char' # AMLCHS_Init = '0' # AMLCHS_Checking = '1' # AMLCHS_Checked = '2' # AMLCHS_RefuseReport = '3' # T['AmlDateType'] = 'char' # AMLDT_DrawDay = '0' # AMLDT_TouchDay = '1' # T['AmlCheckLevel'] = 'char' # AMLCL_CheckLevel0 = '0' # AMLCL_CheckLevel1 = '1' # AMLCL_CheckLevel2 = '2' # AMLCL_CheckLevel3 = '3' # T['AmlCheckFlow'] = 'char[2]' # T['DataType'] = 'char[129]' # T['ExportFileType'] = 'char' # EFT_CSV = '0' # CSV EFT_EXCEL = '1' # Excel EFT_DBF = '2' # DBF T['SettleManagerType'] = 'char' # SMT_Before = '1' # SMT_Settlement = '2' # SMT_After = '3' # SMT_Settlemented = '4' # T['SettleManagerID'] = 'char[33]' # T['SettleManagerName'] = 'char[129]' # T['SettleManagerLevel'] = 'char' # SML_Must = '1' # SML_Alarm = '2' # SML_Prompt = '3' # SML_Ignore = '4' # T['SettleManagerGroup'] = 'char' # SMG_Exhcange = '1' # SMG_ASP = '2' # SMG_CSRC = '3' # T['CheckResultMemo'] = 'char[1025]' # T['FunctionUrl'] = 'char[1025]' # T['AuthInfo'] = 'char[129]' # T['AuthCode'] = 'char[17]' # T['LimitUseType'] = 'char' # LUT_Repeatable = '1' # LUT_Unrepeatable = '2' # T['DataResource'] = 'char' # DAR_Settle = '1' # DAR_Exchange = '2' # DAR_CSRC = '3' # T['MarginType'] = 'char' # MGT_ExchMarginRate = '0' # MGT_InstrMarginRate = '1' # MGT_InstrMarginRateTrade = '2' # T['ActiveType'] = 'char' # ACT_Intraday = '1' # ACT_Long = '2' # T['MarginRateType'] = 'char' # MRT_Exchange = '1' # MRT_Investor = '2' # MRT_InvestorTrade = '3' # T['BackUpStatus'] = 'char' # BUS_UnBak = '0' # BUS_BakUp = '1' # BUS_BakUped = '2' # BUS_BakFail = '3' # T['InitSettlement'] = 'char' # SIS_UnInitialize = '0' # SIS_Initialize = '1' # SIS_Initialized = '2' # T['ReportStatus'] = 'char' # SRS_NoCreate = '0' # SRS_Create = '1' # SRS_Created = '2' # SRS_CreateFail = '3' # T['SaveStatus'] = 'char' # SSS_UnSaveData = '0' # SSS_SaveDatad = '1' # T['SettArchiveStatus'] = 'char' # SAS_UnArchived = '0' # SAS_Archiving = '1' # SAS_Archived = '2' # SAS_ArchiveFail = '3' # T['CTPType'] = 'char' # CTP CTPT_Unkown = '0' # CTPT_MainCenter = '1' # CTPT_BackUp = '2' # T['ToolID'] = 'char[9]' # T['ToolName'] = 'char[81]' # T['CloseDealType'] = 'char' # CDT_Normal = '0' # CDT_SpecFirst = '1' # T['MortgageFundUseRange'] = 'char' # MFUR_None = '0' # MFUR_Margin = '1' # MFUR_All = '2' # T['CurrencyUnit'] = 'double' # T['ExchangeRate'] = 'double' # T['SpecProductType'] = 'char' # SPT_CzceHedge = '1' # SPT_IneForeignCurrency = '2' # SPT_DceOpenClose = '3' # T['FundMortgageType'] = 'char' # FMT_Mortgage = '1' # FMT_Redemption = '2' # T['AccountSettlementParamID'] = 'char' # ASPI_BaseMargin = '1' # ASPI_LowestInterest = '2' # T['CurrencyName'] = 'char[31]' # T['CurrencySign'] = 'char[4]' # T['FundMortDirection'] = 'char' # FMD_In = '1' # FMD_Out = '2' # T['BusinessClass'] = 'char' # BT_Profit = '0' # BT_Loss = '1' # BT_Other = 'Z' # T['SwapSourceType'] = 'char' # SST_Manual = '0' # SST_Automatic = '1' # T['CurrExDirection'] = 'char' # CED_Settlement = '0' # CED_Sale = '1' # T['CurrencySwapStatus'] = 'char' # CSS_Entry = '1' # CSS_Approve = '2' # CSS_Refuse = '3' # CSS_Revoke = '4' # CSS_Send = '5' # CSS_Success = '6' # CSS_Failure = '7' # T['CurrExchCertNo'] = 'char[13]' # T['BatchSerialNo'] = 'char[21]' # T['ReqFlag'] = 'char' # REQF_NoSend = '0' # REQF_SendSuccess = '1' # REQF_SendFailed = '2' # REQF_WaitReSend = '3' # T['ResFlag'] = 'char' # RESF_Success = '0' # RESF_InsuffiCient = '1' # RESF_UnKnown = '8' # T['PageControl'] = 'char[2]' # T['RecordCount'] = 'int' # T['CurrencySwapMemo'] = 'char[101]' # T['ExStatus'] = 'char' # EXS_Before = '0' # EXS_After = '1' # T['ClientRegion'] = 'char' # CR_Domestic = '1' # CR_GMT = '2' # CR_Foreign = '3' # T['WorkPlace'] = 'char[101]' # T['BusinessPeriod'] = 'char[21]' # T['WebSite'] = 'char[101]' # T['UOAIdCardType'] = 'char[3]' # T['ClientMode'] = 'char[3]' # T['InvestorFullName'] = 'char[101]' # T['UOABrokerID'] = 'char[11]' # ID T['UOAZipCode'] = 'char[11]' # T['UOAEMail'] = 'char[101]' # T['OldCity'] = 'char[41]' # T['CorporateIdentifiedCardNo'] = 'char[101]' # T['HasBoard'] = 'char' # HB_No = '0' # HB_Yes = '1' # T['StartMode'] = 'char' # SM_Normal = '1' # SM_Emerge = '2' # SM_Restore = '3' # T['TemplateType'] = 'char' # TPT_Full = '1' # TPT_Increment = '2' # TPT_BackUp = '3' # T['LoginMode'] = 'char' # LM_Trade = '0' # LM_Transfer = '1' # T['PromptType'] = 'char' # CPT_Instrument = '1' # CPT_Margin = '2' # T['LedgerManageID'] = 'char[51]' # T['InvestVariety'] = 'char[101]' # T['BankAccountType'] = 'char[2]' # T['LedgerManageBank'] = 'char[101]' # T['CffexDepartmentName'] = 'char[101]' # T['CffexDepartmentCode'] = 'char[9]' # T['HasTrustee'] = 'char' # HT_Yes = '1' # HT_No = '0' # T['CSRCMemo1'] = 'char[41]' # T['AssetmgrCFullName'] = 'char[101]' # T['AssetmgrApprovalNO'] = 'char[51]' # T['AssetmgrMgrName'] = 'char[401]' # T['AmType'] = 'char' # AMT_Bank = '1' # AMT_Securities = '2' # AMT_Fund = '3' # AMT_Insurance = '4' # AMT_Trust = '5' # AMT_Other = '9' # T['CSRCAmType'] = 'char[5]' # T['CSRCFundIOType'] = 'char' # CFIOT_FundIO = '0' # CFIOT_SwapCurrency = '1' # T['CusAccountType'] = 'char' # CAT_Futures = '1' # CAT_AssetmgrFuture = '2' # CAT_AssetmgrTrustee = '3' # CAT_AssetmgrTransfer = '4' # T['CSRCNational'] = 'char[4]' # T['CSRCSecAgentID'] = 'char[11]' # ID T['LanguageType'] = 'char' # LT_Chinese = '1' # LT_English = '2' # T['AmAccount'] = 'char[23]' # T['AssetmgrClientType'] = 'char' # AMCT_Person = '1' # AMCT_Organ = '2' # AMCT_SpecialOrgan = '4' # T['AssetmgrType'] = 'char' # ASST_Futures = '3' # ASST_SpecialOrgan = '4' # T['UOM'] = 'char[11]' # T['SHFEInstLifePhase'] = 'char[3]' # T['SHFEProductClass'] = 'char[11]' # T['PriceDecimal'] = 'char[2]' # T['InTheMoneyFlag'] = 'char[2]' # T['CheckInstrType'] = 'char' # CIT_HasExch = '0' # CIT_HasATP = '1' # CIT_HasDiff = '2' # T['DeliveryType'] = 'char' # DT_HandDeliv = '1' # DT_PersonDeliv = '2' # T['BigMoney'] = 'double' # T['MaxMarginSideAlgorithm'] = 'char' # MMSA_NO = '0' # MMSA_YES = '1' # T['DAClientType'] = 'char' # CACT_Person = '0' # CACT_Company = '1' # CACT_Other = '2' # T['CombinInstrID'] = 'char[61]' # T['CombinSettlePrice'] = 'char[61]' # T['DCEPriority'] = 'int' # T['TradeGroupID'] = 'int' # T['IsCheckPrepa'] = 'int' # T['UOAAssetmgrType'] = 'char' # UOAAT_Futures = '1' # UOAAT_SpecialOrgan = '2' # T['DirectionEn'] = 'char' # DEN_Buy = '0' # Buy DEN_Sell = '1' # Sell T['OffsetFlagEn'] = 'char' # OFEN_Open = '0' # Position Opening OFEN_Close = '1' # Position Close OFEN_ForceClose = '2' # Forced Liquidation OFEN_CloseToday = '3' # Close Today OFEN_CloseYesterday = '4' # Close Prev. OFEN_ForceOff = '5' # Forced Reduction OFEN_LocalForceClose = '6' # Local Forced Liquidation T['HedgeFlagEn'] = 'char' # HFEN_Speculation = '1' # Speculation HFEN_Arbitrage = '2' # Arbitrage HFEN_Hedge = '3' # Hedge T['FundIOTypeEn'] = 'char' # FIOTEN_FundIO = '1' # Deposit/Withdrawal FIOTEN_Transfer = '2' # Bank-Futures Transfer FIOTEN_SwapCurrency = '3' # Bank-Futures FX Exchange T['FundTypeEn'] = 'char' # FTEN_Deposite = '1' # Bank Deposit FTEN_ItemFund = '2' # Payment/Fee FTEN_Company = '3' # Brokerage Adj FTEN_InnerTransfer = '4' # Internal Transfer T['FundDirectionEn'] = 'char' # FDEN_In = '1' # Deposit FDEN_Out = '2' # Withdrawal T['FundMortDirectionEn'] = 'char' # FMDEN_In = '1' # Pledge FMDEN_Out = '2' # Redemption T['SwapBusinessType'] = 'char[3]' # T['OptionsType'] = 'char' # CP_CallOptions = '1' # CP_PutOptions = '2' # T['StrikeMode'] = 'char' # STM_Continental = '0' # STM_American = '1' # STM_Bermuda = '2' # T['StrikeType'] = 'char' # STT_Hedge = '0' # STT_Match = '1' # T['ApplyType'] = 'char' # APPT_NotStrikeNum = '4' # T['GiveUpDataSource'] = 'char' # GUDS_Gen = '0' # GUDS_Hand = '1' # T['ExecOrderSysID'] = 'char[21]' # T['ExecResult'] = 'char' # OER_NoExec = 'n' # OER_Canceled = 'c' # OER_OK = '0' # OER_NoPosition = '1' # OER_NoDeposit = '2' # OER_NoParticipant = '3' # OER_NoClient = '4' # OER_NoInstrument = '6' # OER_NoRight = '7' # OER_InvalidVolume = '8' # OER_NoEnoughHistoryTrade = '9' # OER_Unknown = 'a' # T['StrikeSequence'] = 'int' # T['StrikeTime'] = 'char[13]' # T['CombinationType'] = 'char' # COMBT_Future = '0' # COMBT_BUL = '1' # BUL COMBT_BER = '2' # BER COMBT_STD = '3' # COMBT_STG = '4' # COMBT_PRT = '5' # COMBT_CLD = '6' # T['OptionRoyaltyPriceType'] = 'char' # ORPT_PreSettlementPrice = '1' # ORPT_OpenPrice = '4' # T['BalanceAlgorithm'] = 'char' # BLAG_Default = '1' # BLAG_IncludeOptValLost = '2' # T['ActionType'] = 'char' # ACTP_Exec = '1' # ACTP_Abandon = '2' # T['ForQuoteStatus'] = 'char' # FQST_Submitted = 'a' # FQST_Accepted = 'b' # FQST_Rejected = 'c' # T['ValueMethod'] = 'char' # VM_Absolute = '0' # VM_Ratio = '1' # T['ExecOrderPositionFlag'] = 'char' # EOPF_Reserve = '0' # EOPF_UnReserve = '1' # T['ExecOrderCloseFlag'] = 'char' # EOCF_AutoClose = '0' # EOCF_NotToClose = '1' # T['ProductType'] = 'char' # PTE_Futures = '1' # PTE_Options = '2' # T['CZCEUploadFileName'] = 'char' # CUFN_CUFN_O = 'O' # ^\d{8}_zz_\d{4} CUFN_CUFN_T = 'T' # ^\d{8} CUFN_CUFN_P = 'P' # ^\d{8}new CUFN_CUFN_N = 'N' # ^\d{8} CUFN_CUFN_L = 'L' # ^\d{8} CUFN_CUFN_F = 'F' # ^\d{8} CUFN_CUFN_C = 'C' # ^\d{8} CUFN_CUFN_M = 'M' # ^\d{8} T['DCEUploadFileName'] = 'char' # DUFN_DUFN_O = 'O' # ^\d{8}_dl_\d{3} DUFN_DUFN_T = 'T' # ^\d{8}_ DUFN_DUFN_P = 'P' # ^\d{8}_ DUFN_DUFN_F = 'F' # ^\d{8}_ DUFN_DUFN_C = 'C' # ^\d{8}_ DUFN_DUFN_D = 'D' # ^\d{8}_ DUFN_DUFN_M = 'M' # ^\d{8}_ DUFN_DUFN_S = 'S' # ^\d{8}_ T['SHFEUploadFileName'] = 'char' # SUFN_SUFN_O = 'O' # ^\d{4}_\d{8}_\d{8}_DailyFundChg SUFN_SUFN_T = 'T' # ^\d{4}_\d{8}_\d{8}_Trade SUFN_SUFN_P = 'P' # ^\d{4}_\d{8}_\d{8}_SettlementDetail SUFN_SUFN_F = 'F' # ^\d{4}_\d{8}_\d{8}_Capital T['CFFEXUploadFileName'] = 'char' # CFUFN_SUFN_T = 'T' # ^\d{4}_SG\d{1}_\d{8}_\d{1}_Trade CFUFN_SUFN_P = 'P' # ^\d{4}_SG\d{1}_\d{8}_\d{1}_SettlementDetail CFUFN_SUFN_F = 'F' # ^\d{4}_SG\d{1}_\d{8}_\d{1}_Capital CFUFN_SUFN_S = 'S' # ^\d{4}_SG\d{1}_\d{8}_\d{1}_OptionExec T['CombDirection'] = 'char' # CMDR_Comb = '0' # CMDR_UnComb = '1' # error = { 'NONE': 0, 0: 'CTP:', 'INVALID_DATA_SYNC_STATUS': 1, 1: 'CTP:', 'INCONSISTENT_INFORMATION': 2, 2: 'CTP:', 'INVALID_LOGIN': 3, 3: 'CTP:', 'USER_NOT_ACTIVE': 4, 4: 'CTP:', 'DUPLICATE_LOGIN': 5, 5: 'CTP:', 'NOT_LOGIN_YET': 6, 6: 'CTP:', 'NOT_INITED': 7, 7: 'CTP:', 'FRONT_NOT_ACTIVE': 8, 8: 'CTP:', 'NO_PRIVILEGE': 9, 9: 'CTP:', 'CHANGE_OTHER_PASSWORD': 10, 10: 'CTP:', 'USER_NOT_FOUND': 11, 11: 'CTP:', 'BROKER_NOT_FOUND': 12, 12: 'CTP:', 'INVESTOR_NOT_FOUND': 13, 13: 'CTP:', 'OLD_PASSWORD_MISMATCH': 14, 14: 'CTP:', 'BAD_FIELD': 15, 15: 'CTP:', 'INSTRUMENT_NOT_FOUND': 16, 16: 'CTP:', 'INSTRUMENT_NOT_TRADING': 17, 17: 'CTP:', 'NOT_EXCHANGE_PARTICIPANT': 18, 18: 'CTP:', 'INVESTOR_NOT_ACTIVE': 19, 19: 'CTP:', 'NOT_EXCHANGE_CLIENT': 20, 20: 'CTP:', 'NO_VALID_TRADER_AVAILABLE': 21, 21: 'CTP:', 'DUPLICATE_ORDER_REF': 22, 22: 'CTP:', 'BAD_ORDER_ACTION_FIELD': 23, 23: 'CTP:', 'DUPLICATE_ORDER_ACTION_REF': 24, 24: 'CTP:', 'ORDER_NOT_FOUND': 25, 25: 'CTP:', 'INSUITABLE_ORDER_STATUS': 26, 26: 'CTP:', 'UNSUPPORTED_FUNCTION': 27, 27: 'CTP:', 'NO_TRADING_RIGHT': 28, 28: 'CTP:', 'CLOSE_ONLY': 29, 29: 'CTP:', 'OVER_CLOSE_POSITION': 30, 30: 'CTP:', 'INSUFFICIENT_MONEY': 31, 31: 'CTP:', 'DUPLICATE_PK': 32, 32: 'CTP:', 'CANNOT_FIND_PK': 33, 33: 'CTP:', 'CAN_NOT_INACTIVE_BROKER': 34, 34: 'CTP:', 'BROKER_SYNCHRONIZING': 35, 35: 'CTP:', 'BROKER_SYNCHRONIZED': 36, 36: 'CTP:', 'SHORT_SELL': 37, 37: 'CTP:', 'INVALID_SETTLEMENT_REF': 38, 38: 'CTP:', 'CFFEX_NETWORK_ERROR': 39, 39: 'CTP:', 'CFFEX_OVER_REQUEST': 40, 40: 'CTP:', 'CFFEX_OVER_REQUEST_PER_SECOND': 41, 41: 'CTP:', 'SETTLEMENT_INFO_NOT_CONFIRMED': 42, 42: 'CTP:', 'DEPOSIT_NOT_FOUND': 43, 43: 'CTP:', 'EXCHANG_TRADING': 44, 44: 'CTP:', 'PARKEDORDER_NOT_FOUND': 45, 45: 'CTP:', 'PARKEDORDER_HASSENDED': 46, 46: 'CTP:', 'PARKEDORDER_HASDELETE': 47, 47: 'CTP:', 'INVALID_INVESTORIDORPASSWORD': 48, 48: 'CTP:', 'INVALID_LOGIN_IPADDRESS': 49, 49: 'CTP:IP', 'OVER_CLOSETODAY_POSITION': 50, 50: 'CTP:', 'OVER_CLOSEYESTERDAY_POSITION': 51, 51: 'CTP:', 'BROKER_NOT_ENOUGH_CONDORDER': 52, 52: 'CTP:', 'INVESTOR_NOT_ENOUGH_CONDORDER': 53, 53: 'CTP:', 'BROKER_NOT_SUPPORT_CONDORDER': 54, 54: 'CTP:', 'RESEND_ORDER_BROKERINVESTOR_NOTMATCH': 55, 55: 'CTP:/', 'SYC_OTP_FAILED': 56, 56: 'CTP:', 'OTP_MISMATCH': 57, 57: 'CTP:', 'OTPPARAM_NOT_FOUND': 58, 58: 'CTP:', 'UNSUPPORTED_OTPTYPE': 59, 59: 'CTP:', 'SINGLEUSERSESSION_EXCEED_LIMIT': 60, 60: 'CTP:', 'EXCHANGE_UNSUPPORTED_ARBITRAGE': 61, 61: 'CTP:', 'NO_CONDITIONAL_ORDER_RIGHT': 62, 62: 'CTP:', 'AUTH_FAILED': 63, 63: 'CTP:', 'NOT_AUTHENT': 64, 64: 'CTP:', 'SWAPORDER_UNSUPPORTED': 65, 65: 'CTP:', 'OPTIONS_ONLY_SUPPORT_SPEC': 66, 66: 'CTP:', 'DUPLICATE_EXECORDER_REF': 67, 67: 'CTP:', 'RESEND_EXECORDER_BROKERINVESTOR_NOTMATCH': 68, 68: 'CTP:/', 'EXECORDER_NOTOPTIONS': 69, 69: 'CTP:', 'OPTIONS_NOT_SUPPORT_EXEC': 70, 70: 'CTP:', 'BAD_EXECORDER_ACTION_FIELD': 71, 71: 'CTP:', 'DUPLICATE_EXECORDER_ACTION_REF': 72, 72: 'CTP:', 'EXECORDER_NOT_FOUND': 73, 73: 'CTP:', 'OVER_EXECUTE_POSITION': 74, 74: 'CTP:', 'LOGIN_FORBIDDEN': 75, 75: 'CTP:', 'INVALID_TRANSFER_AGENT': 76, 76: 'CTP:', 'NO_FOUND_FUNCTION': 77, 77: 'CTP:', 'SEND_EXCHANGEORDER_FAILED': 78, 78: 'CTP:', 'SEND_EXCHANGEORDERACTION_FAILED': 79, 79: 'CTP:', 'PRICETYPE_NOTSUPPORT_BYEXCHANGE': 80, 80: 'CTP:', 'BAD_EXECUTE_TYPE': 81, 81: 'CTP:', 'BAD_OPTION_INSTR': 82, 82: 'CTP:', 'INSTR_NOTSUPPORT_FORQUOTE': 83, 83: 'CTP:', 'RESEND_QUOTE_BROKERINVESTOR_NOTMATCH': 84, 84: 'CTP:/', 'INSTR_NOTSUPPORT_QUOTE': 85, 85: 'CTP:', 'QUOTE_NOT_FOUND': 86, 86: 'CTP:', 'OPTIONS_NOT_SUPPORT_ABANDON': 87, 87: 'CTP:', 'COMBOPTIONS_SUPPORT_IOC_ONLY': 88, 88: 'CTP:IOC', 'OPEN_FILE_FAILED': 89, 89: 'CTP:', 'NEED_RETRY': 90, 90: 'CTP', 'EXCHANGE_RTNERROR': 91, 91: 'CTP', 'QUOTE_DERIVEDORDER_ACTIONERROR': 92, 92: 'CTP:', 'INSTRUMENTMAP_NOT_FOUND': 93, 93: 'CTP:', 'NO_TRADING_RIGHT_IN_SEPC_DR': 101, 101: 'CTP:', 'NO_DR_NO': 102, 102: 'CTP:', 'BATCHACTION_NOSUPPORT': 103, 103: 'CTP:', 'OUT_OF_TIMEINTERVAL': 113, 113: 'CTP:', 'OUT_OF_PRICEINTERVAL': 114, 114: 'CTP:', 'SEND_INSTITUTION_CODE_ERROR': 1000, 1000: 'CTP:', 'NO_GET_PLATFORM_SN': 1001, 1001: 'CTP:', 'ILLEGAL_TRANSFER_BANK': 1002, 1002: 'CTP:', 'ALREADY_OPEN_ACCOUNT': 1003, 1003: 'CTP:', 'NOT_OPEN_ACCOUNT': 1004, 1004: 'CTP:', 'PROCESSING': 1005, 1005: 'CTP:', 'OVERTIME': 1006, 1006: 'CTP:', 'RECORD_NOT_FOUND': 1007, 1007: 'CTP:', 'NO_FOUND_REVERSAL_ORIGINAL_TRANSACTION': 1008, 1008: 'CTP:', 'CONNECT_HOST_FAILED': 1009, 1009: 'CTP:', 'SEND_FAILED': 1010, 1010: 'CTP:', 'LATE_RESPONSE': 1011, 1011: 'CTP:', 'REVERSAL_BANKID_NOT_MATCH': 1012, 1012: 'CTP:', 'REVERSAL_BANKACCOUNT_NOT_MATCH': 1013, 1013: 'CTP:', 'REVERSAL_BROKERID_NOT_MATCH': 1014, 1014: 'CTP:', 'REVERSAL_ACCOUNTID_NOT_MATCH': 1015, 1015: 'CTP:', 'REVERSAL_AMOUNT_NOT_MATCH': 1016, 1016: 'CTP:', 'DB_OPERATION_FAILED': 1017, 1017: 'CTP:', 'SEND_ASP_FAILURE': 1018, 1018: 'CTP:', 'NOT_SIGNIN': 1019, 1019: 'CTP:', 'ALREADY_SIGNIN': 1020, 1020: 'CTP:', 'AMOUNT_OR_TIMES_OVER': 1021, 1021: 'CTP:', 'NOT_IN_TRANSFER_TIME': 1022, 1022: 'CTP:', 'BANK_SERVER_ERROR': 1023, 1023: '', 'BANK_SERIAL_IS_REPEALED': 1024, 1024: 'CTP:', 'BANK_SERIAL_NOT_EXIST': 1025, 1025: 'CTP:', 'NOT_ORGAN_MAP': 1026, 1026: 'CTP:', 'EXIST_TRANSFER': 1027, 1027: 'CTP:', 'BANK_FORBID_REVERSAL': 1028, 1028: 'CTP:', 'DUP_BANK_SERIAL': 1029, 1029: 'CTP:', 'FBT_SYSTEM_BUSY': 1030, 1030: 'CTP:', 'MACKEY_SYNCING': 1031, 1031: 'CTP:MAC', 'ACCOUNTID_ALREADY_REGISTER': 1032, 1032: 'CTP:', 'BANKACCOUNT_ALREADY_REGISTER': 1033, 1033: 'CTP:', 'DUP_BANK_SERIAL_REDO_OK': 1034, 1034: 'CTP:,', 'CURRENCYID_NOT_SUPPORTED': 1035, 1035: 'CTP:', 'INVALID_MAC': 1036, 1036: 'CTP:MAC', 'NOT_SUPPORT_SECAGENT_BY_BANK': 1037, 1037: 'CTP:', 'PINKEY_SYNCING': 1038, 1038: 'CTP:PIN', 'SECAGENT_QUERY_BY_CCB': 1039, 1039: 'CTP:', 'NO_VALID_BANKOFFER_AVAILABLE': 2000, 2000: 'CTP:', 'PASSWORD_MISMATCH': 2001, 2001: 'CTP:', 'DUPLATION_BANK_SERIAL': 2004, 2004: 'CTP:', 'DUPLATION_OFFER_SERIAL': 2005, 2005: 'CTP:', 'SERIAL_NOT_EXSIT': 2006, 2006: 'CTP:()', 'SERIAL_IS_REPEALED': 2007, 2007: 'CTP:()', 'SERIAL_MISMATCH': 2008, 2008: 'CTP:()', 'IdentifiedCardNo_MISMATCH': 2009, 2009: 'CTP:', 'ACCOUNT_NOT_FUND': 2011, 2011: 'CTP:', 'ACCOUNT_NOT_ACTIVE': 2012, 2012: 'CTP:', 'NOT_ALLOW_REPEAL_BYMANUAL': 2013, 2013: 'CTP:', 'AMOUNT_OUTOFTHEWAY': 2014, 2014: 'CTP:', 'EXCHANGERATE_NOT_FOUND': 2015, 2015: 'CTP:', 'WAITING_OFFER_RSP': 999999, 999999: 'CTP:', 'FBE_NO_GET_PLATFORM_SN': 3001, 3001: 'CTP:', 'FBE_ILLEGAL_TRANSFER_BANK': 3002, 3002: 'CTP:', 'FBE_PROCESSING': 3005, 3005: 'CTP:', 'FBE_OVERTIME': 3006, 3006: 'CTP:', 'FBE_RECORD_NOT_FOUND': 3007, 3007: 'CTP:', 'FBE_CONNECT_HOST_FAILED': 3009, 3009: 'CTP:', 'FBE_SEND_FAILED': 3010, 3010: 'CTP:', 'FBE_LATE_RESPONSE': 3011, 3011: 'CTP:', 'FBE_DB_OPERATION_FAILED': 3017, 3017: 'CTP:', 'FBE_NOT_SIGNIN': 3019, 3019: 'CTP:', 'FBE_ALREADY_SIGNIN': 3020, 3020: 'CTP:', 'FBE_AMOUNT_OR_TIMES_OVER': 3021, 3021: 'CTP:', 'FBE_NOT_IN_TRANSFER_TIME': 3022, 3022: 'CTP:', 'FBE_BANK_SERVER_ERROR': 3023, 3023: 'CTP:', 'FBE_NOT_ORGAN_MAP': 3026, 3026: 'CTP:', 'FBE_SYSTEM_BUSY': 3030, 3030: 'CTP:', 'FBE_CURRENCYID_NOT_SUPPORTED': 3035, 3035: 'CTP:', 'FBE_WRONG_BANK_ACCOUNT': 3036, 3036: 'CTP:', 'FBE_BANK_ACCOUNT_NO_FUNDS': 3037, 3037: 'CTP:', 'FBE_DUP_CERT_NO': 3038, 3038: 'CTP:'} ```
/content/code_sandbox/trader/utils/ApiStruct.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
27,013
```python # coding=utf-8 # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the import asyncio import re from collections import defaultdict import datetime from decimal import Decimal import logging from django.db.models import Q, F, Sum from django.utils import timezone from talib import ATR import ujson as json import aioredis from trader.strategy import BaseModule from trader.utils.func_container import RegisterCallback from trader.utils.read_config import config, ctp_errors from trader.utils import ApiStruct, price_round, is_trading_day, update_from_shfe, update_from_dce, update_from_czce, update_from_cffex, \ get_contracts_argument, calc_main_inst, str_to_number, get_next_id, ORDER_REF_SIGNAL_ID_START, update_from_gfex from panel.models import * logger = logging.getLogger('CTPApi') HANDLER_TIME_OUT = config.getint('TRADE', 'command_timeout', fallback=10) class TradeStrategy(BaseModule): def __init__(self, name: str): super().__init__() self.__market_response_format = config.get('MSG_CHANNEL', 'market_response_format') self.__trade_response_format = config.get('MSG_CHANNEL', 'trade_response_format') self.__request_format = config.get('MSG_CHANNEL', 'request_format') self.__ignore_inst_list = config.get('TRADE', 'ignore_inst', fallback="WH,bb,JR,RI,RS,LR,PM,im").split(',') self.__strategy = Strategy.objects.get(name=name) self.__inst_ids = self.__strategy.instruments.all().values_list('product_code', flat=True) self.__broker = self.__strategy.broker self.__fake = self.__broker.fake # self.__current = self.__broker.current # self.__pre_balance = self.__broker.pre_balance # self.__cash = self.__broker.cash # self.__shares = dict() # { instrument : position } self.__cur_account = None self.__margin = self.__broker.margin # self.__withdraw = 0 # self.__deposit = 0 # self.__activeOrders = dict() # self.__cur_pos = dict() # self.__re_extract_code = re.compile(r'([a-zA-Z]*)(\d+)') # IF1509 -> IF self.__re_extract_name = re.compile('(.*?)([0-9]+)(.*?)$') # self.__trading_day = timezone.make_aware(datetime.datetime.strptime(self.raw_redis.get("TradingDay")+'08', '%Y%m%d%H')) self.__last_trading_day = timezone.make_aware(datetime.datetime.strptime(self.raw_redis.get("LastTradingDay")+'08', '%Y%m%d%H')) async def start(self): await self.install() self.raw_redis.set('HEARTBEAT:TRADER', 1, ex=61) today = timezone.localtime() now = int(today.strftime('%H%M')) if today.isoweekday() < 6 and (820 <= now <= 1550 or 2010 <= now <= 2359): # await self.refresh_account() order_list = await self.query('Order') for order in order_list: # if int(order['OrderStatus']) in range(1, 5) and order['OrderSubmitStatus'] == ApiStruct.OSS_Accepted: direct_str = DirectionType.values[order['Direction']] logger.info(f": {order['InstrumentID']} {direct_str} {order['VolumeTotal']} {order['LimitPrice']}") await self.cancel_order(order) # elif order['OrderSubmitStatus'] == ApiStruct.OSS_Accepted: self.save_order(order) await self.refresh_position() # today = timezone.make_aware(datetime.datetime.strptime(self.raw_redis.get('LastTradingDay'), '%Y%m%d')) # self.calculate(today, create_main_bar=False) # await self.processing_signal3() async def refresh_account(self): try: logger.debug('') account = await self.query('TradingAccount') account = account[0] self.__withdraw = Decimal(account['Withdraw']) self.__deposit = Decimal(account['Deposit']) # =()-+ fake = self.__fake - self.__deposit + self.__withdraw if fake < 1: fake = 0 # =+- self.__pre_balance = Decimal(account['PreBalance']) + self.__deposit - self.__withdraw # =++- self.__current = self.__pre_balance + Decimal(account['CloseProfit']) + Decimal(account['PositionProfit']) - Decimal(account['Commission']) self.__margin = Decimal(account['CurrMargin']) self.__cash = Decimal(account['Available']) self.__cur_account = account self.__broker.cash = self.__cash self.__broker.current = self.__current self.__broker.pre_balance = self.__pre_balance self.__broker.margin = self.__margin self.__broker.save(update_fields=['cash', 'current', 'pre_balance', 'margin']) logger.debug(f",: {self.__cash:,.0f} : {self.__pre_balance:,.0f} : {self.__current:,.0f} " f": {self.__withdraw - self.__deposit:,.0f} : {fake:,.0f}") except Exception as e: logger.warning(f'refresh_account : {repr(e)}', exc_info=True) async def refresh_position(self): try: logger.debug('...') pos_list = await self.query('InvestorPositionDetail') self.__cur_pos.clear() for pos in pos_list: if 'empty' in pos and pos['empty'] is True: continue if pos['Volume'] > 0: old_pos = self.__cur_pos.get(pos['InstrumentID']) if old_pos is None: self.__cur_pos[pos['InstrumentID']] = pos else: old_pos['OpenPrice'] = (old_pos['OpenPrice'] * old_pos['Volume'] + pos['OpenPrice'] * pos['Volume']) / (old_pos['Volume'] + pos['Volume']) old_pos['Volume'] += pos['Volume'] old_pos['PositionProfitByTrade'] += pos['PositionProfitByTrade'] old_pos['Margin'] += pos['Margin'] Trade.objects.filter(~Q(code__in=self.__cur_pos.keys()), close_time__isnull=True).delete() # for _, pos in self.__cur_pos.items(): p_code = self.__re_extract_code.match(pos['InstrumentID']).group(1) inst = Instrument.objects.get(product_code=p_code) trade = Trade.objects.filter(broker=self.__broker, strategy=self.__strategy, instrument=inst, code=pos['InstrumentID'], close_time__isnull=True, direction=DirectionType.values[pos['Direction']]).first() bar = DailyBar.objects.filter(code=pos['InstrumentID']).order_by('-time').first() profit = (bar.close - Decimal(pos['OpenPrice'])) * pos['Volume'] * inst.volume_multiple if pos['Direction'] == DirectionType.values[DirectionType.SHORT]: profit *= -1 if trade: trade.shares = (trade.closed_shares if trade.closed_shares else 0) + pos['Volume'] trade.filled_shares = trade.shares trade.profit = profit trade.save(update_fields=['shares', 'filled_shares', 'profit']) else: Trade.objects.create( broker=self.__broker, strategy=self.__strategy, instrument=inst, code=pos['InstrumentID'], profit=profit, filled_shares=pos['Volume'], direction=DirectionType.values[pos['Direction']], avg_entry_price=Decimal(pos['OpenPrice']), shares=pos['Volume'], open_time=timezone.make_aware(datetime.datetime.strptime(pos['OpenDate'] + '08', '%Y%m%d%H')), frozen_margin=Decimal(pos['Margin']), cost=pos['Volume'] * Decimal(pos['OpenPrice']) * inst.fee_money * inst.volume_multiple + pos['Volume'] * inst.fee_volume) logger.debug('!') except Exception as e: logger.warning(f'refresh_position : {repr(e)}', exc_info=True) async def refresh_instrument(self): try: logger.debug("...") inst_dict = defaultdict(dict) inst_list = await self.query('Instrument') for inst in inst_list: if inst['empty']: continue if inst['IsTrading'] == 1 and chr(inst['ProductClass']) == ApiStruct.PC_Futures and int(str_to_number(inst['StrikePrice'])) == 0: if inst['ProductID'] in self.__ignore_inst_list or inst['LongMarginRatio'] > 1: continue inst_dict[inst['ProductID']][inst['InstrumentID']] = dict() inst_dict[inst['ProductID']][inst['InstrumentID']]['name'] = inst['InstrumentName'] inst_dict[inst['ProductID']][inst['InstrumentID']]['exchange'] = inst['ExchangeID'] inst_dict[inst['ProductID']][inst['InstrumentID']]['multiple'] = inst['VolumeMultiple'] inst_dict[inst['ProductID']][inst['InstrumentID']]['price_tick'] = inst['PriceTick'] for code in inst_dict.keys(): all_inst = ','.join(sorted(inst_dict[code].keys())) inst_data = list(inst_dict[code].values())[0] valid_name = self.__re_extract_name.match(inst_data['name']) if valid_name is not None: valid_name = valid_name.group(1) else: valid_name = inst_data['name'] if valid_name == code: valid_name = '' inst_data['name'] = valid_name inst, created = Instrument.objects.update_or_create(product_code=code, exchange=inst_data['exchange']) print(f"inst:{inst} created:{created} main_code:{inst.main_code}") update_field_list = list() # if inst.main_code: margin_rate = await self.query('InstrumentMarginRate', InstrumentID=inst.main_code) inst.margin_rate = margin_rate[0]['LongMarginRatioByMoney'] fee = await self.query('InstrumentCommissionRate', InstrumentID=inst.main_code) inst.fee_money = Decimal(fee[0]['CloseRatioByMoney']) inst.fee_volume = Decimal(fee[0]['CloseRatioByVolume']) update_field_list += ['margin_rate', 'fee_money', 'fee_volume'] if created: inst.name = inst_data['name'] inst.volume_multiple = inst_data['multiple'] inst.price_tick = inst_data['price_tick'] update_field_list += ['name', 'volume_multiple', 'price_tick'] elif inst.main_code: inst.all_inst = all_inst update_field_list.append('all_inst') inst.save(update_fields=update_field_list) logger.debug("!") except Exception as e: logger.warning(f'refresh_instrument : {repr(e)}', exc_info=True) def getShares(self, instrument: str): # shares = 0 pos_price = 0 for pos in self.__shares[instrument]: pos_price += pos['Volume'] * pos['OpenPrice'] shares += pos['Volume'] * (-1 if pos['Direction'] == DirectionType.SHORT else 1) return shares, pos_price / abs(shares), self.__shares[instrument][0]['OpenDate'] def getPositions(self, inst_id: int): # return self.__shares[inst_id][0] def async_query(self, query_type: str, **kwargs): request_id = get_next_id() kwargs['RequestID'] = request_id self.raw_redis.publish(self.__request_format.format('ReqQry' + query_type), json.dumps(kwargs)) @staticmethod async def query_reader(pb: aioredis.client.PubSub): msg_list = [] async for msg in pb.listen(): # print(f"query_reader msg: {msg}") msg_dict = json.loads(msg['data']) if 'empty' not in msg_dict or not msg_dict['empty']: msg_list.append(msg_dict) if 'bIsLast' not in msg_dict or msg_dict['bIsLast']: return msg_list async def query(self, query_type: str, **kwargs): sub_client = None channel_rsp_qry, channel_rsp_err = None, None try: sub_client = self.redis_client.pubsub(ignore_subscribe_messages=True) request_id = get_next_id() kwargs['RequestID'] = request_id channel_rsp_qry = self.__trade_response_format.format('OnRspQry' + query_type, request_id) channel_rsp_err = self.__trade_response_format.format('OnRspError', request_id) await sub_client.psubscribe(channel_rsp_qry, channel_rsp_err) task = asyncio.create_task(self.query_reader(sub_client)) self.raw_redis.publish(self.__request_format.format('ReqQry' + query_type), json.dumps(kwargs)) await asyncio.wait_for(task, HANDLER_TIME_OUT) await sub_client.punsubscribe() await sub_client.close() return task.result() except Exception as e: logger.warning(f'{query_type} : {repr(e)}', exc_info=True) if sub_client and channel_rsp_qry: await sub_client.unsubscribe() await sub_client.close() return None async def SubscribeMarketData(self, inst_ids: list): sub_client = None channel_rsp_dat, channel_rsp_err = None, None try: sub_client = self.redis_client.pubsub(ignore_subscribe_messages=True) channel_rsp_dat = self.__market_response_format.format('OnRspSubMarketData', 0) channel_rsp_err = self.__market_response_format.format('OnRspError', 0) await sub_client.psubscribe(channel_rsp_dat, channel_rsp_err) task = asyncio.create_task(self.query_reader(sub_client)) self.raw_redis.publish(self.__request_format.format('SubscribeMarketData'), json.dumps(inst_ids)) await asyncio.wait_for(task, HANDLER_TIME_OUT) await sub_client.punsubscribe() await sub_client.close() return task.result() except Exception as e: logger.warning(f'SubscribeMarketData : {repr(e)}', exc_info=True) if sub_client and sub_client.in_pubsub and channel_rsp_dat: await sub_client.unsubscribe() await sub_client.close() return None async def UnSubscribeMarketData(self, inst_ids: list): sub_client = None channel_rsp_dat, channel_rsp_err = None, None try: sub_client = self.redis_client.pubsub(ignore_subscribe_messages=True) channel_rsp_dat = self.__market_response_format.format('OnRspUnSubMarketData', 0) channel_rsp_err = self.__market_response_format.format('OnRspError', 0) await sub_client.psubscribe(channel_rsp_dat, channel_rsp_err) task = asyncio.create_task(self.query_reader(sub_client)) self.raw_redis.publish(self.__request_format.format('UnSubscribeMarketData'), json.dumps(inst_ids)) await asyncio.wait_for(task, HANDLER_TIME_OUT) await sub_client.punsubscribe() await sub_client.close() return task.result() except Exception as e: logger.warning(f'UnSubscribeMarketData : {repr(e)}', exc_info=True) if sub_client and sub_client.in_pubsub and channel_rsp_dat: await sub_client.unsubscribe() await sub_client.close() return None def ReqOrderInsert(self, sig: Signal): try: request_id = get_next_id() autoid = Autonumber.objects.create() order_ref = f"{autoid.id:07}{sig.id:05}" param_dict = dict() param_dict['RequestID'] = request_id param_dict['OrderRef'] = order_ref param_dict['InstrumentID'] = sig.code param_dict['VolumeTotalOriginal'] = sig.volume param_dict['LimitPrice'] = float(sig.price) match sig.type: case SignalType.BUY | SignalType.SELL_SHORT: param_dict['Direction'] = ApiStruct.D_Buy if sig.type == SignalType.BUY else ApiStruct.D_Sell param_dict['CombOffsetFlag'] = ApiStruct.OF_Open logger.info(f'{sig.instrument} {sig.type}{sig.volume} : {sig.price}') case SignalType.BUY_COVER | SignalType.SELL: param_dict['Direction'] = ApiStruct.D_Buy if sig.type == SignalType.BUY_COVER else ApiStruct.D_Sell param_dict['CombOffsetFlag'] = ApiStruct.OF_Close pos = Trade.objects.filter( broker=self.__broker, strategy=self.__strategy, code=sig.code, shares=sig.volume, close_time__isnull=True, direction=DirectionType.values[DirectionType.SHORT] if sig.type == SignalType.BUY_COVER else DirectionType.values[ DirectionType.LONG]).first() if pos.open_time.astimezone().date() == timezone.localtime().date() and pos.instrument.exchange == ExchangeType.SHFE: param_dict['CombOffsetFlag'] = ApiStruct.OF_CloseToday # logger.info(f'{sig.instrument} {sig.type}{sig.volume} : {sig.price}') case SignalType.ROLL_CLOSE: param_dict['CombOffsetFlag'] = ApiStruct.OF_Close pos = Trade.objects.filter(broker=self.__broker, strategy=self.__strategy, code=sig.code, shares=sig.volume, close_time__isnull=True).first() param_dict['Direction'] = ApiStruct.D_Sell if pos.direction == DirectionType.values[DirectionType.LONG] else ApiStruct.D_Buy if pos.open_time.astimezone().date() == timezone.localtime().date() and pos.instrument.exchange == ExchangeType.SHFE: param_dict['CombOffsetFlag'] = ApiStruct.OF_CloseToday # logger.info(f'{sig.code}->{sig.instrument.main_code} {pos.direction}{sig.volume} : {sig.price}') case SignalType.ROLL_OPEN: param_dict['CombOffsetFlag'] = ApiStruct.OF_Open pos = Trade.objects.filter( Q(close_time__isnull=True) | Q(close_time__date__gte=timezone.localtime().now().date()), broker=self.__broker, strategy=self.__strategy, code=sig.instrument.last_main, shares=sig.volume).first() param_dict['Direction'] = ApiStruct.D_Buy if pos.direction == DirectionType.values[DirectionType.LONG] else ApiStruct.D_Sell logger.info(f'{pos.code}->{sig.code} {pos.direction}{sig.volume} : {sig.price}') self.raw_redis.publish(self.__request_format.format('ReqOrderInsert'), json.dumps(param_dict)) except Exception as e: logger.warning(f'ReqOrderInsert : {repr(e)}', exc_info=True) async def cancel_order(self, order: dict): sub_client = None channel_rsp_odr_act, channel_rsp_err = None, None try: sub_client = self.redis_client.pubsub(ignore_subscribe_messages=True) request_id = get_next_id() order['RequestID'] = request_id channel_rtn_odr = self.__trade_response_format.format('OnRtnOrder', order['OrderRef']) channel_rsp_odr_act = self.__trade_response_format.format('OnRspOrderAction', 0) channel_rsp_err = self.__trade_response_format.format('OnRspError', request_id) await sub_client.psubscribe(channel_rtn_odr, channel_rsp_odr_act, channel_rsp_err) task = asyncio.create_task(self.query_reader(sub_client)) self.raw_redis.publish(self.__request_format.format('ReqOrderAction'), json.dumps(order)) await asyncio.wait_for(task, HANDLER_TIME_OUT) await sub_client.punsubscribe() await sub_client.close() result = task.result()[0] if 'ErrorID' in result: logger.warning(f": {ctp_errors[result['ErrorID']]}") return False return True except Exception as e: logger.warning('cancel_order : %s', repr(e), exc_info=True) if sub_client and sub_client.in_pubsub and channel_rsp_odr_act: await sub_client.unsubscribe() await sub_client.close() return False @RegisterCallback(channel='MSG:CTP:RSP:MARKET:OnRtnDepthMarketData:*') async def OnRtnDepthMarketData(self, channel, tick: dict): try: inst = channel.split(':')[-1] tick['UpdateTime'] = datetime.datetime.strptime(tick['UpdateTime'], "%Y%m%d %H:%M:%S:%f") logger.debug('inst=%s, tick: %s', inst, tick) except Exception as ee: logger.warning('OnRtnDepthMarketData : %s', repr(ee), exc_info=True) @staticmethod def get_trade_string(trade: dict) -> str: if trade['OffsetFlag'] == OffsetFlag.Open: open_direct = DirectionType.values[trade['Direction']] else: open_direct = DirectionType.values[DirectionType.LONG] if trade['Direction'] == DirectionType.SHORT else DirectionType.values[DirectionType.SHORT] return f"{trade['ExchangeID']}.{trade['InstrumentID']} {OffsetFlag.values[trade['OffsetFlag']]}{open_direct}{trade['Volume']} " \ f":{trade['Price']} :{trade['TradeTime']} : {trade['OrderRef']}" @RegisterCallback(channel='MSG:CTP:RSP:TRADE:OnRtnTrade:*') async def OnRtnTrade(self, channel, trade: dict): try: signal = None new_trade = False trade_completed = False order_ref: str = channel.split(':')[-1] manual_trade = int(order_ref) < 10000 if not manual_trade: signal = Signal.objects.get(id=int(order_ref[ORDER_REF_SIGNAL_ID_START:])) logger.info(f": {self.get_trade_string(trade)}") inst = Instrument.objects.get(product_code=self.__re_extract_code.match(trade['InstrumentID']).group(1)) order = Order.objects.filter(order_ref=order_ref, code=trade['InstrumentID']).order_by('-send_time').first() trade_cost = trade['Volume'] * Decimal(trade['Price']) * inst.fee_money * inst.volume_multiple + trade['Volume'] * inst.fee_volume trade_margin = trade['Volume'] * Decimal(trade['Price']) * inst.margin_rate now = timezone.localtime() trade_time = timezone.make_aware(datetime.datetime.strptime(trade['TradeDate'] + trade['TradeTime'], '%Y%m%d%H:%M:%S')) if trade_time.date() > now.date(): trade_time.replace(year=now.year, month=now.month, day=now.day) if trade['OffsetFlag'] == OffsetFlag.Open: # last_trade = Trade.objects.filter( broker=self.__broker, strategy=self.__strategy, instrument=inst, code=trade['InstrumentID'], open_time__lte=trade_time, close_time__isnull=True, direction=DirectionType.values[trade['Direction']]).first() if manual_trade else Trade.objects.filter(open_order=order).first() # print(connection.queries[-1]['sql']) if last_trade is None: new_trade = True last_trade = Trade.objects.create( broker=self.__broker, strategy=self.__strategy, instrument=inst, code=trade['InstrumentID'], open_order=order if order else None, direction=DirectionType.values[trade['Direction']], open_time=trade_time, shares=order.volume if order else trade['Volume'], cost=trade_cost, filled_shares=trade['Volume'], avg_entry_price=trade['Price'], frozen_margin=trade_margin) if order is None or order.status == OrderStatus.values[OrderStatus.AllTraded]: trade_completed = True if (not new_trade and not manual_trade) or (trade_completed and not new_trade and manual_trade): last_trade.avg_entry_price = (last_trade.avg_entry_price * last_trade.filled_shares + trade['Volume'] * Decimal(trade['Price'])) / \ (last_trade.filled_shares + trade['Volume']) last_trade.filled_shares += trade['Volume'] if trade_completed and not new_trade and manual_trade: last_trade.shares += trade['Volume'] last_trade.cost += trade_cost last_trade.frozen_margin += trade_margin last_trade.save() else: # open_direct = DirectionType.values[DirectionType.LONG] if trade['Direction'] == DirectionType.SHORT else DirectionType.values[DirectionType.SHORT] last_trade = Trade.objects.filter(Q(closed_shares__isnull=True) | Q(closed_shares__lt=F('shares')), shares=F('filled_shares'), broker=self.__broker, strategy=self.__strategy, instrument=inst, code=trade['InstrumentID'], direction=open_direct).first() # print(connection.queries[-1]['sql']) logger.debug(f'trade={last_trade}') if last_trade: if last_trade.closed_shares and last_trade.avg_exit_price: last_trade.avg_exit_price = (last_trade.avg_exit_price * last_trade.closed_shares + trade['Volume'] * Decimal(trade['Price'])) / \ (last_trade.closed_shares + trade['Volume']) last_trade.closed_shares += trade['Volume'] else: last_trade.avg_exit_price = trade['Volume'] * Decimal(trade['Price']) / trade['Volume'] last_trade.closed_shares = trade['Volume'] last_trade.cost += trade_cost last_trade.close_order = order if last_trade.closed_shares == last_trade.shares: # trade_completed = True last_trade.close_time = trade_time if last_trade.direction == DirectionType.values[DirectionType.LONG]: profit_point = last_trade.avg_exit_price - last_trade.avg_entry_price else: profit_point = last_trade.avg_entry_price - last_trade.avg_exit_price last_trade.profit = profit_point * last_trade.shares * inst.volume_multiple last_trade.save(force_update=True) logger.debug(f"new_trade:{new_trade} manual_trade:{manual_trade} trade_completed:{trade_completed} " f"order:{order} signal: {signal}") if trade_completed and not manual_trade: signal.processed = True signal.save(update_fields=['processed']) order.signal = signal order.save(update_fields=['signal']) except Exception as ee: logger.warning(f'OnRtnTrade : {repr(ee)}', exc_info=True) @staticmethod def save_order(order: dict): try: if int(order['OrderRef']) < 10000: # return None, None signal = Signal.objects.get(id=int(order['OrderRef'][ORDER_REF_SIGNAL_ID_START:])) odr, created = Order.objects.update_or_create( code=order['InstrumentID'], order_ref=order['OrderRef'], defaults={ 'broker': signal.strategy.broker, 'strategy': signal.strategy, 'instrument': signal.instrument, 'front': order['FrontID'], 'session': order['SessionID'], 'price': order['LimitPrice'], 'volume': order['VolumeTotalOriginal'], 'direction': DirectionType.values[order['Direction']], 'status': OrderStatus.values[order['OrderStatus']], 'offset_flag': CombOffsetFlag.values[order['CombOffsetFlag']], 'update_time': timezone.localtime(), 'send_time': timezone.make_aware(datetime.datetime.strptime(order['InsertDate'] + order['InsertTime'], '%Y%m%d%H:%M:%S'))}) if order['OrderStatus'] == ApiStruct.OST_Canceled: # odr.delete() return None, None now = timezone.localtime().date() if created and odr.send_time.date() > timezone.localtime().date(): # odr.send_time.replace(year=now.year, month=now.month, day=now.day) odr.save(update_fields=['send_time']) odr.signal = signal return odr, created except Exception as ee: logger.warning(f'save_order : {repr(ee)}', exc_info=True) return None, None @staticmethod def get_order_string(order: dict) -> str: off_set_flag = CombOffsetFlag.values[order['CombOffsetFlag']] if order['CombOffsetFlag'] in CombOffsetFlag.values else \ OffsetFlag.values[order['CombOffsetFlag']] order_str = f":{order['OrderRef']},{order['ExchangeID']}.{order['InstrumentID']} {off_set_flag}{DirectionType.values[order['Direction']]}" \ f"{order['VolumeTotalOriginal']} :{order['LimitPrice']} :{order['InsertTime']} " \ f":{OrderSubmitStatus.values[order['OrderSubmitStatus']]} " if order['OrderStatus'] != OrderStatus.Unknown: order_str += f":{OrderStatus.values[order['OrderStatus']]} :{order['StatusMsg']} " if order['OrderStatus'] == OrderStatus.PartTradedQueueing: order_str += f":{order['VolumeTraded']} :{order['VolumeTotal']}" return order_str @RegisterCallback(channel='MSG:CTP:RSP:TRADE:OnRtnOrder:*') async def OnRtnOrder(self, _: str, order: dict): try: if order["OrderSysID"]: logger.debug(f": {self.get_order_string(order)}") order_obj, _ = self.save_order(order) if not order_obj: return signal = order_obj.signal inst = Instrument.objects.get(product_code=self.__re_extract_code.match(order['InstrumentID']).group(1)) # 50% if order['OrderStatus'] == OrderStatus.Canceled and order['OrderSubmitStatus'] == OrderSubmitStatus.InsertRejected: last_bar = DailyBar.objects.filter(exchange=inst.exchange, code=order['InstrumentID']).order_by('-time').first() volume = int(order['VolumeTotalOriginal']) price = Decimal(order['LimitPrice']) if order['CombOffsetFlag'] == CombOffsetFlag.Open: if order['Direction'] == DirectionType.LONG: delta = (price - last_bar.settlement) * Decimal(0.5) price = price_round(last_bar.settlement + delta, inst.price_tick) if delta / last_bar.settlement < 0.01: logger.warning(f"{inst} : {price} !") return logger.info(f"{inst} {price} {volume} ...") signal.price = price self.io_loop.call_soon(self.ReqOrderInsert, signal) else: delta = (last_bar.settlement - price) * Decimal(0.5) price = price_round(last_bar.settlement - delta, inst.price_tick) if delta / last_bar.settlement < 0.01: logger.warning(f"{inst} : {price} !") return logger.info(f"{inst} {price} {volume} ...") signal.price = price self.io_loop.call_soon(self.ReqOrderInsert, signal) else: if order['Direction'] == DirectionType.LONG: delta = (price - last_bar.settlement) * Decimal(0.5) price = price_round(last_bar.settlement + delta, inst.price_tick) if delta / last_bar.settlement < 0.01: logger.warning(f"{inst} : {price} !") return logger.info(f"{inst} {price} {volume} ...") signal.price = price self.io_loop.call_soon(self.ReqOrderInsert, signal) else: delta = (last_bar.settlement - price) * Decimal(0.5) price = price_round(last_bar.settlement - delta, inst.price_tick) if delta / last_bar.settlement < 0.01: logger.warning(f"{inst} : {price} !") return logger.info(f"{inst} {price} {volume} ...") signal.price = price self.io_loop.call_soon(self.ReqOrderInsert, signal) except Exception as ee: logger.warning(f'OnRtnOrder : {repr(ee)}', exc_info=True) @RegisterCallback(crontab='*/1 * * * *') async def heartbeat(self): self.raw_redis.set('HEARTBEAT:TRADER', 1, ex=301) @RegisterCallback(crontab='55 8 * * *') async def processing_signal1(self): await asyncio.sleep(5) day = timezone.localtime() _, trading = await is_trading_day(day) if trading: logger.debug('..') for sig in Signal.objects.filter(~Q(instrument__exchange=ExchangeType.CFFEX), trigger_time__gte=self.__last_trading_day, strategy=self.__strategy, instrument__night_trade=False, processed=False).order_by('-priority'): logger.info(f': {sig}') self.io_loop.call_soon(self.ReqOrderInsert, sig) if (self.__trading_day - self.__last_trading_day).days > 3: logger.info(f'.') self.io_loop.call_soon(asyncio.create_task, self.processing_signal3()) @RegisterCallback(crontab='1 9 * * *') async def check_signal1_processed(self): day = timezone.localtime() _, trading = await is_trading_day(day) if trading: logger.debug('..') for sig in Signal.objects.filter(~Q(instrument__exchange=ExchangeType.CFFEX), trigger_time__gte=self.__last_trading_day, strategy=self.__strategy, instrument__night_trade=False, processed=False).order_by('-priority'): logger.info(f': {sig}') self.io_loop.call_soon(self.ReqOrderInsert, sig) @RegisterCallback(crontab='25 9 * * *') async def processing_signal2(self): await asyncio.sleep(5) day = timezone.localtime() _, trading = await is_trading_day(day) if trading: logger.debug('..') for sig in Signal.objects.filter(instrument__exchange=ExchangeType.CFFEX, trigger_time__gte=self.__last_trading_day, strategy=self.__strategy, instrument__night_trade=False, processed=False).order_by('-priority'): logger.info(f': {sig}') self.io_loop.call_soon(self.ReqOrderInsert, sig) @RegisterCallback(crontab='31 9 * * *') async def check_signal2_processed(self): day = timezone.localtime() _, trading = await is_trading_day(day) if trading: logger.debug('..') for sig in Signal.objects.filter(instrument__exchange=ExchangeType.CFFEX, trigger_time__gte=self.__last_trading_day, strategy=self.__strategy, instrument__night_trade=False, processed=False).order_by('-priority'): logger.info(f': {sig}') self.io_loop.call_soon(self.ReqOrderInsert, sig) @RegisterCallback(crontab='55 20 * * *') async def processing_signal3(self): await asyncio.sleep(5) day = timezone.localtime() _, trading = await is_trading_day(day) if trading: logger.debug('..') for sig in Signal.objects.filter( trigger_time__gte=self.__last_trading_day, strategy=self.__strategy, instrument__night_trade=True, processed=False).order_by('-priority'): logger.info(f': {sig}') self.io_loop.call_soon(self.ReqOrderInsert, sig) @RegisterCallback(crontab='1 21 * * *') async def check_signal3_processed(self): day = timezone.localtime() _, trading = await is_trading_day(day) if trading: logger.debug('..') for sig in Signal.objects.filter( trigger_time__gte=self.__last_trading_day, strategy=self.__strategy, instrument__night_trade=True, processed=False).order_by('-priority'): logger.info(f': {sig}') self.io_loop.call_soon(self.ReqOrderInsert, sig) @RegisterCallback(crontab='20 15 * * *') async def refresh_all(self): day = timezone.localtime() _, trading = await is_trading_day(day) if not trading: logger.info(', ') return await self.refresh_account() await self.refresh_position() await self.refresh_instrument() logger.debug('!') @RegisterCallback(crontab='30 15 * * *') async def update_equity(self): today, trading = await is_trading_day(timezone.localtime()) if trading: dividend = Performance.objects.filter( broker=self.__broker, day__lt=today.date()).aggregate(Sum('dividend'))['dividend__sum'] if dividend is None: dividend = Decimal(0) dividend = dividend + self.__deposit - self.__withdraw # =()-+ self.__fake = self.__fake - self.__deposit + self.__withdraw if self.__fake < 1: self.__fake = 0 self.__broker.fake = self.__fake self.__broker.save(update_fields=['fake']) unit = dividend + self.__fake nav = (self.__current + self.__fake) / unit # accumulated = self.__current / (unit - self.__fake) # Performance.objects.update_or_create(broker=self.__broker, day=today.date(), defaults={ 'used_margin': self.__margin, 'dividend': self.__deposit - self.__withdraw, 'fake': self.__fake, 'capital': self.__current, 'unit_count': unit, 'NAV': nav, 'accumulated': accumulated}) logger.info(f": {self.__current:,.0f}({self.__current/10000:.1f}) " f": {self.__pre_balance:,.0f}({self.__pre_balance/10000:.1f}) " f": {self.__cash:,.0f}({self.__cash/10000:.1f}) " f": {self.__margin:,.0f}({self.__margin/10000:.1f}) " f": {self.__fake:,.0f}({self.__fake/10000:.1f}) : {self.__deposit:,.0f} " f": {self.__withdraw:,.0f} : {nav:,.2f} : {accumulated:,.2f}") @RegisterCallback(crontab='0 17 * * *') async def collect_quote(self, tasks=None): try: day = timezone.localtime() _, trading = await is_trading_day(day) if not trading: logger.info(', ') return logger.debug(f'{day},..') if tasks is None: tasks = [update_from_shfe, update_from_dce, update_from_czce, update_from_cffex, update_from_gfex, get_contracts_argument] result = await asyncio.gather(*[func(day) for func in tasks], return_exceptions=True) if all(result): self.io_loop.call_soon(self.calculate, day) else: failed_tasks = [tasks[i] for i, rst in enumerate(result) if not rst] self.io_loop.call_later(10*60, asyncio.create_task, self.collect_quote(failed_tasks)) except Exception as e: logger.warning(f'collect_quote : {repr(e)}', exc_info=True) logger.debug('!') def calculate(self, day, create_main_bar=True): try: p_code_set = set(self.__inst_ids) for code in self.__cur_pos.keys(): p_code_set.add(self.__re_extract_code.match(code).group(1)) all_margin = 0 for inst in Instrument.objects.all().order_by('section', 'exchange', 'name'): if create_main_bar: logger.debug(f': {inst.name}') calc_main_inst(inst, day) if inst.product_code in p_code_set: logger.debug(f': {inst.name}') sig, margin = self.calc_signal(inst, day) all_margin += margin if (all_margin + self.__margin) / self.__current > 0.8: logger.info(f": {all_margin:.0f}({all_margin/10000:.1f}) " f": {100 * (all_margin + self.__margin) / self.__current:.0f}% ") except Exception as e: logger.warning(f'calculate : {repr(e)}', exc_info=True) def calc_signal(self, inst: Instrument, day: datetime.datetime) -> (Signal, Decimal): try: break_n = self.__strategy.param_set.get(code='BreakPeriod').int_value atr_n = self.__strategy.param_set.get(code='AtrPeriod').int_value long_n = self.__strategy.param_set.get(code='LongPeriod').int_value short_n = self.__strategy.param_set.get(code='ShortPeriod').int_value stop_n = self.__strategy.param_set.get(code='StopLoss').int_value risk = self.__strategy.param_set.get(code='Risk').float_value # 400 df = to_df(MainBar.objects.filter(time__lte=day.date(), exchange=inst.exchange, product_code=inst.product_code).order_by('-time').values_list( 'time', 'open', 'high', 'low', 'close')[:400], index_col='time', parse_dates=['time']) df = df.iloc[::-1] # df["atr"] = ATR(df.high, df.low, df.close, timeperiod=atr_n) df["short_trend"] = df.close df["long_trend"] = df.close for idx in range(1, df.shape[0]): # SMA df.short_trend[idx] = (df.short_trend[idx-1] * (short_n - 1) + df.close[idx]) / short_n df.long_trend[idx] = (df.long_trend[idx-1] * (long_n - 1) + df.close[idx]) / long_n df["high_line"] = df.close.rolling(window=break_n).max() df["low_line"] = df.close.rolling(window=break_n).min() idx = -1 buy_sig = df.short_trend[idx] > df.long_trend[idx] and price_round(df.close[idx], inst.price_tick) >= price_round(df.high_line[idx - 1], inst.price_tick) sell_sig = df.short_trend[idx] < df.long_trend[idx] and price_round(df.close[idx], inst.price_tick) <= price_round(df.low_line[idx - 1], inst.price_tick) pos = Trade.objects.filter(close_time__isnull=True, broker=self.__broker, strategy=self.__strategy, instrument=inst, shares__gt=0).first() roll_over = False if pos: roll_over = pos.code != inst.main_code and pos.code < inst.main_code elif self.__strategy.force_opens.filter(id=inst.id).exists() and not buy_sig and not sell_sig: logger.info(f': {inst}') if df.short_trend[idx] > df.long_trend[idx]: buy_sig = True else: sell_sig = True self.__strategy.force_opens.remove(inst) signal = signal_code = price = volume = volume_ori = use_margin = None priority = PriorityType.LOW if pos: # if pos.direction == DirectionType.values[DirectionType.LONG]: first_pos = pos while hasattr(first_pos, 'open_order') and first_pos.open_order and first_pos.open_order.signal and first_pos.open_order.signal.type == \ SignalType.ROLL_OPEN: last_pos = Trade.objects.filter( close_order__signal__type=SignalType.ROLL_CLOSE, instrument=first_pos.instrument, strategy=first_pos.strategy, shares=first_pos.shares, direction=first_pos.direction, close_time__date=first_pos.open_time.date()).first() if last_pos is None: break logger.debug(f":{last_pos} : {last_pos.open_time}") first_pos = last_pos pos_idx = df.index.get_loc(first_pos.open_time.astimezone().date().isoformat()) # if df.close[idx] <= df.high[pos_idx:idx].max() - df.atr[pos_idx - 1] * stop_n: signal = SignalType.SELL signal_code = pos.code volume = pos.shares last_bar = DailyBar.objects.filter(exchange=inst.exchange, code=pos.code, time=day.date()).first() price = self.calc_down_limit(inst, last_bar) priority = PriorityType.High # elif roll_over: signal = SignalType.ROLL_OPEN volume = pos.shares last_bar = DailyBar.objects.filter(exchange=inst.exchange, code=pos.code, time=day.date()).first() new_bar = DailyBar.objects.filter(exchange=inst.exchange, code=inst.main_code, time=day.date()).first() price = self.calc_up_limit(inst, new_bar) priority = PriorityType.Normal Signal.objects.update_or_create( code=pos.code, strategy=self.__strategy, instrument=inst, type=SignalType.ROLL_CLOSE, trigger_time=day, defaults={'price': self.calc_down_limit(inst, last_bar), 'volume': volume, 'priority': priority, 'processed': False}) # else: first_pos = pos while hasattr(first_pos, 'open_order') and first_pos.open_order and first_pos.open_order.signal \ and first_pos.open_order.signal.type == SignalType.ROLL_OPEN: last_pos = Trade.objects.filter( close_order__signal__type=SignalType.ROLL_CLOSE, instrument=first_pos.instrument, strategy=first_pos.strategy, shares=first_pos.shares, direction=first_pos.direction,close_time__date=first_pos.open_time.date()).first() if last_pos is None: break logger.debug(f":{last_pos} : {last_pos.open_time}") first_pos = last_pos pos_idx = df.index.get_loc(first_pos.open_time.astimezone().date().isoformat()) # if df.close[idx] >= df.low[pos_idx:idx].min() + df.atr[pos_idx - 1] * stop_n: signal = SignalType.BUY_COVER signal_code = pos.code volume = pos.shares last_bar = DailyBar.objects.filter(exchange=inst.exchange, code=pos.code, time=day.date()).first() price = self.calc_up_limit(inst, last_bar) priority = PriorityType.High # elif roll_over: signal = SignalType.ROLL_OPEN volume = pos.shares last_bar = DailyBar.objects.filter(exchange=inst.exchange, code=pos.code, time=day.date()).first() new_bar = DailyBar.objects.filter(exchange=inst.exchange, code=inst.main_code, time=day.date()).first() price = self.calc_down_limit(inst, new_bar) priority = PriorityType.Normal Signal.objects.update_or_create( code=pos.code, strategy=self.__strategy, instrument=inst, type=SignalType.ROLL_CLOSE, trigger_time=day, defaults={'price': self.calc_up_limit(inst, last_bar), 'volume': volume, 'priority': priority, 'processed': False}) # elif buy_sig or sell_sig: start_cash = Performance.objects.last().unit_count # profit = Trade.objects.filter(strategy=self.__strategy, instrument__section=inst.section).aggregate(sum=Sum('profit'))['sum'] profit = profit if profit else 0 risk_each = Decimal(df.atr[idx]) * Decimal(inst.volume_multiple) volume_ori = (start_cash + profit) * risk / risk_each volume = round(volume_ori) print(f"{inst}: ({start_cash:,.0f} + {profit:,.0f}) / {risk_each:,.0f} = {volume_ori}") if volume > 0: new_bar = DailyBar.objects.filter(exchange=inst.exchange, code=inst.main_code, time=day.date()).first() use_margin = new_bar.settlement * inst.volume_multiple * inst.margin_rate * volume price = self.calc_up_limit(inst, new_bar) if buy_sig else self.calc_down_limit(inst, new_bar) signal = SignalType.BUY if buy_sig else SignalType.SELL_SHORT else: logger.info(f"{'' if buy_sig else ''}{inst},:{risk_each:.0f},") if signal: use_margin = use_margin if use_margin else 0 sig, _ = Signal.objects.update_or_create( code=signal_code if signal_code else inst.main_code,strategy=self.__strategy, instrument=inst, type=signal, trigger_time=day, defaults={'price': price, 'volume': volume, 'priority': priority, 'processed': False}) volume_ori = volume_ori if volume_ori else volume logger.info(f": {sig}({volume_ori:.1f}) " f": {use_margin:.0f}({use_margin/10000:.1f})") return signal, use_margin except Exception as e: logger.warning(f'calc_signal : {repr(e)}', exc_info=True) return None, 0 def calc_up_limit(self, inst: Instrument, bar: DailyBar): settlement = bar.settlement limit_ratio = str_to_number(self.raw_redis.get(f"LIMITRATIO:{inst.exchange}:{inst.product_code}:{bar.code}")) price_tick = inst.price_tick price = price_round(settlement * (Decimal(1) + Decimal(limit_ratio)), price_tick) return price - price_tick def calc_down_limit(self, inst: Instrument, bar: DailyBar): settlement = bar.settlement limit_ratio = str_to_number(self.raw_redis.get(f"LIMITRATIO:{inst.exchange}:{inst.product_code}:{bar.code}")) price_tick = inst.price_tick price = price_round(settlement * (Decimal(1) - Decimal(limit_ratio)), price_tick) return price + price_tick ```
/content/code_sandbox/trader/strategy/brother2.py
python
2016-07-21T09:46:31
2024-08-16T13:23:38
trader
BigBrotherTrade/trader
3,361
10,913
```json PODS: - SDCycleScrollView (1.75): - SDWebImage (>= 4.0.0) - SDWebImage (4.0.0): - SDWebImage/Core (= 4.0.0) - SDWebImage/Core (4.0.0) - WebViewJavascriptBridge (6.0.3) - YYModel (1.0.4) DEPENDENCIES: - SDCycleScrollView (~> 1.66) - SDWebImage (~> 4.0.0) - WebViewJavascriptBridge (~> 6.0.3) - YYModel SPEC REPOS: trunk: - SDCycleScrollView - SDWebImage - WebViewJavascriptBridge - YYModel SPEC CHECKSUMS: SDCycleScrollView: 884b88f0266dd4708a0e1934975c69cb971707b1 SDWebImage: 76a6348bdc74eb5a55dd08a091ef298e56b55e41 WebViewJavascriptBridge: 7f5bc4d3581e672e8f32bd0f812d54bc69bb8e29 YYModel: 2a7fdd96aaa4b86a824e26d0c517de8928c04b30 PODFILE CHECKSUM: 0623578268c8e826e1e8d8a38da0883d1ca73adb COCOAPODS: 1.10.1 ```
/content/code_sandbox/Pods/Manifest.lock
json
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
345
```objective-c // // BigShow1949Tests.m // BigShow1949Tests // // Created by WangMengqi on 15/9/1. // #import <UIKit/UIKit.h> #import <XCTest/XCTest.h> @interface BigShow1949Tests : XCTestCase @end @implementation BigShow1949Tests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // This is an example of a functional test case. XCTAssert(YES, @"Pass"); } - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ // Put the code you want to measure the time of here. }]; } @end ```
/content/code_sandbox/BigShow1949Tests/BigShow1949Tests.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
208
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIView+WebCacheOperation.h" #if SD_UIKIT || SD_MAC #import "objc/runtime.h" static char loadOperationKey; typedef NSMutableDictionary<NSString *, id> SDOperationsDictionary; @implementation UIView (WebCacheOperation) - (SDOperationsDictionary *)operationDictionary { SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); if (operations) { return operations; } operations = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); return operations; } - (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key { if (key) { [self sd_cancelImageLoadOperationWithKey:key]; if (operation) { SDOperationsDictionary *operationDictionary = [self operationDictionary]; operationDictionary[key] = operation; } } } - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key { // Cancel in progress downloader from queue SDOperationsDictionary *operationDictionary = [self operationDictionary]; id operations = operationDictionary[key]; if (operations) { if ([operations isKindOfClass:[NSArray class]]) { for (id <SDWebImageOperation> operation in operations) { if (operation) { [operation cancel]; } } } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ [(id<SDWebImageOperation>) operations cancel]; } [operationDictionary removeObjectForKey:key]; } } - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key { if (key) { SDOperationsDictionary *operationDictionary = [self operationDictionary]; [operationDictionary removeObjectForKey:key]; } } @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
437
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIButton+WebCache.h" #if SD_UIKIT #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" #import "UIView+WebCache.h" static char imageURLStorageKey; typedef NSMutableDictionary<NSNumber *, NSURL *> SDStateImageURLDictionary; @implementation UIButton (WebCache) - (nullable NSURL *)sd_currentImageURL { NSURL *url = self.imageURLStorage[@(self.state)]; if (!url) { url = self.imageURLStorage[@(UIControlStateNormal)]; } return url; } - (nullable NSURL *)sd_imageURLForState:(UIControlState)state { return self.imageURLStorage[@(state)]; } #pragma mark - Image - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { if (!url) { [self.imageURLStorage removeObjectForKey:@(state)]; return; } self.imageURLStorage[@(state)] = url; __weak typeof(self)weakSelf = self; [self sd_internalSetImageWithURL:url placeholderImage:placeholder options:options operationKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)] setImageBlock:^(UIImage *image, NSData *imageData) { [weakSelf setImage:image forState:state]; } progress:nil completed:completedBlock]; } #pragma mark - Background image - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; } - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { if (!url) { [self.imageURLStorage removeObjectForKey:@(state)]; return; } self.imageURLStorage[@(state)] = url; __weak typeof(self)weakSelf = self; [self sd_internalSetImageWithURL:url placeholderImage:placeholder options:options operationKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)] setImageBlock:^(UIImage *image, NSData *imageData) { [weakSelf setBackgroundImage:image forState:state]; } progress:nil completed:completedBlock]; } - (void)sd_setImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state { [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; } - (void)sd_cancelImageLoadForState:(UIControlState)state { [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; } - (void)sd_setBackgroundImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state { [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; } - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; } - (SDStateImageURLDictionary *)imageURLStorage { SDStateImageURLDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); if (!storage) { storage = [NSMutableDictionary dictionary]; objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return storage; } @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,362
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "NSData+ImageContentType.h" @interface UIImage (MultiFormat) + (nullable UIImage *)sd_imageWithData:(nullable NSData *)data; - (nullable NSData *)sd_imageData; - (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
121
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImageView+WebCache.h" #if SD_UIKIT || SD_MAC #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" #import "UIView+WebCache.h" @implementation UIImageView (WebCache) - (void)sd_setImageWithURL:(nullable NSURL *)url { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; } - (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; } - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_internalSetImageWithURL:url placeholderImage:placeholder options:options operationKey:nil setImageBlock:nil progress:progressBlock completed:completedBlock]; } - (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:key]; [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; } #if SD_UIKIT #pragma mark - Animation of multiple images - (void)sd_setAnimationImagesWithURLs:(nonnull NSArray<NSURL *> *)arrayOfURLs { [self sd_cancelCurrentAnimationImagesLoad]; __weak __typeof(self)wself = self; NSMutableArray<id<SDWebImageOperation>> *operationsArray = [[NSMutableArray alloc] init]; for (NSURL *logoImageURL in arrayOfURLs) { id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager loadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (!wself) return; dispatch_main_async_safe(^{ __strong UIImageView *sself = wself; [sself stopAnimating]; if (sself && image) { NSMutableArray<UIImage *> *currentImages = [[sself animationImages] mutableCopy]; if (!currentImages) { currentImages = [[NSMutableArray alloc] init]; } [currentImages addObject:image]; sself.animationImages = currentImages; [sself setNeedsLayout]; } [sself startAnimating]; }); }]; [operationsArray addObject:operation]; } [self sd_setImageLoadOperation:[operationsArray copy] forKey:@"UIImageViewAnimationImages"]; } - (void)sd_cancelCurrentAnimationImagesLoad { [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; } #endif @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
955
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageManager.h" @class SDWebImagePrefetcher; @protocol SDWebImagePrefetcherDelegate <NSObject> @optional /** * Called when an image was prefetched. * * @param imagePrefetcher The current image prefetcher * @param imageURL The image url that was prefetched * @param finishedCount The total number of images that were prefetched (successful or not) * @param totalCount The total number of images that were to be prefetched */ - (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(nullable NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; /** * Called when all images are prefetched. * @param imagePrefetcher The current image prefetcher * @param totalCount The total number of images that were prefetched (whether successful or not) * @param skippedCount The total number of images that were skipped */ - (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; @end typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); /** * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. */ @interface SDWebImagePrefetcher : NSObject /** * The web image manager */ @property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager; /** * Maximum number of URLs to prefetch at the same time. Defaults to 3. */ @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; /** * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. */ @property (nonatomic, assign) SDWebImageOptions options; /** * Queue options for Prefetcher. Defaults to Main Queue. */ @property (nonatomic, assign, nonnull) dispatch_queue_t prefetcherQueue; @property (weak, nonatomic, nullable) id <SDWebImagePrefetcherDelegate> delegate; /** * Return the global image prefetcher instance. */ + (nonnull instancetype)sharedImagePrefetcher; /** * Allows you to instantiate a prefetcher with any arbitrary image manager. */ - (nonnull instancetype)initWithImageManager:(nonnull SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list. * Any previously-running prefetch operations are canceled. * * @param urls list of URLs to prefetch */ - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls; /** * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, * currently one image is downloaded at a time, * and skips images for failed downloads and proceed to the next image in the list. * Any previously-running prefetch operations are canceled. * * @param urls list of URLs to prefetch * @param progressBlock block to be called when progress updates; * first parameter is the number of completed (successful or not) requests, * second parameter is the total number of images originally requested to be prefetched * @param completionBlock block to be called when prefetching is completed * first param is the number of completed (successful or not) requests, * second parameter is the number of skipped requests */ - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock; /** * Remove and cancel queued list */ - (void)cancelPrefetching; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
907
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIView+WebCache.h" #if SD_UIKIT || SD_MAC #import "objc/runtime.h" #import "UIView+WebCacheOperation.h" static char imageURLKey; #if SD_UIKIT static char TAG_ACTIVITY_INDICATOR; static char TAG_ACTIVITY_STYLE; #endif static char TAG_ACTIVITY_SHOW; @implementation UIView (WebCache) - (nullable NSURL *)sd_imageURL { return objc_getAssociatedObject(self, &imageURLKey); } - (void)sd_internalSetImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options operationKey:(nullable NSString *)operationKey setImageBlock:(nullable SDSetImageBlock)setImageBlock progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]); [self sd_cancelImageLoadOperationWithKey:validOperationKey]; objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); if (!(options & SDWebImageDelayPlaceholder)) { dispatch_main_async_safe(^{ [self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock]; }); } if (url) { // check if activityView is enabled or not if ([self sd_showActivityIndicatorView]) { [self sd_addActivityIndicator]; } __weak __typeof(self)wself = self; id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager loadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { __strong __typeof (wself) sself = wself; [sself sd_removeActivityIndicator]; if (!sself) { return; } dispatch_main_async_safe(^{ if (!sself) { return; } if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) { completedBlock(image, error, cacheType, url); return; } else if (image) { [sself sd_setImage:image imageData:data basedOnClassOrViaCustomSetImageBlock:setImageBlock]; [sself sd_setNeedsLayout]; } else { if ((options & SDWebImageDelayPlaceholder)) { [sself sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock]; [sself sd_setNeedsLayout]; } } if (completedBlock && finished) { completedBlock(image, error, cacheType, url); } }); }]; [self sd_setImageLoadOperation:operation forKey:validOperationKey]; } else { dispatch_main_async_safe(^{ [self sd_removeActivityIndicator]; if (completedBlock) { NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; completedBlock(nil, error, SDImageCacheTypeNone, url); } }); } } - (void)sd_cancelCurrentImageLoad { [self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])]; } - (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock { if (setImageBlock) { setImageBlock(image, imageData); return; } #if SD_UIKIT || SD_MAC if ([self isKindOfClass:[UIImageView class]]) { UIImageView *imageView = (UIImageView *)self; imageView.image = image; } #endif #if SD_UIKIT if ([self isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton *)self; [button setImage:image forState:UIControlStateNormal]; } #endif } - (void)sd_setNeedsLayout { #if SD_UIKIT [self setNeedsLayout]; #elif SD_MAC [self setNeedsLayout:YES]; #endif } #pragma mark - Activity indicator #pragma mark - #if SD_UIKIT - (UIActivityIndicatorView *)activityIndicator { return (UIActivityIndicatorView *)objc_getAssociatedObject(self, &TAG_ACTIVITY_INDICATOR); } - (void)setActivityIndicator:(UIActivityIndicatorView *)activityIndicator { objc_setAssociatedObject(self, &TAG_ACTIVITY_INDICATOR, activityIndicator, OBJC_ASSOCIATION_RETAIN); } #endif - (void)sd_setShowActivityIndicatorView:(BOOL)show { objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, @(show), OBJC_ASSOCIATION_RETAIN); } - (BOOL)sd_showActivityIndicatorView { return [objc_getAssociatedObject(self, &TAG_ACTIVITY_SHOW) boolValue]; } #if SD_UIKIT - (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style{ objc_setAssociatedObject(self, &TAG_ACTIVITY_STYLE, [NSNumber numberWithInt:style], OBJC_ASSOCIATION_RETAIN); } - (int)sd_getIndicatorStyle{ return [objc_getAssociatedObject(self, &TAG_ACTIVITY_STYLE) intValue]; } #endif - (void)sd_addActivityIndicator { #if SD_UIKIT if (!self.activityIndicator) { self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:[self sd_getIndicatorStyle]]; self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO; dispatch_main_async_safe(^{ [self addSubview:self.activityIndicator]; [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]]; [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]]; }); } dispatch_main_async_safe(^{ [self.activityIndicator startAnimating]; }); #endif } - (void)sd_removeActivityIndicator { #if SD_UIKIT if (self.activityIndicator) { [self.activityIndicator removeFromSuperview]; self.activityIndicator = nil; } #endif } @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIView+WebCache.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,406
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDownloaderOperation.h" #import "SDWebImageDecoder.h" #import "UIImage+MultiFormat.h" #import <ImageIO/ImageIO.h> #import "SDWebImageManager.h" #import "NSImage+WebCache.h" NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; NSString *const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification"; NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; NSString *const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification"; static NSString *const kProgressCallbackKey = @"progress"; static NSString *const kCompletedCallbackKey = @"completed"; typedef NSMutableDictionary<NSString *, id> SDCallbacksDictionary; @interface SDWebImageDownloaderOperation () @property (strong, nonatomic, nonnull) NSMutableArray<SDCallbacksDictionary *> *callbackBlocks; @property (assign, nonatomic, getter = isExecuting) BOOL executing; @property (assign, nonatomic, getter = isFinished) BOOL finished; @property (strong, nonatomic, nullable) NSMutableData *imageData; // This is weak because it is injected by whoever manages this session. If this gets nil-ed out, we won't be able to run // the task associated with this operation @property (weak, nonatomic, nullable) NSURLSession *unownedSession; // This is set if we're using not using an injected NSURLSession. We're responsible of invalidating this one @property (strong, nonatomic, nullable) NSURLSession *ownedSession; @property (strong, nonatomic, readwrite, nullable) NSURLSessionTask *dataTask; @property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t barrierQueue; #if SD_UIKIT @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; #endif @end @implementation SDWebImageDownloaderOperation { size_t width, height; #if SD_UIKIT || SD_WATCH UIImageOrientation orientation; #endif BOOL responseFromCached; } @synthesize executing = _executing; @synthesize finished = _finished; - (nonnull instancetype)init { return [self initWithRequest:nil inSession:nil options:0]; } - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request inSession:(nullable NSURLSession *)session options:(SDWebImageDownloaderOptions)options { if ((self = [super init])) { _request = [request copy]; _shouldDecompressImages = YES; _options = options; _callbackBlocks = [NSMutableArray new]; _executing = NO; _finished = NO; _expectedSize = 0; _unownedSession = session; responseFromCached = YES; // Initially wrong until `- URLSession:dataTask:willCacheResponse:completionHandler: is called or not called _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderOperationBarrierQueue", DISPATCH_QUEUE_CONCURRENT); } return self; } - (void)dealloc { SDDispatchQueueRelease(_barrierQueue); } - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { SDCallbacksDictionary *callbacks = [NSMutableDictionary new]; if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; dispatch_barrier_async(self.barrierQueue, ^{ [self.callbackBlocks addObject:callbacks]; }); return callbacks; } - (nullable NSArray<id> *)callbacksForKey:(NSString *)key { __block NSMutableArray<id> *callbacks = nil; dispatch_sync(self.barrierQueue, ^{ // We need to remove [NSNull null] because there might not always be a progress block for each callback callbacks = [[self.callbackBlocks valueForKey:key] mutableCopy]; [callbacks removeObjectIdenticalTo:[NSNull null]]; }); return [callbacks copy]; // strip mutability here } - (BOOL)cancel:(nullable id)token { __block BOOL shouldCancel = NO; dispatch_barrier_sync(self.barrierQueue, ^{ [self.callbackBlocks removeObjectIdenticalTo:token]; if (self.callbackBlocks.count == 0) { shouldCancel = YES; } }); if (shouldCancel) { [self cancel]; } return shouldCancel; } - (void)start { @synchronized (self) { if (self.isCancelled) { self.finished = YES; [self reset]; return; } #if SD_UIKIT Class UIApplicationClass = NSClassFromString(@"UIApplication"); BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)]; if (hasApplication && [self shouldContinueWhenAppEntersBackground]) { __weak __typeof__ (self) wself = self; UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)]; self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof (wself) sself = wself; if (sself) { [sself cancel]; [app endBackgroundTask:sself.backgroundTaskId]; sself.backgroundTaskId = UIBackgroundTaskInvalid; } }]; } #endif NSURLSession *session = self.unownedSession; if (!self.unownedSession) { NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfig.timeoutIntervalForRequest = 15; /** * Create the session for this task * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate * method calls and completion handler calls. */ self.ownedSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; session = self.ownedSession; } self.dataTask = [session dataTaskWithRequest:self.request]; self.executing = YES; } [self.dataTask resume]; if (self.dataTask) { for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { progressBlock(0, NSURLResponseUnknownLength, self.request.URL); } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; }); } else { [self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}]]; } #if SD_UIKIT Class UIApplicationClass = NSClassFromString(@"UIApplication"); if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { return; } if (self.backgroundTaskId != UIBackgroundTaskInvalid) { UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; [app endBackgroundTask:self.backgroundTaskId]; self.backgroundTaskId = UIBackgroundTaskInvalid; } #endif } - (void)cancel { @synchronized (self) { [self cancelInternal]; } } - (void)cancelInternal { if (self.isFinished) return; [super cancel]; if (self.dataTask) { [self.dataTask cancel]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; }); // As we cancelled the connection, its callback won't be called and thus won't // maintain the isFinished and isExecuting flags. if (self.isExecuting) self.executing = NO; if (!self.isFinished) self.finished = YES; } [self reset]; } - (void)done { self.finished = YES; self.executing = NO; [self reset]; } - (void)reset { dispatch_barrier_async(self.barrierQueue, ^{ [self.callbackBlocks removeAllObjects]; }); self.dataTask = nil; self.imageData = nil; if (self.ownedSession) { [self.ownedSession invalidateAndCancel]; self.ownedSession = nil; } } - (void)setFinished:(BOOL)finished { [self willChangeValueForKey:@"isFinished"]; _finished = finished; [self didChangeValueForKey:@"isFinished"]; } - (void)setExecuting:(BOOL)executing { [self willChangeValueForKey:@"isExecuting"]; _executing = executing; [self didChangeValueForKey:@"isExecuting"]; } - (BOOL)isConcurrent { return YES; } #pragma mark NSURLSessionDataDelegate - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { //'304 Not Modified' is an exceptional one if (![response respondsToSelector:@selector(statusCode)] || (((NSHTTPURLResponse *)response).statusCode < 400 && ((NSHTTPURLResponse *)response).statusCode != 304)) { NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; self.expectedSize = expected; for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { progressBlock(0, expected, self.request.URL); } self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; self.response = response; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:self]; }); } else { NSUInteger code = ((NSHTTPURLResponse *)response).statusCode; //This is the case when server returns '304 Not Modified'. It means that remote image is not changed. //In case of 304 we need just cancel the operation and return cached image from the cache. if (code == 304) { [self cancelInternal]; } else { [self.dataTask cancel]; } dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; }); [self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:((NSHTTPURLResponse *)response).statusCode userInfo:nil]]; [self done]; } if (completionHandler) { completionHandler(NSURLSessionResponseAllow); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [self.imageData appendData:data]; if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0) { // The following code is from path_to_url // Thanks to the author @Nyx0uf // Get the total bytes downloaded const NSInteger totalSize = self.imageData.length; // Update the data source, we must pass ALL the data, not just the new bytes CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)self.imageData, NULL); if (width + height == 0) { CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); if (properties) { NSInteger orientationValue = -1; CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); if (val) CFNumberGetValue(val, kCFNumberLongType, &height); val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); if (val) CFNumberGetValue(val, kCFNumberLongType, &width); val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); CFRelease(properties); // When we draw to Core Graphics, we lose orientation information, // which means the image below born of initWithCGIImage will be // oriented incorrectly sometimes. (Unlike the image born of initWithData // in didCompleteWithError.) So save it here and pass it on later. #if SD_UIKIT || SD_WATCH orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; #endif } } if (width + height > 0 && totalSize < self.expectedSize) { // Create the image CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); #if SD_UIKIT || SD_WATCH // Workaround for iOS anamorphic image if (partialImageRef) { const size_t partialHeight = CGImageGetHeight(partialImageRef); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); if (bmContext) { CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); CGImageRelease(partialImageRef); partialImageRef = CGBitmapContextCreateImage(bmContext); CGContextRelease(bmContext); } else { CGImageRelease(partialImageRef); partialImageRef = nil; } } #endif if (partialImageRef) { #if SD_UIKIT || SD_WATCH UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; #elif SD_MAC UIImage *image = [[UIImage alloc] initWithCGImage:partialImageRef size:NSZeroSize]; #endif NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; UIImage *scaledImage = [self scaledImageForKey:key image:image]; if (self.shouldDecompressImages) { image = [UIImage decodedImageWithImage:scaledImage]; } else { image = scaledImage; } CGImageRelease(partialImageRef); [self callCompletionBlocksWithImage:image imageData:nil error:nil finished:NO]; } } CFRelease(imageSource); } for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { progressBlock(self.imageData.length, self.expectedSize, self.request.URL); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { responseFromCached = NO; // If this method is called, it means the response wasn't read from cache NSCachedURLResponse *cachedResponse = proposedResponse; if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { // Prevents caching of responses cachedResponse = nil; } if (completionHandler) { completionHandler(cachedResponse); } } #pragma mark NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { @synchronized(self) { self.dataTask = nil; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; if (!error) { [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:self]; } }); } if (error) { [self callCompletionBlocksWithError:error]; } else { if ([self callbacksForKey:kCompletedCallbackKey].count > 0) { /** * See #1608 and #1623 - apparently, there is a race condition on `NSURLCache` that causes a crash * Limited the calls to `cachedResponseForRequest:` only for cases where we should ignore the cached response * and images for which responseFromCached is YES (only the ones that cannot be cached). * Note: responseFromCached is set to NO inside `willCacheResponse:`. This method doesn't get called for large images or images behind authentication */ if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached && [[NSURLCache sharedURLCache] cachedResponseForRequest:self.request]) { // hack [self callCompletionBlocksWithImage:nil imageData:nil error:nil finished:YES]; } else if (self.imageData) { UIImage *image = [UIImage sd_imageWithData:self.imageData]; NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; image = [self scaledImageForKey:key image:image]; // Do not force decoding animated GIFs if (!image.images) { if (self.shouldDecompressImages) { if (self.options & SDWebImageDownloaderScaleDownLargeImages) { #if SD_UIKIT || SD_WATCH image = [UIImage decodedAndScaledDownImageWithImage:image]; [self.imageData setData:UIImagePNGRepresentation(image)]; #endif } else { image = [UIImage decodedImageWithImage:image]; } } } if (CGSizeEqualToSize(image.size, CGSizeZero)) { [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}]]; } else { [self callCompletionBlocksWithImage:image imageData:self.imageData error:nil finished:YES]; } } else { [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Image data is nil"}]]; } } } [self done]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; __block NSURLCredential *credential = nil; if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates)) { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } else { credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; disposition = NSURLSessionAuthChallengeUseCredential; } } else { if (challenge.previousFailureCount == 0) { if (self.credential) { credential = self.credential; disposition = NSURLSessionAuthChallengeUseCredential; } else { disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; } } else { disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; } } if (completionHandler) { completionHandler(disposition, credential); } } #pragma mark Helper methods #if SD_UIKIT || SD_WATCH + (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { switch (value) { case 1: return UIImageOrientationUp; case 3: return UIImageOrientationDown; case 8: return UIImageOrientationLeft; case 6: return UIImageOrientationRight; case 2: return UIImageOrientationUpMirrored; case 4: return UIImageOrientationDownMirrored; case 5: return UIImageOrientationLeftMirrored; case 7: return UIImageOrientationRightMirrored; default: return UIImageOrientationUp; } } #endif - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image { return SDScaledImageForKey(key, image); } - (BOOL)shouldContinueWhenAppEntersBackground { return self.options & SDWebImageDownloaderContinueInBackground; } - (void)callCompletionBlocksWithError:(nullable NSError *)error { [self callCompletionBlocksWithImage:nil imageData:nil error:error finished:YES]; } - (void)callCompletionBlocksWithImage:(nullable UIImage *)image imageData:(nullable NSData *)imageData error:(nullable NSError *)error finished:(BOOL)finished { NSArray<id> *completionBlocks = [self callbacksForKey:kCompletedCallbackKey]; dispatch_main_async_safe(^{ for (SDWebImageDownloaderCompletedBlock completedBlock in completionBlocks) { completedBlock(image, imageData, error, finished); } }); } @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
4,479