text
stringlengths
2
1.04M
meta
dict
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>shuffle: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- 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="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.0 / shuffle - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> shuffle <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-15 07:12:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-15 07:12:26 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/shuffle&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Shuffle&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: Gilbreath&#39;s card trick&quot; &quot;keyword: binary sequences&quot; &quot;category: Miscellaneous/Logical Puzzles and Entertainment&quot; ] authors: [ &quot;Gérard Huet&quot; ] bug-reports: &quot;https://github.com/coq-contribs/shuffle/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/shuffle.git&quot; synopsis: &quot;Gilbreath&#39;s card trick&quot; description: &quot;&quot;&quot; A full axiomatization and proof development of a non-trivial property of binary sequences, inspired from a card trick of N. Gilbreath.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/shuffle/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=f8608e22822ddf636aa946569788a188&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-shuffle.8.9.0 coq.8.11.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.0). The following dependencies couldn&#39;t be met: - coq-shuffle -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-shuffle.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "a0d861bd9e147fd5d931a2d53096448c", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 159, "avg_line_length": 40.30177514792899, "alnum_prop": 0.5405960945529291, "repo_name": "coq-bench/coq-bench.github.io", "id": "19afcd75653afafd628cddf3b61b93c610364a2d", "size": "6837", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.11.0/shuffle/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import os import pickle import numpy as np import scipy as sp import scipy.signal as sig import pandas as pd import matplotlib.pylab as plt import matplotlib.mlab as m import statsmodels.api as sm ## Constants Fs = 200 # sampling frequency in Hz F_nyq = Fs/2 # Nyquist frequency Ts = 1./Fs # sampling period in seconds EPOCH_START = -0.2 # in seconds relative to event EPOCH_END = 0.8 # in seconds relative to event BASELINE_START = -0.2 # in seconds relative to event BASELINE_END = 0 # in seconds relative to event Neg_ErrP_START = 0.325 # in seconds relative to feedback Neg_ErrP_END = 0.435 # in seconds relative to feedback Pos_ErrP_START = 0.550 # in seconds relative to feedback Pos_ErrP_END = 0.650 # in seconds relative to feedback # Filter options N_ord = 4 # order of the filter F_lo = 0.1 # cuttof frequency in Hz F_hi = 30.0 # cuttof frequency in Hz # Design the bandpass filter (bpfilt_b, bpfilt_a) = sig.butter(N_ord, [F_lo/F_nyq, F_hi/F_nyq], btype='bandpass') def compute_trial_idxs(sessions, feedbacknos): ''' Given the numbers of sessions and trials in the sessions, gives absolute ordinal numbers of the trials. ''' trial_idxs = [] for (session, feedbackno) in zip(sessions, feedbacknos): if session == 5: trial_idxs.append(4 * 60 + feedbackno) else: trial_idxs.append((session - 1) * 60 + feedbackno) return trial_idxs def lat2idx(lats, Fs): ''' Latencies lats in seconds transformed to sample indices using sampling frequency Fs in Hz. ''' return np.array([int(lat * Fs) for lat in lats]) def idx2lat(idxs, Fs): ''' Sample indices idxs transformed to latencies in seconds using sampling frequency Fs in Hz. ''' return np.array([float(idx) / Fs for idx in idxs]) def get_epochs(x, idxs, epoch_start, epoch_end): ''' The indices and boundaries are given in samples. ''' epoched_x = x[:, np.array([idx + np.arange(epoch_start, epoch_end + 1) for idx in idxs])] epoched_x = epoched_x.transpose([0, 2, 1]) # rearranges dimensions into: channel X time X epoch return epoched_x def remove_baseline(epoched_x, epoch_start, baseline_start, baseline_end): ''' Removes the mean value of the baseline period from the trial. All the times are given in number of samples. ''' new_epoched_x = np.zeros_like(epoched_x) idx_start = baseline_start - epoch_start idx_end = baseline_end - epoch_start for i_trial in range(np.size(epoched_x, 2)): for i_ch in range(np.size(epoched_x, 0)): baseline = np.mean(epoched_x[i_ch, idx_start:idx_end, i_trial]) new_epoched_x[i_ch, :, i_trial] = epoched_x[i_ch, :, i_trial] - baseline return new_epoched_x def mean_amplitude(epoched_x, epoch_start, peak_start, peak_end): ''' Calculates mean amplitude for each channel and each trial of epoched x. Peak start and end are given in sample indices. ''' idx_start = peak_start - epoch_start idx_end = peak_end - epoch_start n_trial = np.size(epoched_x, 2) n_chan = np.size(epoched_x, 0) amps = np.zeros((n_trial, n_chan)) for i_trial in range(n_trial): for i_chan in range(n_chan): amps[i_trial, i_chan] = np.mean(epoched_x[i_chan, idx_start:idx_end, i_trial]) return amps if __name__ == '__main__': # Load trial descriptions TrainLabels = pd.read_csv('../data/TrainLabels.csv', header=0) # Add columns, for subject, session, feedback number, type of trial, Cz ERP, Neg-ErrP and Pos-ErrP amplitudes TrainLabels['Subject'] = TrainLabels['IdFeedBack'].map(lambda s : int(s[1:3])) TrainLabels['Session'] = TrainLabels['IdFeedBack'].map(lambda s : int(s[8:10])) TrainLabels['FeedbackNo'] = TrainLabels['IdFeedBack'].map(lambda s : int(s[13:])) TrainLabels['AbsTrialNum'] = compute_trial_idxs(TrainLabels['Session'], TrainLabels['FeedbackNo']) #TrainLabels['Cz ERP'] = np.nan #TrainLabels['Cz ERP'] = TrainLabels['Cz ERP'].astype(object) # change dtype to object so it can contain np arrays TrainLabels['Neg-ErrP'] = np.nan TrainLabels['Pos-ErrP'] = np.nan TrainLabels = TrainLabels[['IdFeedBack', 'Subject','Session','FeedbackNo','AbsTrialNum','Prediction','Neg-ErrP','Pos-ErrP']] # Define grouping over subjects and sessions to access datasets TrainGroups = TrainLabels.groupby(['Subject','Session']) # Go through all datasets and compute Cz ERP, Neg-ErrP and Pos-ErrP Cz_ERP = dict() test_dict = {(2,2) : range(60, 121)} for ((subject, session), rows) in TrainGroups.groups.iteritems(): #for ((subject, session), rows) in test_dict.iteritems(): # Load the dataset dataset_path = os.path.join('..', 'data', 'train', 'Data_S%02d_Sess%02d.csv') % (subject, session) print "Processing: ", dataset_path SessionData = pd.read_csv(dataset_path, header=0, usecols=['Time', 'Cz', 'EOG', 'FeedBackEvent']) # Define variables of interest t_session = SessionData['Time'] eog = SessionData['EOG'] cz = SessionData['Cz'] event_ch = SessionData['FeedBackEvent'] event_times = SessionData.Time[SessionData.FeedBackEvent == 1] # in seconds event_idxs = lat2idx(event_times, Fs) # in samples (epoch_start, epoch_end) = lat2idx((EPOCH_START, EPOCH_END), Fs) (baseline_start, baseline_end) = lat2idx((BASELINE_START, BASELINE_END), Fs) (negerrp_start, negerrp_end) = lat2idx((Neg_ErrP_START, Neg_ErrP_END), Fs) (poserrp_start, poserrp_end) = lat2idx((Pos_ErrP_START, Pos_ErrP_END), Fs) # Filter Cz and EOG eog_filt = sig.filtfilt(bpfilt_b, bpfilt_a, eog, padtype='even') cz_filt = sig.filtfilt(bpfilt_b, bpfilt_a, cz, padtype='even') # Regress EOG out of Cz mod = sm.OLS(cz_filt, eog_filt) # Describe model (Cz = beta * Eog + eps) res = mod.fit() # Fit model cz_clean = cz_filt - res.params[0] * eog_filt # Remove beta * EOG from Cz # Split Cz into epochs cz_epochs = get_epochs(cz_clean[np.newaxis], event_idxs, epoch_start, epoch_end) # Remove baseline cz_epochs_nobase = remove_baseline(cz_epochs, epoch_start, baseline_start, baseline_end) # Calculate Neg-ErrP and Pos-ErrP mean amplitude negerrp_amps = mean_amplitude(cz_epochs_nobase, epoch_start, negerrp_start, negerrp_end) poserrp_amps = mean_amplitude(cz_epochs_nobase, epoch_start, poserrp_start, poserrp_end) # Save results into table for row in rows: trial = TrainLabels.loc[row, 'FeedbackNo'] - 1; #TrainLabels.at[row, 'Cz ERP'] = cz_epochs_nobase[:, :, trial] Cz_ERP[row] = cz_epochs_nobase[:, :, trial] TrainLabels.at[row, 'Neg-ErrP'] = negerrp_amps[trial] TrainLabels.at[row, 'Pos-ErrP'] = poserrp_amps[trial] # Save the extended trial descriptions and signals results_path = os.path.join('..', 'results', 'trial_description.csv') TrainLabels.to_csv(results_path) cz_results_path = os.path.join('..', 'results', 'Cz_ERP.out') f = open(cz_results_path, 'w') pickle.dump(Cz_ERP, f) f.close()
{ "content_hash": "b3437559099c2c5b1db87261aab601ce", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 128, "avg_line_length": 39.126315789473686, "alnum_prop": 0.6320957761635728, "repo_name": "fmelinscak/error-py", "id": "2456523d42d72065a9ea50a6acfaaffed45f9861", "size": "7458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "7458" } ], "symlink_target": "" }
package com.artificial.cachereader.meta; import com.artificial.cachereader.datastream.Stream; import com.artificial.cachereader.fs.CacheSource; import java.util.Map; public class RS3ReferenceTable extends ReferenceTable { public RS3ReferenceTable(CacheSource cache, int id) { super(cache, id); } @Override protected void decode(Stream data) { this.format = data.getUByte(); if (format >= MINIMUM_FORMAT_FOR_VERSION) { this.version = data.getInt(); } this.flags = data.getUByte(); final int count = data.getReferenceTableSmart(); final int[] ids = getIds(count); for (int id : ids) { entries.put(id, new ArchiveMeta(id)); } if ((flags & FLAG_IDENTIFIERS) == FLAG_IDENTIFIERS) { for (int id : ids) { entries.get(id).setIdentifier(data.getInt()); } } for (int id : ids) { entries.get(id).setCrc(data.getInt()); } if ((flags & FLAG_UNKNOWN_2) == FLAG_UNKNOWN_2) { for (int id : ids) { int value = data.getInt(); } } if ((flags & FLAG_WHIRLPOOL) == FLAG_WHIRLPOOL) { for (int id : ids) { final byte[] rawWhirlpool = entries.get(id).getAndInitializeWhirlpool(); data.getBytes(rawWhirlpool); } } if ((flags & FLAG_UNKNOWN_1) == FLAG_UNKNOWN_1) { for (int id : ids) { int value1 = data.getInt(); int value2 = data.getInt(); } } for (int id : ids) { entries.get(id).setVersion(data.getInt()); } for (int id : ids) { int childCount = data.getReferenceTableSmart(); entries.get(id).setChildCount(childCount); } final int[][] children = new int[ids.length][]; for (int i = 0; i < ids.length; ++i) { ArchiveMeta currentEntry = getEntry(ids[i]); int childCount = currentEntry.getChildCount(); children[i] = getIds(childCount); for (int id : children[i]) { currentEntry.addChild(id); } } if ((flags & FLAG_IDENTIFIERS) == FLAG_IDENTIFIERS) { for (int i = 0; i < ids.length; ++i) { for (int childId : children[i]) { entries.get(ids[i]).getChild(childId).setIdentifier(data.getInt()); } } } } private int[] getIds(int size) { int[] ids = new int[size]; int accumulator = 0; for (int i = 0; i < ids.length; ++i) { int delta = data.getReferenceTableSmart(); accumulator += delta; ids[i] = accumulator; } return ids; } public Map<Integer, ArchiveMeta> getEntries() { return entries; } }
{ "content_hash": "21835d4fa10e367960ee0c39bd3c5182", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 88, "avg_line_length": 28.346153846153847, "alnum_prop": 0.5115332428765265, "repo_name": "ArtificialPB/DevelopmentKit", "id": "45fe9a22869490206f1b0513c5e5c33fb95ad6ec", "size": "2948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/artificial/cachereader/meta/RS3ReferenceTable.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "208818" } ], "symlink_target": "" }
%%OLAnalyzeCalTimeSeries Analyze the time series of an OLcalibration file % Description: % Analyze the time series of temperature, power fluctuation, and spectral % shift data found in an OLcalibration file % % History: % 5/31/2018 NPC Wrote it. % 6/05/2018 NPC Import calFile based on getpref('OneLightToolbox', 'OneLightCalData') % function OLAnalyzeCalTimeSeries % Provide an estimate of the comb SPD peaks combSPDNominalPeaks = [468 530 590 645]; % Load calibrations [cals, calFile] = loadCalData(); timeSeries = extractTimeSeries(cals); % Plot the time series analysis plotTimeSeries(timeSeries, calFile, combSPDNominalPeaks); end function plotTimeSeries(timeSeries, calFile, combSPDNominalPeaks) % Colors and symbols for all cals (up to 12*5 = 60 measurements) uniqueColorsNum = 12; colors = brewermap(12,'Paired'); markers = {'s', 'o', 'd', '^', '.'}; subplotPosVectors = NicePlot.getSubPlotPosVectors(... 'rowsNum', 2, ... 'colsNum', 3, ... 'heightMargin', 0.1, ... 'widthMargin', 0.035, ... 'leftMargin', 0.04, ... 'rightMargin', 0.001, ... 'bottomMargin', 0.05, ... 'topMargin', 0.05); tmp = subplotPosVectors(1,1).v; tmp(3) = tmp(3)-0.1; subplotPosVectors(1,1).v = tmp; tmp = subplotPosVectors(2,1).v; tmp(3) = tmp(3)-0.1; subplotPosVectors(2,1).v = tmp; tmp = subplotPosVectors(1,2).v; tmp(1) = tmp(1)-0.12; tmp(3) = tmp(3)+0.12; subplotPosVectors(1,2).v = tmp; tmp = subplotPosVectors(2,2).v; tmp(1) = tmp(1)-0.12; tmp(3) = tmp(3)+0.12; subplotPosVectors(2,2).v = tmp; hFig = figure(1); clf; set(hFig, 'Color', [1 1 1], ... 'Position', [10 10 1680 940], ... 'Name', sprintf('TIME SERIES ANALYSIS FOR %s', strrep(calFile, '.mat', ''))); legends = {}; % Do not show the figure as it takes a while to build up set(hFig,'visible','off'); % Find the earliest and latest time stamp for each dayTimeSeries calsNum = numel(timeSeries); for calIndex = 1:calsNum willPlotTemperatureTimeSeries = true; willPlotSpectralShiftsTimeSeries = true; willPlotPowerFluctuationTimeSeries = true; dayTimeSeries = timeSeries{calIndex}; if (isempty(dayTimeSeries.temperature)) willPlotTemperatureTimeSeries = false; end if (isempty(dayTimeSeries.spectralShiftsMeas)) fprintf(2,'There was no spectralShiftsMeas data in calibration #%d / %d\n', calIndex, calsNum); willPlotSpectralShiftsTimeSeries = false; end if (isempty(dayTimeSeries.powerFluctuationMeas)) fprintf(2,'There was no powerFluctuationMeas data in calibration #%d / %d\n', calIndex, calsNum); willPlotPowerFluctuationTimeSeries = false; end if (~willPlotPowerFluctuationTimeSeries||~willPlotSpectralShiftsTimeSeries) fprintf('No spectral shift data\n'); return; else if (willPlotTemperatureTimeSeries == false) fprintf('No temperature data in calibration #%d/%d\n', calIndex, calsNum); dayTimeSeries.temperature.t = dayTimeSeries.powerFluctuationMeas.t; dayTimeSeries.temperature.value = nan(numel(dayTimeSeries.temperature.t),2); timeSeries{calIndex} = dayTimeSeries; willPlotTemperatureTimeSeries = true; end end time0(calIndex) = min([min(dayTimeSeries.temperature.t) min(dayTimeSeries.spectralShiftsMeas.t) min(dayTimeSeries.powerFluctuationMeas.t)]); timeN(calIndex) = max([max(dayTimeSeries.temperature.t) max(dayTimeSeries.spectralShiftsMeas.t) max(dayTimeSeries.powerFluctuationMeas.t)]); end maxDuration = max(timeN-time0); % Reference SPD (SPD0) dayTimeSeries = timeSeries{1}; SPD0power = squeeze(dayTimeSeries.powerFluctuationMeas.measSpd(:,1)); SPD0comb = squeeze(dayTimeSeries.spectralShiftsMeas.measSpd(:,1)); for calIndex = 1:calsNum % Get color and symbol for this cal symbolIndex = floor((calIndex-1)/uniqueColorsNum)+1; colorIndex = mod(calIndex-1,uniqueColorsNum)+1; % Get the legend for this cal dayTimeSeries = timeSeries{calIndex}; legends{numel(legends)+1} = dayTimeSeries.date; % Plot the temperature data if (willPlotTemperatureTimeSeries) plotDayTemperatureTimeSeries(symbolIndex, colorIndex, colors, markers, dayTimeSeries.temperature.t-time0(calIndex), dayTimeSeries.temperature.value, subplotPosVectors); end if (willPlotPowerFluctuationTimeSeries) % Plot the power fluctuation data plotPowerFluctuationTimeSeries(... symbolIndex, colorIndex, colors, markers, ... dayTimeSeries.powerFluctuationMeas.t-time0(calIndex), ... dayTimeSeries.powerFluctuationMeas.measSpd, SPD0power, ... dayTimeSeries.waveAxis, subplotPosVectors); end % Plot the spectral shift data if (willPlotSpectralShiftsTimeSeries) maxCombSPD(calIndex) = max(dayTimeSeries.spectralShiftsMeas.measSpd(:)); [visualizedSpectralShiftWavelength, combSPDComputedPeaks(calIndex,:)] = ... plotSpectralShiftTimeSeries(symbolIndex, colorIndex, colors, markers, dayTimeSeries.spectralShiftsMeas.t-time0(calIndex), dayTimeSeries.spectralShiftsMeas.measSpd, SPD0comb, dayTimeSeries.waveAxis, combSPDNominalPeaks, calIndex, subplotPosVectors); end end % Show the figure now set(hFig,'visible','on'); % TEMPERATURE PLOTS % Finish OL temperature time series subplot('Position', subplotPosVectors(1,3).v); set(gca, 'XLim', [0 maxDuration/60], 'XTick', 0:10:1000, 'YTick', 1:1:100, 'YLim', [25 40]); grid on; box on; %legend(legends, 'Location', 'EastOutside'); xlabel('time (minutes)'); ylabel('temperature (deg C)'); title('OneLight internal temperature'); set(gca, 'FontSize', 14); % Finish ambient temperature time series subplot('Position', subplotPosVectors(2,3).v); set(gca, 'XLim', [0 maxDuration/60], 'XTick', 0:10:1000, 'YTick', 1:1:100, 'YLim', [25 40]); grid on; box on; %legend(legends, 'Location', 'EastOutside'); xlabel('time (minutes)'); ylabel('Temperature (deg C)'); title('Ambient temperature'); set(gca, 'FontSize', 14); % POWER FLUCTUATION PLOTS % Finish fluctuation factor time series subplot('Position', subplotPosVectors(1,2).v); set(gca, 'XLim', [0 maxDuration/60], 'XTick', 0:10:1000); grid on; box on; legend(legends, 'Location', 'WestOutside'); xlabel('time (minutes)'); ylabel('Power fluctuation factor (SPD/SPD0)'); title(sprintf('Power fluctuation with respect to the first SPD in\n''%s'.', strrep(strrep(calFile, '.mat', ''), '_', ''))); set(gca, 'FontSize', 14); % Finish Full on SPDs subplot('Position', subplotPosVectors(1,1).v); set(gca, 'XLim', [350 750], 'XTick', 200:50:800); grid on; box on; xlabel('wavelength (nm)'); ylabel('Power'); title(sprintf('Power fluctuation SPDs\n')); set(gca, 'FontSize', 14); % SPECTRAL SHIFTS PLOTS % Finish shift amount plot subplot('Position', subplotPosVectors(2,2).v); set(gca, 'XLim', [0 maxDuration/60], 'XTick', 0:10:1000); grid on; box on; legend(legends, 'Location', 'WestOutside'); xlabel('time (minutes)'); ylabel(sprintf('Spectral shift (nm)')); title(sprintf('Spectral shift (@%2.0fnm) with respect to the first SPD in\n''%s'.', visualizedSpectralShiftWavelength, strrep(strrep(calFile, '.mat', ''), '_', ''))); set(gca, 'FontSize', 14); % Finish combd SPDs subplot('Position', subplotPosVectors(2,1).v); % Plot nominal and computed peaks plot(combSPDNominalPeaks, 1.1*max(maxCombSPD(:))*ones(1,numel(combSPDNominalPeaks)), 'ks', 'MarkerSize', 14); for calIndex = 1:calsNum plot(combSPDComputedPeaks, 1.1*max(maxCombSPD(:))*ones(1,size(combSPDComputedPeaks,2)), 'k.', 'MarkerSize', 10); end set(gca, 'XLim', [350 750], 'XTick', 200:50:800); grid on; box on; xlabel('wavelength (nm)'); ylabel('Power'); title(sprintf('Spectral shifts SPDs\n')); set(gca, 'FontSize', 14); drawnow; exportPDF = false; if (exportPDF) NicePlot.exportFigToPDF('CalTimeSeriesAnalysis.pdf', hFig, 300); end end function plotDayTemperatureTimeSeries(markerIndex, colorIndex, colors, markers, time, value, subplotPosVectors) timeInMinutes = time/60; subplot('Position', subplotPosVectors(1,3).v); if (any(isnan(value(:)))) % t = text(30, 33, 'NO TEMPERATURE DATA'); % set(t, 'FontSize', 16); else hold on; plot(timeInMinutes, value(:,1), '-', ... 'Marker', markers{markerIndex}, ... 'MarkerSize', 6, ... 'Color', squeeze(colors(colorIndex,:)), ... 'MarkerFaceColor', squeeze(colors(colorIndex,:)), ... 'LineWidth', 1.5); end subplot('Position', subplotPosVectors(2,3).v); if (any(isnan(value(:)))) % t = text(30, 33, 'NO TEMPERATURE DATA'); % set(t, 'FontSize', 16); else hold on; plot(timeInMinutes, value(:,2), '-', ... 'Marker', markers{markerIndex}, ... 'MarkerSize', 6, ... 'Color', squeeze(colors(colorIndex,:)), ... 'MarkerFaceColor', squeeze(colors(colorIndex,:)), ... 'LineWidth', 1.5); end end function [visualizedSpectralShiftWavelength, combSPDComputedPeaks] = ... plotSpectralShiftTimeSeries(markerIndex, colorIndex, colors, markers, ... time, SPDs, SPD0, waveAxis, combSPDNominalPeaks, calIndex, subplotPosVectors) timeInMinutes = time/60; spectralShiftsMeasurementsNum = size(SPDs,2); % Find the reference SPD peaks [combPeakReference, gainReference] = ... findPeaks(squeeze(SPD0), ... waveAxis, ... combSPDNominalPeaks); displayedPeakIndex = 2; visualizedSpectralShiftWavelength = combPeakReference(displayedPeakIndex); % Find the SPD peaks for all measurements combPeakTimeSeries = zeros(numel(combSPDNominalPeaks), spectralShiftsMeasurementsNum); gainTimeSeries = combPeakTimeSeries; progressBarHandle = waitbar(0, sprintf('Finding spectral peaks for cal. no: %d', calIndex)); wax = findobj(progressBarHandle, 'type','axes'); tax = get(wax,'title'); set(tax,'fontsize',14) for tIndex = 1:spectralShiftsMeasurementsNum waitbar(tIndex/spectralShiftsMeasurementsNum,progressBarHandle, ... sprintf('Finding spectral peaks for cal. no %d (%d/%d)', calIndex, tIndex,spectralShiftsMeasurementsNum)); [combPeakTimeSeries(:, tIndex), gainTimeSeries(:, tIndex)] = ... findPeaks(squeeze(SPDs(:,tIndex)), ... waveAxis, ... combSPDNominalPeaks); end delete(progressBarHandle); combSPDComputedPeaks = combPeakTimeSeries(:,1); combPeakTimeSeries = bsxfun(@minus, combPeakTimeSeries, combPeakReference'); gainTimeSeries = bsxfun(@times, gainTimeSeries, 1./gainReference'); subplot('Position', subplotPosVectors(2,2).v); hold on; plot(timeInMinutes, squeeze(combPeakTimeSeries(displayedPeakIndex,:)), '-', ... 'Marker', markers{markerIndex}, ... 'MarkerSize', 6, ... 'Color', squeeze(colors(colorIndex,:)), ... 'MarkerFaceColor', squeeze(colors(colorIndex,:)), ... 'LineWidth', 1.5); subplot('Position', subplotPosVectors(2,1).v); hold on; for tIndex = 1:spectralShiftsMeasurementsNum plot(waveAxis, squeeze(SPDs(:,tIndex)), '-', ... 'Color', squeeze(colors(colorIndex,:)), ... 'MarkerFaceColor', squeeze(colors(colorIndex,:)), ... 'LineWidth', 1.5); end end function plotPowerFluctuationTimeSeries(markerIndex, colorIndex, colors, ... markers, time, SPDs, SPD0, waveAxis, subplotPosVectors) timeInMinutes = time/60; powerFluctuationMeasurementsNum = size(SPDs,2); scalar = zeros(1,powerFluctuationMeasurementsNum); for tIndex = 1:powerFluctuationMeasurementsNum scalar(tIndex) = SPD0 \ squeeze(SPDs(:,tIndex)); end subplot('Position', subplotPosVectors(1,2).v); hold on; plot(timeInMinutes, scalar, '-', ... 'Marker', markers{markerIndex}, ... 'MarkerSize', 6, ... 'Color', squeeze(colors(colorIndex,:)), ... 'MarkerFaceColor', squeeze(colors(colorIndex,:)), ... 'LineWidth', 1.5); subplot('Position', subplotPosVectors(1,1).v); hold on; for tIndex = 1:powerFluctuationMeasurementsNum plot(waveAxis, squeeze(SPDs(:,tIndex)), '-', ... 'Color', squeeze(colors(colorIndex,:)), ... 'MarkerFaceColor', squeeze(colors(colorIndex,:)), ... 'LineWidth', 1.5); end end function timeSeries = extractTimeSeries(cals) calsNum = numel(cals); fprintf('Analyzing data from %d cals\n', calsNum); timeSeries = []; for calIndex = 1:calsNum c = cals{calIndex}; timeEntry = struct(... 'date', c.describe.date, ... 'waveAxis', SToWls(c.describe.S), ... 'temperature', [], ... 'powerFluctuationMeas', [], ... 'spectralShiftsMeas', [] ... ); fprintf('[%d]: %s\n', calIndex, timeEntry.date); rawData = c.raw; if (isfield(rawData, 'temperature')) if (numel(rawData.temperature)~=1) error('Size of temperature struct is %d. Should be 1\n', numel(rawData.temperature)) end timeEntry.temperature = rawData.temperature(1); end if (isfield(rawData, 'powerFluctuationMeas')) if (numel(rawData.powerFluctuationMeas)~=1) error('Size of powerFluctuationMeas struct is %d. Should be 1\n', numel(rawData.powerFluctuationMeas)) end timeEntry.powerFluctuationMeas = rawData.powerFluctuationMeas(1); end if (isfield(rawData, 'spectralShiftsMeas')) if (numel(rawData.spectralShiftsMeas)~=1) error('Size of spectralShiftsMeas struct is %d. Should be 1\n', numel(rawData.spectralShiftsMeas)) end timeEntry.spectralShiftsMeas = rawData.spectralShiftsMeas(1); end timeSeries{numel(timeSeries)+1} = timeEntry; end end function [cals, file] = loadCalData() cals = {}; systemInfo = GetComputerInfo(); melaMaterialsDir = getpref('OneLightToolbox', 'OneLightCalData'); % if (strcmp(systemInfo.localHostName, 'Ithaca')) % melaMaterialsDir = '/Users/nicolas/Desktop/OLApproach_Squint/OneLightCalData'; % else % melaMaterialsDir = getpref('OneLightToolbox', 'OneLightCalData'); % end [file, path] = uigetfile(melaMaterialsDir, '*.mat'); calFileName = fullfile(path,file); load(calFileName, 'cals'); if isempty(cals) error('Cal file ''%s'' contained no cals structs', calFileName); end end function [combPeakTimeSeries, gainTimeSeries] = findPeaks(spd, spectralAxis, combSPDNominalPeaks) for peakIndex = 1:numel(combSPDNominalPeaks) % nominal peak peak = combSPDNominalPeaks(peakIndex); % Find exact peak dataIndicesToFit = sort(find(abs(spectralAxis - peak) <= 15)); [maxComb,idx] = max(spd(dataIndicesToFit)); peak = spectralAxis(dataIndicesToFit(idx)); refPeaks(peakIndex) = peak; % Select spectral region to fit dataIndicesToFit = sort(find(abs(spectralAxis - peak) <= 15)); dataIndicesToFit = dataIndicesToFit(find(spd(dataIndicesToFit) > 0.1*maxComb)); xData = spectralAxis(dataIndicesToFit); xDataHiRes = (xData(1):0.1:xData(end))'; initialParams = [0 5 peak 6.28 6.28 2.0]; paramLowerBounds = [0 0 peak-30 1.00 1.00 1.5]; paramUpperBounds = [0 100 peak+30 30.00 30.00 10.0]; % Fit the reference SPD peak spdData = 1000*spd(dataIndicesToFit); % in milliWatts fitParamsRef = fitGaussianToData(xData, spdData, initialParams, paramLowerBounds, paramUpperBounds); combPeakTimeSeries(peakIndex) = fitParamsRef(3); gainTimeSeries(peakIndex) = fitParamsRef(2); end % peakIndex end function solution = fitGaussianToData(xData, yData, initialParams, paramLowerBounds, paramUpperBounds) Aeq = []; beq = []; A = []; b = []; nonlcon = []; options = optimoptions('fmincon'); options = optimset('Display', 'off'); solution = fmincon(@functionToMinimize, initialParams,A, b,Aeq,beq, paramLowerBounds, paramUpperBounds, nonlcon, options); function rmsResidual = functionToMinimize(params) yfit = twoSidedExponential(xData, params); rmsResidual = sum((yfit - yData) .^2); end end function g = twoSidedExponential(wavelength, params) offset = params(1); gain = params(2); peakWavelength = params(3); leftSigmaWavelength = params(4); rightSigmaWavelength = params(5); exponent = params(6); leftIndices = find(wavelength < peakWavelength); rightIndices = find(wavelength >= peakWavelength); g1 = offset + gain*exp(-0.5*(abs((wavelength(leftIndices)-peakWavelength)/leftSigmaWavelength)).^exponent); g2 = offset + gain*exp(-0.5*(abs((wavelength(rightIndices)-peakWavelength)/rightSigmaWavelength)).^exponent); g = cat(1, g1, g2); end
{ "content_hash": "8176da8f8df244156fc66ede8698c6db", "timestamp": "", "source": "github", "line_count": 456, "max_line_length": 264, "avg_line_length": 39.291666666666664, "alnum_prop": 0.6295138695094045, "repo_name": "DavidBrainard/OneLightToolbox", "id": "7e02134f8f3f15086162b56ca085152d6519d30b", "size": "17917", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OLPrograms/OLAnalyzeCalTimeSeries.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "426205" }, { "name": "M", "bytes": "61727" }, { "name": "Makefile", "bytes": "1579" }, { "name": "Matlab", "bytes": "1052379" }, { "name": "Objective-C", "bytes": "131139" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- 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="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">8.5.dev / contrib:search-trees 8.4.dev</a></li> <li class="active"><a href="">2015-01-29 18:50:21</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:search-trees <small> 8.4.dev <span class="label label-info">Not compatible with this Coq</span> </small> </h1> <p><em><script>document.write(moment("2015-01-29 18:50:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-01-29 18:50:21 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:search-trees/coq:contrib:search-trees.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>The package is valid. </pre></dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --dry-run coq:contrib:search-trees.8.4.dev coq.8.5.dev</code></dd> <dt>Return code</dt> <dd>768</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.5.dev). The following dependencies couldn&#39;t be met: - coq:contrib:search-trees -&gt; coq &lt;= 8.4.dev+ltacprof Your request can&#39;t be satisfied: - Conflicting version constraints for coq No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --dry-run coq:contrib:search-trees.8.4.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>3 s</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - remove coq.8.5.dev === 1 to remove === =-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Removing coq.8.5.dev. [WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing The following actions will be performed: - install coq.8.4.dev [required by coq:contrib:search-trees] - install coq:contrib:search-trees.8.4.dev === 2 to install === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= =-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Building coq.8.4.dev: ./configure -configdir /home/bench/.opam/system/lib/coq/config -mandir /home/bench/.opam/system/man -docdir /home/bench/.opam/system/doc -prefix /home/bench/.opam/system -usecamlp5 -camlp5dir /home/bench/.opam/system/lib/camlp5 -coqide no make -j4 make install Installing coq.8.4.dev. Building coq:contrib:search-trees.8.4.dev: coq_makefile -f Make -o Makefile make -j4 make install Installing coq:contrib:search-trees.8.4.dev. </pre></dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "dee272acc7675e894691d77912e04697", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 240, "avg_line_length": 41.273809523809526, "alnum_prop": 0.5057686760888376, "repo_name": "coq-bench/coq-bench.github.io-old", "id": "88958138081f55eafb46aff11f74d6a439bb2440", "size": "6936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.01.0-1.2.0/unstable/8.5.dev/contrib:search-trees/8.4.dev/2015-01-29_18-50-21.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#include "Portfolio.hpp" #include <memory> using namespace apache::geode::client; using namespace testobject; const char* Portfolio::secIds[] = {"SUN", "IBM", "YHOO", "GOOG", "MSFT", "AOL", "APPL", "ORCL", "SAP", "DELL"}; Portfolio::Portfolio(int32_t i, uint32_t size, std::shared_ptr<CacheableStringArray> nm) : names(nm) { ID = i; char pkidbuf[1024]; sprintf(pkidbuf, "%d", i); pkid = CacheableString::create(pkidbuf); const char* statusStr = (i % 2 == 0) ? "active" : "inactive"; size_t statusSize = strlen(statusStr) + 1; status = new char[statusSize]; memcpy(status, statusStr, statusSize); char buf[100]; sprintf(buf, "type%d", (i % 3)); type = CacheableString::create(buf); int numSecIds = sizeof(secIds) / sizeof(char*); position1 = std::make_shared<Position>(secIds[Position::cnt % numSecIds], Position::cnt * 1000); if (i % 2 != 0) { position2 = std::make_shared<Position>(secIds[Position::cnt % numSecIds], Position::cnt * 1000); } else { position2 = nullptr; } positions = CacheableHashMap::create(); (*positions)[CacheableString::create(secIds[Position::cnt % numSecIds])] = position1; newVal = new uint8_t[size + 1]; memset(newVal, 'B', size); newVal[size] = '\0'; newValSize = size; creationDate = CacheableDate::create(); arrayNull = NULL; arrayZeroSize = NULL; } Portfolio::~Portfolio() { if (newVal != NULL) { delete[] newVal; newVal = NULL; } if (status != NULL) { delete[] status; status = NULL; } } void Portfolio::toData(DataOutput& output) const { output.writeInt(ID); output.writeObject(pkid); output.writeObject(position1); output.writeObject(position2); output.writeObject(positions); output.writeObject(type); output.writeUTF(status); output.writeObject(names); output.writeBytes(newVal, newValSize + 1); output.writeObject(creationDate); output.writeBytes(arrayNull, 0); output.writeBytes(arrayZeroSize, 0); } Serializable* Portfolio::fromData(DataInput& input) { input.readInt(&ID); input.readObject(pkid); input.readObject(position1); input.readObject(position2); input.readObject(positions); input.readObject(type); input.readUTF(&status); input.readObject(names); input.readBytes(&newVal, &newValSize); input.readObject(creationDate); int tmp = 0; input.readBytes(&arrayNull, &tmp); input.readBytes(&arrayZeroSize, &tmp); return this; } std::shared_ptr<CacheableString> Portfolio::toString() const { char idbuf[1024]; sprintf(idbuf, "PortfolioObject: [ ID=%d", ID); char pkidbuf[1024]; if (pkid != nullptr) { sprintf(pkidbuf, " status=%s type=%s pkid=%s\n", this->status, this->type->toString(), this->pkid->asChar()); } else { sprintf(pkidbuf, " status=%s type=%s pkid=%s\n", this->status, this->type->toString(), this->pkid->asChar()); } char position1buf[2048]; if (position1 != nullptr) { sprintf(position1buf, "\t\t\t P1: %s", position1->toString()->asChar()); } else { sprintf(position1buf, "\t\t\t P1: %s", "NULL"); } char position2buf[2048]; if (position2 != nullptr) { sprintf(position2buf, " P2: %s", position2->toString()->asChar()); } else { sprintf(position2buf, " P2: %s ]", "NULL"); } char creationdatebuf[2048]; if (creationDate != nullptr) { sprintf(creationdatebuf, "creation Date %s", creationDate->toString()->asChar()); } else { sprintf(creationdatebuf, "creation Date %s", "NULL"); } char stringBuf[7000]; sprintf(stringBuf, "%s%s%s%s%s", idbuf, pkidbuf, creationdatebuf, position1buf, position2buf); return CacheableString::create(stringBuf); }
{ "content_hash": "27af82bc5a1c391c5ac84c3bb1588a08", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 92, "avg_line_length": 30.414634146341463, "alnum_prop": 0.6460839347767976, "repo_name": "mhansonp/geode-native", "id": "5444b8904d6c4e635e57092caa8ee2e4e3ca0f1e", "size": "4543", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "quickstart/cpp/queryobjects/Portfolio.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1899" }, { "name": "C#", "bytes": "3515617" }, { "name": "C++", "bytes": "10771399" }, { "name": "CMake", "bytes": "107196" }, { "name": "GAP", "bytes": "73860" }, { "name": "Java", "bytes": "408387" }, { "name": "Perl", "bytes": "2704" }, { "name": "PowerShell", "bytes": "20450" }, { "name": "Shell", "bytes": "35505" } ], "symlink_target": "" }
module Admin class ReleasesController < Admin::ApplicationController # To customize the behavior of this controller, # simply overwrite any of the RESTful actions. For example: # # def index # super # @resources = Release.all.paginate(10, params[:page]) # end # Define a custom finder by overriding the `find_resource` method: # def find_resource(param) # Release.find_by!(slug: param) # end # See https://administrate-docs.herokuapp.com/customizing_controller_actions # for more information end end
{ "content_hash": "31f979dd9b05692b6752557eb9787647", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 80, "avg_line_length": 29.68421052631579, "alnum_prop": 0.6826241134751773, "repo_name": "cornelius/yes_it_shipped", "id": "3860c45310f74f4c36622af9bdfa1a591b776a17", "size": "564", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/admin/releases_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "232" }, { "name": "HTML", "bytes": "8809" }, { "name": "Haml", "bytes": "2475" }, { "name": "JavaScript", "bytes": "4369" }, { "name": "Procfile", "bytes": "39" }, { "name": "Ruby", "bytes": "62127" }, { "name": "SCSS", "bytes": "12821" } ], "symlink_target": "" }
Simple sample of a [Swift](https://swift.org) app using [Kitura](http://www.kitura.io) that runs on [Google App Engine](https://cloud.google.com/appengine). ## Run locally $ swift build $ .build/debug/MyApplication ## Deploy $ gcloud app deploy
{ "content_hash": "152f93894616f5665f063f43fd6fd402", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 156, "avg_line_length": 26.1, "alnum_prop": 0.685823754789272, "repo_name": "GoogleCloudPlatform/appengine-custom-runtimes-samples", "id": "b6baf3a6876b846208fe71ce9f7f2ad9077fe6ae", "size": "300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "swift/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2405" }, { "name": "Elixir", "bytes": "797" }, { "name": "HTML", "bytes": "757" }, { "name": "Perl", "bytes": "155" }, { "name": "Ruby", "bytes": "1985" }, { "name": "Swift", "bytes": "633" } ], "symlink_target": "" }
module Spree class OrderContents attr_accessor :order, :currency def initialize(order) @order = order end def add(variant, quantity = 1, currency = nil, shipment = nil, options = {}) line_item = add_to_line_item(variant, quantity, currency, shipment, options) reload_totals PromotionHandler::Cart.new(order, line_item).activate ItemAdjustments.new(line_item).update reload_totals line_item end def remove(variant, quantity = 1, shipment = nil, options = {}) line_item = remove_from_line_item(variant, quantity, shipment, options) reload_totals PromotionHandler::Cart.new(order, line_item).activate ItemAdjustments.new(line_item).update reload_totals line_item end def update_cart(params) if order.update_attributes(params) order.line_items = order.line_items.select { |li| li.quantity > 0 } # Update totals, then check if the order is eligible for any cart promotions. # If we do not update first, then the item total will be wrong and ItemTotal # promotion rules would not be triggered. reload_totals PromotionHandler::Cart.new(order).activate order.ensure_updated_shipments reload_totals true else false end end private def order_updater @updater ||= OrderUpdater.new(order) end def reload_totals order_updater.update_item_count order_updater.update_item_total order_updater.update_adjustment_total order_updater.update_payment_state if order.completed? order_updater.persist_totals order.reload end def add_to_line_item(variant, quantity, currency=nil, shipment=nil, options = {}) line_item = grab_line_item_by_variant(variant, false, options) if line_item line_item.target_shipment = shipment line_item.quantity += quantity.to_i line_item.currency = currency unless currency.nil? else line_item = order.line_items.new(quantity: quantity, variant: variant) line_item.target_shipment = shipment if currency line_item.currency = currency line_item.price = variant.price_in(currency).amount + variant.price_modifier_amount_in(currency, options) else line_item.price = variant.price + variant.price_modifier_amount(options) end line_item.build_options(options) if options end line_item.save line_item end def remove_from_line_item(variant, quantity, shipment=nil, options = {}) line_item = grab_line_item_by_variant(variant, true, options) line_item.quantity += -quantity line_item.target_shipment= shipment if line_item.quantity == 0 line_item.destroy else line_item.save! end line_item end def grab_line_item_by_variant(variant, raise_error = false, options = nil) line_item = order.find_line_item_by_variant(variant, options) if !line_item.present? && raise_error raise ActiveRecord::RecordNotFound, "Line item not found for variant #{variant.sku}" end line_item end end end
{ "content_hash": "ca13bb178157ce5c249a2f2b2aea4104", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 94, "avg_line_length": 31.146788990825687, "alnum_prop": 0.617378497790869, "repo_name": "tailic/spree", "id": "e1278f85dd1b1bf4c3a0e91d23f472d01ee7f817", "size": "3395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/app/models/spree/order_contents.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "88001" }, { "name": "CoffeeScript", "bytes": "31182" }, { "name": "JavaScript", "bytes": "56308" }, { "name": "Ruby", "bytes": "1616633" }, { "name": "Shell", "bytes": "1516" } ], "symlink_target": "" }
#include "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h" // Check that the ftz (flush denormals to zero) flag is reflected in PTX as // expected. namespace xla { namespace gpu { namespace { class GpuFtzTest : public GpuCodegenTest { public: explicit GpuFtzTest(bool ftz) : ftz_(ftz) {} // Creates an HLO module that performs the given binary operation on some // data. std::unique_ptr<HloModule> CreateBinaryOpModule(HloOpcode op) { HloComputation::Builder builder(TestName()); Shape param_shape = ShapeUtil::MakeShapeWithLayout( F32, /*dimensions=*/{100, 100}, /*minor_to_major=*/{1, 0}); HloInstruction* x = builder.AddInstruction(HloInstruction::CreateParameter( /* parameter_number=*/0, param_shape, "x")); HloInstruction* y = builder.AddInstruction(HloInstruction::CreateParameter( /* parameter_number=*/1, param_shape, "y")); builder.AddInstruction(HloInstruction::CreateBinary(param_shape, op, x, y)); auto hlo_module = CreateNewUnverifiedModuleWithFTZ(ftz_); hlo_module->AddEntryComputation(builder.Build()); return hlo_module; } // Creates an HLO module that performs the given unary operation on some data. std::unique_ptr<HloModule> CreateUnaryOpModule(HloOpcode op) { HloComputation::Builder builder(TestName()); Shape param_shape = ShapeUtil::MakeShapeWithLayout( F32, /*dimensions=*/{100, 100}, /*minor_to_major=*/{1, 0}); HloInstruction* x = builder.AddInstruction(HloInstruction::CreateParameter( /* parameter_number=*/0, param_shape, "x")); builder.AddInstruction(HloInstruction::CreateUnary(param_shape, op, x)); auto hlo_module = CreateNewUnverifiedModuleWithFTZ(ftz_); hlo_module->AddEntryComputation(builder.Build()); return hlo_module; } bool ftz_; }; class GpuFtzEnabledTest : public GpuFtzTest { public: GpuFtzEnabledTest() : GpuFtzTest(/*ftz=*/true) {} }; class GpuFtzDisabledTest : public GpuFtzTest { public: GpuFtzDisabledTest() : GpuFtzTest(/*ftz=*/false) {} }; // Check that we emit mul.ftz.f32 when in ftz mode, and plain mul.f32 otherwise. TEST_F(GpuFtzEnabledTest, MultiplyFtz) { CompileAndVerifyPtx(CreateBinaryOpModule(HloOpcode::kMultiply), R"( CHECK-NOT: mul.f32 CHECK: mul.ftz.f32 CHECK-NOT: mul.f32 )"); } TEST_F(GpuFtzDisabledTest, MultiplyFtz) { CompileAndVerifyPtx(CreateBinaryOpModule(HloOpcode::kMultiply), R"( CHECK-NOT: mul.ftz.f32 CHECK: mul.f32 CHECK-NOT: mul.ftz.f32 )"); } // In NVPTX, exp(float) is implemented in libdevice, and consults __nvvm_reflect // to determine whether or not ftz is enabled. The implementation uses two // calls to ex2.approx. When ftz is on, we get two calls to the ftz version; // when ftz is off, we get one call to the ftz version and one call to the // regular version. TEST_F(GpuFtzEnabledTest, ExpFtz) { CompileAndVerifyPtx(CreateUnaryOpModule(HloOpcode::kExp), R"( CHECK-NOT: ex2.approx.f32 CHECK: ex2.approx.ftz.f32 CHECK-NOT: ex2.approx.f32 CHECK: ex2.approx.ftz.f32 CHECK-NOT: ex2.approx.f32 CHECK-NOT: ex2.approx.ftz.f32 )"); } TEST_F(GpuFtzDisabledTest, ExpFtz) { CompileAndVerifyPtx(CreateUnaryOpModule(HloOpcode::kExp), R"( CHECK-NOT: ex2.approx.f32 CHECK-DAG: ex2.approx.ftz.f32 CHECK-DAG: ex2.approx.f32 CHECK-NOT: ex2.approx.f32 CHECK-NOT: ex2.approx.ftz.f32 )"); } } // namespace } // namespace gpu } // namespace xla
{ "content_hash": "2bae126090fffb0655d3dacd99e8a769", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 80, "avg_line_length": 32.716981132075475, "alnum_prop": 0.7047289504036909, "repo_name": "brchiu/tensorflow", "id": "d0ccd8619bde9ddd560989380b403efed5c5f42c", "size": "4136", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tensorflow/compiler/xla/service/gpu/tests/gpu_ftz_test.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4882" }, { "name": "Batchfile", "bytes": "10132" }, { "name": "C", "bytes": "473950" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "51674376" }, { "name": "CMake", "bytes": "199085" }, { "name": "Dockerfile", "bytes": "36908" }, { "name": "Go", "bytes": "1285435" }, { "name": "HTML", "bytes": "4680032" }, { "name": "Java", "bytes": "875500" }, { "name": "Jupyter Notebook", "bytes": "2623054" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "63390" }, { "name": "Objective-C", "bytes": "15634" }, { "name": "Objective-C++", "bytes": "101475" }, { "name": "PHP", "bytes": "5191" }, { "name": "Pascal", "bytes": "221" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "41718475" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "553" }, { "name": "Shell", "bytes": "490100" }, { "name": "Smarty", "bytes": "6976" } ], "symlink_target": "" }
package com.aspose.slides.maven.utils; import org.netbeans.api.progress.aggregate.AggregateProgressFactory; import org.netbeans.api.progress.aggregate.ProgressContributor; /** * @author Adeel Ilyas <adeel.ilyas@aspose.com> */ public abstract class AbstractTask extends Thread { /** * */ protected ProgressContributor p = null; /** * * @param id */ public AbstractTask(String id) { p = AggregateProgressFactory.createProgressContributor(id); } /** * * @return */ public ProgressContributor getProgressContributor() { return p; } }
{ "content_hash": "e6c7e4afa007a83401c08c67e86d44e4", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 68, "avg_line_length": 21.161290322580644, "alnum_prop": 0.6189024390243902, "repo_name": "ali-salman/Aspose.Slides-for-Java", "id": "13147805d1b8e0d4900e2ddb2255dce18bd401ff", "size": "656", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Plugins/Aspose.Slides Java (Maven) for NetBeans/src/com/aspose/slides/maven/utils/AbstractTask.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "25219" }, { "name": "Java", "bytes": "697904" }, { "name": "PHP", "bytes": "146397" }, { "name": "Python", "bytes": "132116" }, { "name": "Ruby", "bytes": "166824" } ], "symlink_target": "" }
import DS from 'ember-data'; import testInDebug from 'dummy/tests/helpers/test-in-debug'; import { module } from 'qunit'; module("unit/model/internal-model - Internal Model"); function MockModelFactory () { } MockModelFactory._create = function() { return { trigger() {} }; }; MockModelFactory.eachRelationship = function() { }; testInDebug("Materializing a model twice errors out", function(assert) { assert.expect(1); var internalModel = new DS.InternalModel(MockModelFactory, null, { }, null); internalModel.materializeRecord(); assert.expectAssertion(function() { internalModel.materializeRecord(); }, /more than once/); });
{ "content_hash": "ba3732504bd1405f53852adc4a70fb3b", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 78, "avg_line_length": 27.166666666666668, "alnum_prop": 0.7193251533742331, "repo_name": "danmcclain/data", "id": "04f21f4c3639dc3f354c8c6a1c9882d1c6c3cf07", "size": "652", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/unit/model/internal-model-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1680" }, { "name": "JavaScript", "bytes": "1405471" }, { "name": "Ruby", "bytes": "1139" }, { "name": "Shell", "bytes": "4920" } ], "symlink_target": "" }
module ActiveStorage # Provides the class-level DSL for declaring an Active Record model's attachments. module Attached::Model extend ActiveSupport::Concern class_methods do # Specifies the relation between a single attachment and the model. # # class User < ActiveRecord::Base # has_one_attached :avatar # end # # There is no column defined on the model side, Active Storage takes # care of the mapping between your records and the attachment. # # To avoid N+1 queries, you can include the attached blobs in your query like so: # # User.with_attached_avatar # # Under the covers, this relationship is implemented as a +has_one+ association to a # ActiveStorage::Attachment record and a +has_one-through+ association to a # ActiveStorage::Blob record. These associations are available as +avatar_attachment+ # and +avatar_blob+. But you shouldn't need to work with these associations directly in # most circumstances. # # The system has been designed to having you go through the ActiveStorage::Attached::One # proxy that provides the dynamic proxy to the associations and factory methods, like +attach+. # # If the +:dependent+ option isn't set, the attachment will be purged # (i.e. destroyed) whenever the record is destroyed. def has_one_attached(name, dependent: :purge_later) generated_association_methods.class_eval <<-CODE, __FILE__, __LINE__ + 1 def #{name} @active_storage_attached_#{name} ||= ActiveStorage::Attached::One.new("#{name}", self) end def #{name}=(attachable) attachment_changes["#{name}"] = if attachable.nil? ActiveStorage::Attached::Changes::DeleteOne.new("#{name}", self) else ActiveStorage::Attached::Changes::CreateOne.new("#{name}", self, attachable) end end CODE has_one :"#{name}_attachment", -> { where(name: name) }, class_name: "ActiveStorage::Attachment", as: :record, inverse_of: :record, dependent: :destroy has_one :"#{name}_blob", through: :"#{name}_attachment", class_name: "ActiveStorage::Blob", source: :blob scope :"with_attached_#{name}", -> { includes("#{name}_attachment": :blob) } after_save { attachment_changes[name.to_s]&.save } after_commit(on: %i[ create update ]) { attachment_changes.delete(name.to_s).try(:upload) } ActiveRecord::Reflection.add_attachment_reflection( self, name, ActiveRecord::Reflection.create(:has_one_attached, name, nil, { dependent: dependent }, self) ) end # Specifies the relation between multiple attachments and the model. # # class Gallery < ActiveRecord::Base # has_many_attached :photos # end # # There are no columns defined on the model side, Active Storage takes # care of the mapping between your records and the attachments. # # To avoid N+1 queries, you can include the attached blobs in your query like so: # # Gallery.where(user: Current.user).with_attached_photos # # Under the covers, this relationship is implemented as a +has_many+ association to a # ActiveStorage::Attachment record and a +has_many-through+ association to a # ActiveStorage::Blob record. These associations are available as +photos_attachments+ # and +photos_blobs+. But you shouldn't need to work with these associations directly in # most circumstances. # # The system has been designed to having you go through the ActiveStorage::Attached::Many # proxy that provides the dynamic proxy to the associations and factory methods, like +#attach+. # # If the +:dependent+ option isn't set, all the attachments will be purged # (i.e. destroyed) whenever the record is destroyed. def has_many_attached(name, dependent: :purge_later) generated_association_methods.class_eval <<-CODE, __FILE__, __LINE__ + 1 def #{name} @active_storage_attached_#{name} ||= ActiveStorage::Attached::Many.new("#{name}", self) end def #{name}=(attachables) if ActiveStorage.replace_on_assign_to_many attachment_changes["#{name}"] = if attachables.nil? || Array(attachables).none? ActiveStorage::Attached::Changes::DeleteMany.new("#{name}", self) else ActiveStorage::Attached::Changes::CreateMany.new("#{name}", self, attachables) end else if !attachables.nil? || Array(attachables).any? attachment_changes["#{name}"] = ActiveStorage::Attached::Changes::CreateMany.new("#{name}", self, #{name}.blobs + attachables) end end end CODE has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "ActiveStorage::Attachment", inverse_of: :record, dependent: :destroy do def purge each(&:purge) reset end def purge_later each(&:purge_later) reset end end has_many :"#{name}_blobs", through: :"#{name}_attachments", class_name: "ActiveStorage::Blob", source: :blob scope :"with_attached_#{name}", -> { includes("#{name}_attachments": :blob) } after_save { attachment_changes[name.to_s]&.save } after_commit(on: %i[ create update ]) { attachment_changes.delete(name.to_s).try(:upload) } ActiveRecord::Reflection.add_attachment_reflection( self, name, ActiveRecord::Reflection.create(:has_many_attached, name, nil, { dependent: dependent }, self) ) end end def attachment_changes #:nodoc: @attachment_changes ||= {} end def reload(*) #:nodoc: super.tap { @attachment_changes = nil } end end end
{ "content_hash": "12e3f023b48c9d3ed963d6840582cf5e", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 164, "avg_line_length": 42.26896551724138, "alnum_prop": 0.6103768967205091, "repo_name": "msaintemarie/msaintemarie.github.io", "id": "06864a846fb71a9e90d4b5cff3a60a3778e835fd", "size": "6160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/cache/ruby/2.6.0/gems/activestorage-6.0.0/lib/active_storage/attached/model.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "697688" }, { "name": "HTML", "bytes": "931801" }, { "name": "JavaScript", "bytes": "131524" }, { "name": "Ruby", "bytes": "5192" } ], "symlink_target": "" }
import colors from '../settings/colors'; export default { emptyState: { alignItems: 'center', backgroundPosition: 'center bottom', backgroundSize: 'cover', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100%', justifyContent: 'center', padding: '24px', backgroundImage: 'url()' }, heading: { fontSize: '16px', fontWeight: 'bolder', color: colors.secondaryText, margin: '0', textAlign: 'center' }, body: { fontSize: '16px', fontWeight: 'inherit', color: colors.primaryText, marginBottom: '32px', marginTop: '16px', textAlign: 'center', maxWidth: '100%' } };
{ "content_hash": "181ecd493e7acd9943a70c39df1ff8a1", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 40, "avg_line_length": 21.46875, "alnum_prop": 0.604075691411936, "repo_name": "anchorchat/anchor-ui", "id": "1b21ead2d1b62cb2891dffcd11153881a9f85f7e", "size": "687", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/empty-state/styles.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1159370" }, { "name": "Makefile", "bytes": "76" }, { "name": "Ruby", "bytes": "1238" }, { "name": "Shell", "bytes": "828" } ], "symlink_target": "" }
FROM ubuntu MAINTAINER Michael Obermueller RUN adduser jboss USER jboss RUN mkdir -p /tmp/images/mymusic # Add VOLUME as datacontainer VOLUME /tmp/images/mymusic ENTRYPOINT /usr/bin/tail -f /dev/null
{ "content_hash": "dd7962b88ae8d244783cd0036ed8492a", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 37, "avg_line_length": 17, "alnum_prop": 0.7892156862745098, "repo_name": "thi-enterprisejava/music-albums-obermueller", "id": "ccc4f23ad34aadb8006ee86562d164ba437676a0", "size": "204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/docker/filecontainer/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "62314" }, { "name": "HTML", "bytes": "34374" }, { "name": "Java", "bytes": "157066" }, { "name": "JavaScript", "bytes": "36239" } ], "symlink_target": "" }
title: 'Täname!' --- **Aitäh, et võtsite meiega ühendust!** Vastame Teile esimesel võimalusel!
{ "content_hash": "4e36ea0c53b99add2e9aaa87fe50b4c1", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 73, "avg_line_length": 24, "alnum_prop": 0.71875, "repo_name": "ottramst/marvic", "id": "8a487a5ec24e971986fe97dfbb0bc311efe8ebb8", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "user/pages/Contact/thank-you/default.md", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3034" }, { "name": "CSS", "bytes": "168663" }, { "name": "HTML", "bytes": "42757" }, { "name": "JavaScript", "bytes": "87007" }, { "name": "Logos", "bytes": "831" }, { "name": "Nginx", "bytes": "1458" }, { "name": "PHP", "bytes": "1038166" } ], "symlink_target": "" }
<?php use Siefa\CommonsBundle\Tests\Cases\CommandTestCase; class CreateUserCommandTest extends CommandTestCase { /** * @var \Siefa\SecurityBundle\Model\UserProvider */ private $userProvider; /** * {@inheritDoc} */ public function setUp() { static::$kernel = static::createKernel(); static::$kernel->boot(); $this->userProvider = static::$kernel->getContainer() ->get('siga.user_provider'); $this->roleManager = static::$kernel->getContainer()->get('siga.role_manager'); } public function testCreateUser() { $client = self::createClient(); $output = $this->runCommand($client, "siga:user:create testuser test@example.com p@ssword"); $this->assertContains('Created user', $output); $user = $this->userProvider->findUserByUsername('testuser'); $this->assertEquals('test@example.com', $user->getEmail()); $this->assertEquals(true, $user->getIsActive()); } }
{ "content_hash": "c1e97905bb887e5eeab89cf27ef36c4c", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 108, "avg_line_length": 30.11111111111111, "alnum_prop": 0.5747232472324724, "repo_name": "metalvarez/siga-pruebas-seguridad", "id": "468f4f2ce75ed69219a0d49d3dfb53267ed84906", "size": "1084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Siefa/SecurityBundle/Tests/Functional/Command/CreateUserCommandTest.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "250978" }, { "name": "JavaScript", "bytes": "595144" }, { "name": "PHP", "bytes": "316297" }, { "name": "Perl", "bytes": "3707" } ], "symlink_target": "" }
package io.clickhandler.web.reactGwt.client.react; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import io.clickhandler.web.reactGwt.client.Func; /** * */ @JsType(isNative = true) public interface ReactElement<T, P extends BaseProps> { @JsProperty T getType(); @JsProperty P getProps(); @JsProperty Object getKey(); @JsProperty Object getRef(); void setRef(Func.Call1<Object, Object> callback); }
{ "content_hash": "74e3869956cc6ff05e0879b3cfe3457d", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 55, "avg_line_length": 18.92, "alnum_prop": 0.7082452431289641, "repo_name": "ClickHandlerIO/clickhandler-web", "id": "ee7e685a6de369348f5dea7a1ac46dee808f978b", "size": "473", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/clickhandler/web/reactGwt/client/react/ReactElement.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12487" }, { "name": "HTML", "bytes": "3339" }, { "name": "Java", "bytes": "792639" }, { "name": "JavaScript", "bytes": "1913575" }, { "name": "Shell", "bytes": "3263" } ], "symlink_target": "" }
package com.deleidos.rtws.webapp.tenantapi.common; import org.apache.commons.configuration.ConversionException; import org.apache.log4j.Logger; import com.deleidos.rtws.commons.config.RtwsConfig; public final class EndpointUtil { private static Logger logger = Logger.getLogger(EndpointUtil.class); private static String storageEndpoint = null; static { try { storageEndpoint = RtwsConfig.getInstance().getString("webapp.tenantapi.storage.endpoint"); } catch (ConversionException e) { logger.warn("Load property [webapp.tenantapi.storage.endpoint] failed. This is normal on Amazon environments, but not others. Message: " + e.getMessage()); } } private EndpointUtil() { // All calls should be done through static methods } public static String getStorageEndpoint() { return storageEndpoint; } }
{ "content_hash": "de4e4812bd1cace7fab03bae63503f75", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 158, "avg_line_length": 26.125, "alnum_prop": 0.7595693779904307, "repo_name": "deleidos/digitaledge-platform", "id": "30b67d4439961291e70fc50b80058aca2ea02449", "size": "12771", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "webapp-tenantapi/src/main/java/com/deleidos/rtws/webapp/tenantapi/common/EndpointUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "16315580" }, { "name": "Batchfile", "bytes": "15678" }, { "name": "C", "bytes": "26042" }, { "name": "CSS", "bytes": "846559" }, { "name": "Groovy", "bytes": "93743" }, { "name": "HTML", "bytes": "36583222" }, { "name": "Java", "bytes": "33127586" }, { "name": "JavaScript", "bytes": "2030589" }, { "name": "Nginx", "bytes": "3934" }, { "name": "Perl", "bytes": "330290" }, { "name": "Python", "bytes": "54288" }, { "name": "Ruby", "bytes": "5133" }, { "name": "Shell", "bytes": "2482631" }, { "name": "XSLT", "bytes": "978664" } ], "symlink_target": "" }
package com.chenmed.qatests; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.LinkedList; import java.util.List; /** * Created by anastasiyam on 12/21/2016. */ public class TestSortingOfCountries { private WebDriverWait wait; private ChromeDriver driver; @Before public void setup() { //web driver is an interface driver is an object System.setProperty("webdriver.chrome.driver", "C://Windows/chromedriver.exe"); driver = new ChromeDriver(); wait = new WebDriverWait(driver, 5); } @Test public void TestSorting() { Login loginrun = new Login(driver); loginrun.enter("http://localhost/litecart/public_html/admin/login.php", "admin", "admin"); driver.findElement(By.xpath(".//li[3][@id='app-']/a/span[2]")).click(); //create an LinkedList instead of arraylist because it preserves insertion order //"ul[@id='box-apps-menu']//span[text()=Countries']" List<WebElement> countries = new LinkedList<WebElement>(); //store the products (web elements) into the linkedlist countries = driver.findElements(By.cssSelector("a[href*='?app=countries&doc=countries'].name")); //create another linked list of type string to store titles LinkedList<String> countries_names = new LinkedList<String>(); //loop through all the elements of the product_webelement list get it title and store it into the product_names list for (int i = 0; i < countries.size(); i++) { String s = countries.get(i).getAttribute("text"); product_names.add(s); if (driver.findElements(By.cssSelector("a[href*='?app=countries&doc=countries'].name td")).size()!=0); List<WebElement> zones = new LinkedList<WebElement>(); countries = driver.findElements(By.cssSelector("a[href*='?app=countries&doc=countries'].name td")); List<String> zones_names=new LinkedList<String>(); } boolean result=chkalphabetical_order(product_names); // print the result System.out.println(result); } public boolean chkalphabetical_order(List<String>product_names) { String previous = ""; // empty string for (final String current: product_names) { if (current.compareTo(previous) < 0) return false; previous = current; } return true; } @After public void stop() { driver.close(); driver = null; } }
{ "content_hash": "e225acc40024350343ff14fb062d9b9c", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 124, "avg_line_length": 28.8659793814433, "alnum_prop": 0.63, "repo_name": "nogic25/test-selenium", "id": "378a7a77621eae0308076ab1e2b3ac4546a6f2f5", "size": "2800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/chenmed/qatests/TestSortingOfCountries.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8358" } ], "symlink_target": "" }
(function(){ 'use strict'; function mdDataTableCellDirective(ColumnAlignmentHelper, $parse){ return { restrict: 'E', templateUrl: '/main/templates/mdDataTableCell.html', replace: true, transclude: true, scope: { htmlContent: '@' }, require: ['^mdDataTable','^mdDataTableRow'], link: function($scope, element, attrs, ctrl, transclude){ var mdDataTableCtrl = ctrl[0]; var mdDataTableRowCtrl = ctrl[1]; var columnIndex = mdDataTableRowCtrl.getIndex(); //TODO: refactor as the columnDirective $scope.getColumnAlignClass = ColumnAlignmentHelper.getColumnAlignClass(getColumnOptions().alignRule); transclude(function (clone) { //TODO: rework, figure out something for including html content if($scope.htmlContent){ mdDataTableRowCtrl.addToRowDataStorage(columnIndex); }else{ //TODO: better idea? var cellValue = $parse(clone.html().replace('{{', '').replace('}}', ''))($scope.$parent); mdDataTableRowCtrl.addToRowDataStorage(cellValue); } }); $scope.getCellValue = getCellValue; mdDataTableRowCtrl.increaseIndex(); function getColumnOptions(){ return mdDataTableCtrl.getColumnOptions(columnIndex); } function getCellValue(){ return mdDataTableRowCtrl.getRowDataStorageValue(columnIndex); } } }; } angular .module('mdDataTable') .directive('mdDataTableCell', mdDataTableCellDirective); }());
{ "content_hash": "31cc3ec769e0eacfdc4199da8fe66738", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 117, "avg_line_length": 36.32692307692308, "alnum_prop": 0.5267337215457915, "repo_name": "ryanhmaas/nflSiteRewrite", "id": "fa6a4f6438e41d919fae85fe2d532b87fb090ee3", "size": "1889", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "public/libs/md-data-table/app/modules/main/directives/body/mdDataTableCellDirective.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2196147" }, { "name": "HTML", "bytes": "89041" }, { "name": "JavaScript", "bytes": "490773" } ], "symlink_target": "" }
require 'spec_helper' describe Tag do describe 'validations' do it 'should require name to be present' do tag = build :tag, name: nil expect(tag.valid?).to be false expect(tag.errors).to have_key :name expect(tag.errors[:name]).to include "can't be blank" end it 'should require name to be unique' do Tag.create(name: 'videotutorials') tag = Tag.new(name: 'videotutorials') expect(tag.valid?).to be false expect(tag.errors).to have_key :name expect(tag.errors[:name]).to include "has already been taken" end it 'should require name to be at least 2 characters long' do tag = build :tag, name: "A" expect(tag.valid?).to be false expect(tag.errors).to have_key :name expect(tag.errors[:name]).to include "is too short (minimum is 2 characters)" end it 'should only allow aalphanumeric characters, _, -, + and # in tag name' do forbidden_names = ['with space', 'abc***', '$$$'] forbidden_names.each do |name| tag = build :tag, name: name expect(tag.valid?).to be false expect(tag.errors).to have_key :name expect(tag.errors[:name]).to include "is invalid" end end end end
{ "content_hash": "7b753d3e3407be5f81a0300a2a4b3e4b", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 83, "avg_line_length": 33.432432432432435, "alnum_prop": 0.6289409862570736, "repo_name": "kamilbielawski/knowledge_base", "id": "20f4dab1f8dfd7981f039e1fb3a432e8ad2cb836", "size": "1237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/tag_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "985" }, { "name": "CoffeeScript", "bytes": "9676" }, { "name": "JavaScript", "bytes": "885" }, { "name": "Ruby", "bytes": "52145" } ], "symlink_target": "" }
package main import ( "context" "fmt" "math" "net" "os" "syscall" "time" "github.com/spf13/cobra" "github.com/scionproto/scion/go/lib/daemon" "github.com/scionproto/scion/go/lib/log" "github.com/scionproto/scion/go/lib/serrors" "github.com/scionproto/scion/go/lib/snet" "github.com/scionproto/scion/go/lib/snet/addrutil" "github.com/scionproto/scion/go/lib/sock/reliable" "github.com/scionproto/scion/go/lib/tracing" "github.com/scionproto/scion/go/pkg/app" "github.com/scionproto/scion/go/pkg/app/flag" "github.com/scionproto/scion/go/pkg/app/path" "github.com/scionproto/scion/go/pkg/ping" ) func newPing(pather CommandPather) *cobra.Command { var envFlags flag.SCIONEnvironment var flags struct { count uint16 features []string interactive bool interval time.Duration logLevel string maxMTU bool noColor bool refresh bool healthyOnly bool sequence string size uint timeout time.Duration tracer string } var cmd = &cobra.Command{ Use: "ping [flags] <remote>", Short: "Test connectivity to a remote SCION host using SCMP echo packets", Example: fmt.Sprintf(` %[1]s ping 1-ff00:0:110,10.0.0.1 %[1]s ping 1-ff00:0:110,10.0.0.1 -c 5`, pather.CommandPath()), Long: fmt.Sprintf(`'ping' test connectivity to a remote SCION host using SCMP echo packets. When the --count option is set, ping sends the specified number of SCMP echo packets and reports back the statistics. When the --healthy-only option is set, ping first determines healthy paths through probing and chooses amongst them. If no reply packet is received at all, ping will exit with code 1. On other errors, ping will exit with code 2. %s`, app.SequenceHelp), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { remote, err := snet.ParseUDPAddr(args[0]) if err != nil { return serrors.WrapStr("parsing remote", err) } if err := app.SetupLog(flags.logLevel); err != nil { return serrors.WrapStr("setting up logging", err) } closer, err := setupTracer("ping", flags.tracer) if err != nil { return serrors.WrapStr("setting up tracing", err) } defer closer() cmd.SilenceUsage = true if err := envFlags.LoadExternalVars(); err != nil { return err } daemonAddr := envFlags.Daemon() dispatcher := envFlags.Dispatcher() localIP := envFlags.Local().IPAddr().IP log.Debug("Resolved SCION environment flags", "daemon", daemonAddr, "dispatcher", dispatcher, "local", localIP, ) span, traceCtx := tracing.CtxWith(context.Background(), "run") span.SetTag("dst.isd_as", remote.IA) span.SetTag("dst.host", remote.Host.IP) defer span.Finish() ctx, cancelF := context.WithTimeout(traceCtx, time.Second) defer cancelF() sd, err := daemon.NewService(daemonAddr).Connect(ctx) if err != nil { return serrors.WrapStr("connecting to SCION Daemon", err) } info, err := app.QueryASInfo(traceCtx, sd) if err != nil { return err } span.SetTag("src.isd_as", info.IA) opts := []path.Option{ path.WithInteractive(flags.interactive), path.WithRefresh(flags.refresh), path.WithSequence(flags.sequence), path.WithColorScheme(path.DefaultColorScheme(flags.noColor)), } if flags.healthyOnly { opts = append(opts, path.WithProbing(&path.ProbeConfig{ LocalIA: info.IA, LocalIP: localIP, Dispatcher: dispatcher, })) } path, err := path.Choose(traceCtx, sd, remote.IA, opts...) if err != nil { return err } remote.Path = path.Dataplane() remote.NextHop = path.UnderlayNextHop() // Resolve local IP based on underlay next hop if localIP == nil { target := remote.Host.IP if remote.NextHop != nil { target = remote.NextHop.IP } if localIP, err = addrutil.ResolveLocal(target); err != nil { return serrors.WrapStr("resolving local address", err) } fmt.Printf("Resolved local address:\n %s\n", localIP) } fmt.Printf("Using path:\n %s\n\n", path) span.SetTag("src.host", localIP) local := &snet.UDPAddr{ IA: info.IA, Host: &net.UDPAddr{IP: localIP}, } pldSize := int(flags.size) if flags.maxMTU { mtu := int(path.Metadata().MTU) pldSize, err = calcMaxPldSize(local, remote, mtu) if err != nil { return err } } pktSize, err := ping.Size(local, remote, pldSize) if err != nil { return err } fmt.Printf("PING %s pld=%dB scion_pkt=%dB\n", remote, pldSize, pktSize) start := time.Now() ctx = app.WithSignal(traceCtx, os.Interrupt, syscall.SIGTERM) count := flags.count if count == 0 { count = math.MaxUint16 } stats, err := ping.Run(ctx, ping.Config{ Dispatcher: reliable.NewDispatcher(dispatcher), Attempts: count, Interval: flags.interval, Timeout: flags.timeout, Local: local, Remote: remote, PayloadSize: int(flags.size), ErrHandler: func(err error) { fmt.Fprintf(os.Stderr, "ERROR: %s\n", err) }, UpdateHandler: func(update ping.Update) { var additional string switch update.State { case ping.AfterTimeout: additional = " state=After timeout" case ping.OutOfOrder: additional = " state=Out of Order" case ping.Duplicate: additional = " state=Duplicate" } fmt.Fprintf(os.Stdout, "%d bytes from %s,%s: scmp_seq=%d time=%s%s\n", update.Size, update.Source.IA, update.Source.Host, update.Sequence, update.RTT, additional) }, }) pingSummary(stats, remote, time.Since(start)) if err != nil { return err } if stats.Received == 0 { return app.WithExitCode(serrors.New("no reply packet received"), 1) } return nil }, } envFlags.Register(cmd.Flags()) cmd.Flags().BoolVarP(&flags.interactive, "interactive", "i", false, "interactive mode") cmd.Flags().BoolVar(&flags.noColor, "no-color", false, "disable colored output") cmd.Flags().DurationVar(&flags.timeout, "timeout", time.Second, "timeout per packet") cmd.Flags().StringVar(&flags.sequence, "sequence", "", app.SequenceUsage) cmd.Flags().BoolVar(&flags.healthyOnly, "healthy-only", false, "only use healthy paths") cmd.Flags().BoolVar(&flags.refresh, "refresh", false, "set refresh flag for path request") cmd.Flags().DurationVar(&flags.interval, "interval", time.Second, "time between packets") cmd.Flags().Uint16VarP(&flags.count, "count", "c", 0, "total number of packets to send") cmd.Flags().UintVarP(&flags.size, "payload-size", "s", 0, `number of bytes to be sent in addition to the SCION Header and SCMP echo header; the total size of the packet is still variable size due to the variable size of the SCION path.`, ) cmd.Flags().BoolVar(&flags.maxMTU, "max-mtu", false, `choose the payload size such that the sent SCION packet including the SCION Header, SCMP echo header and payload are equal to the MTU of the path. This flag overrides the 'payload_size' flag.`) cmd.Flags().StringVar(&flags.logLevel, "log.level", "", app.LogLevelUsage) cmd.Flags().StringVar(&flags.tracer, "tracing.agent", "", "Tracing agent address") return cmd } func calcMaxPldSize(local, remote *snet.UDPAddr, mtu int) (int, error) { overhead, err := ping.Size(local, remote, 0) if err != nil { return 0, err } return mtu - overhead, nil } func pingSummary(stats ping.Stats, remote *snet.UDPAddr, run time.Duration) { var pktLoss int if stats.Sent != 0 { pktLoss = 100 - stats.Received*100/stats.Sent } fmt.Printf("\n--- %s,%s statistics ---\n", remote.IA, remote.Host.IP) fmt.Printf("%d packets transmitted, %d received, %d%% packet loss, time %v\n", stats.Sent, stats.Received, pktLoss, run.Round(time.Microsecond)) }
{ "content_hash": "32926730a243844678ec1112e291d56d", "timestamp": "", "source": "github", "line_count": 243, "max_line_length": 94, "avg_line_length": 31.94238683127572, "alnum_prop": 0.6717340891522804, "repo_name": "netsec-ethz/scion", "id": "e0d42ff6369467ae7ee11d91d4fed7447cd68726", "size": "8353", "binary": false, "copies": "1", "ref": "refs/heads/scionlab", "path": "go/scion/ping.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "2254" }, { "name": "Dockerfile", "bytes": "195" }, { "name": "Go", "bytes": "11481996" }, { "name": "Lua", "bytes": "37214" }, { "name": "Makefile", "bytes": "1803" }, { "name": "Python", "bytes": "182730" }, { "name": "Ruby", "bytes": "262" }, { "name": "Shell", "bytes": "94920" }, { "name": "Starlark", "bytes": "466716" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "bce11aead3c50b4e8523457358d045a8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7a6fb988088b910912e2423c1bce5a4205d8e6de", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Bulbophyllum/Bulbophyllum dalatensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to Integrated Taxonomic Information System #### Published in Sp. pl. 2:885. 1753 #### Original name null ### Remarks null
{ "content_hash": "7111530972f54cfa9d3cea601065fc0b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.461538461538462, "alnum_prop": 0.7046979865771812, "repo_name": "mdoering/backbone", "id": "af3cdee24aee5688bc091f81b6dcb91f9eaf7e9c", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Doronicum/Doronicum pardalianches/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require 'cane/hashcheck/version' require 'cane/hashcheck/hash_check'
{ "content_hash": "d41bd8031be5dfde24b205841e117dcf", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 35, "avg_line_length": 34.5, "alnum_prop": 0.8115942028985508, "repo_name": "chrishunt/cane-hashcheck", "id": "855823334558eed1ec614793211d9903e64f5f72", "size": "69", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/cane/hashcheck.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4582" } ], "symlink_target": "" }
#ifndef THIRD_PARTY_TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_ASYNC_SERVICE_INTERFACE_H_ #define THIRD_PARTY_TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_ASYNC_SERVICE_INTERFACE_H_ namespace tensorflow { // Represents an abstract asynchronous service that handles incoming // RPCs with a polling loop. class AsyncServiceInterface { public: virtual ~AsyncServiceInterface() {} // A blocking method that should be called to handle incoming RPCs. // This method will block until the service is shutdown, which // depends on the implementation of the service. virtual void HandleRPCsLoop() = 0; // TODO(mrry): Add a clean shutdown method? }; } // namespace tensorflow #endif // THIRD_PARTY_TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_ASYNC_SERVICE_INTERFACE_H_
{ "content_hash": "e020399f5d9b9920227d0a05cccc1215", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 89, "avg_line_length": 32.041666666666664, "alnum_prop": 0.7685305591677504, "repo_name": "RyanYoung25/tensorflow", "id": "2f453b048e8349d6cdec2e4218aa83713dd645e5", "size": "1425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/core/distributed_runtime/rpc/async_service_interface.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "151630" }, { "name": "C++", "bytes": "6922849" }, { "name": "CMake", "bytes": "29325" }, { "name": "CSS", "bytes": "107" }, { "name": "HTML", "bytes": "657597" }, { "name": "Java", "bytes": "50361" }, { "name": "JavaScript", "bytes": "16175" }, { "name": "Jupyter Notebook", "bytes": "777942" }, { "name": "Objective-C", "bytes": "1288" }, { "name": "Protocol Buffer", "bytes": "89536" }, { "name": "Python", "bytes": "3835693" }, { "name": "Shell", "bytes": "66697" }, { "name": "TypeScript", "bytes": "329009" } ], "symlink_target": "" }
var emptyObject = new Object(); // equivalent to emptyObject = {};
{ "content_hash": "9309cfdca1ac9ee4e4296a61cdd1bff5", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 34, "avg_line_length": 33, "alnum_prop": 0.696969696969697, "repo_name": "kcdodd/ecsp-book", "id": "1e16b7774d39bcc67735f200f88251918609c636", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/js/newKeyword.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "142" }, { "name": "JavaScript", "bytes": "12888" }, { "name": "TeX", "bytes": "137537" } ], "symlink_target": "" }
package name.cs.csutils.collector; import java.util.concurrent.atomic.AtomicInteger; public class MaxCountCollector<T> implements Collector<T> { private final int maxcount; private AtomicInteger count = new AtomicInteger(0); private Collector<T> collector; public MaxCountCollector(int maxcount, Collector<T> collector) { this.maxcount = maxcount; this.collector = collector; } public int collect(T item) { if (count.get()>=maxcount || count.incrementAndGet()>=maxcount) { return FINISHED; } else { return collector.collect(item); } } }
{ "content_hash": "ff2202ddbd2c64009f1315ef0c2f95d7", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 73, "avg_line_length": 25.8, "alnum_prop": 0.648062015503876, "repo_name": "wesen/rw-patchmanager", "id": "de00afcd0741ecbc883e0e015949ea26c18ceb2a", "size": "2223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/name/cs/csutils/collector/MaxCountCollector.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "923076" }, { "name": "Shell", "bytes": "487" } ], "symlink_target": "" }
using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Compute.Models { public partial class UpgradeOperationHistoricalStatusInfoProperties { internal static UpgradeOperationHistoricalStatusInfoProperties DeserializeUpgradeOperationHistoricalStatusInfoProperties(JsonElement element) { Optional<UpgradeOperationHistoryStatus> runningStatus = default; Optional<RollingUpgradeProgressInfo> progress = default; Optional<ComputeApiError> error = default; Optional<UpgradeOperationInvoker> startedBy = default; Optional<ImageReference> targetImageReference = default; Optional<RollbackStatusInfo> rollbackInfo = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("runningStatus")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } runningStatus = UpgradeOperationHistoryStatus.DeserializeUpgradeOperationHistoryStatus(property.Value); continue; } if (property.NameEquals("progress")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } progress = RollingUpgradeProgressInfo.DeserializeRollingUpgradeProgressInfo(property.Value); continue; } if (property.NameEquals("error")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } error = ComputeApiError.DeserializeComputeApiError(property.Value); continue; } if (property.NameEquals("startedBy")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } startedBy = property.Value.GetString().ToUpgradeOperationInvoker(); continue; } if (property.NameEquals("targetImageReference")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } targetImageReference = ImageReference.DeserializeImageReference(property.Value); continue; } if (property.NameEquals("rollbackInfo")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } rollbackInfo = RollbackStatusInfo.DeserializeRollbackStatusInfo(property.Value); continue; } } return new UpgradeOperationHistoricalStatusInfoProperties(runningStatus.Value, progress.Value, error.Value, Optional.ToNullable(startedBy), targetImageReference.Value, rollbackInfo.Value); } } }
{ "content_hash": "45c538391f98425aca19329d480816ed", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 200, "avg_line_length": 45.03658536585366, "alnum_prop": 0.5301922556187382, "repo_name": "Azure/azure-sdk-for-net", "id": "e29623afa1c831ff28aa2c4e9241861b95ea577b", "size": "3831", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/UpgradeOperationHistoricalStatusInfoProperties.Serialization.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('helix'), require('cannon')) : typeof define === 'function' && define.amd ? define('HX_PHYS', ['exports', 'helix', 'cannon'], factory) : (factory((global.HX_PHYS = {}),global.HX,global.CANNON)); }(this, (function (exports,HX,CANNON$1) { 'use strict'; function SubShape(shape, offset, orientation) { this.shape = shape; this.offset = offset || new HX.Float4(); this.orientation = orientation; } /** * @classdesc * Compound shape allows combining multiple shapes into a single shape. * * @constructor * * @author derschmale <http://www.derschmale.com> */ function CompoundShape() { this._shapes = []; } CompoundShape.prototype = { get shapes() { return this._shapes; }, addShape: function(shape, offset, orientation) { this._shapes.push(new SubShape(shape, offset, orientation)); } }; /** * @ignore * * @author derschmale <http://www.derschmale.com> */ function Collider() { // these can optionally be set by subclasses // center is the local object space center of mass (ie: an offset of the entity's origin). When allowed to auto-calculate, it uses the bounding box center // orientation allows this._center = null; this._orientation = null; } Collider.prototype = { /** * @ignore */ createRigidBody: function(bounds) { if (!this._center) this._center = bounds.center; var shape = this.createShape(bounds); var body = new CANNON$1.Body({ mass: 50 * this.volume() }); if (shape instanceof CompoundShape) { var shapes = shape.shapes; for (var i = 0; i < shapes.length; ++i) { var subShape = shapes[i]; var c = HX.Float4.add(this._center, subShape.offset); var q = undefined; if (this._orientation) { q = this._orientation.clone(); } if (subShape.orientation) { if (q) q.append(subShape.orientation); else q = subShape.orientation.clone(); } body.addShape(subShape.shape, c, q); } } else body.addShape(shape, this._center, this._orientation); return body; }, /** * @ignore */ createShape: function(bounds) { throw new Error("Abstract method called!"); }, /** * @ignore */ volume: function() { throw new Error("Abstract method called!"); } }; /** * @classdesc * * A box-shaped collider. * * @constructor * * @param {Float4} [min] The minimum coordinates of the box in local object space. If omitted, will use the object bounds. * @param {Float4} [max] The maximum coordinates of the box in local object space. If omitted, will use the object bounds. * * @author derschmale <http://www.derschmale.com> */ function BoxCollider(min, max) { Collider.call(this); if (min && max) { this._halfExtents = HX.Float4.subtract(max, min).scale(.5); this._center = HX.Float4.add(max, min).scale(.5); } } BoxCollider.prototype = Object.create(Collider.prototype); BoxCollider.prototype.volume = function() { return 8 * (this._halfExtents.x * this._halfExtents.y * this._halfExtents.z); }; BoxCollider.prototype.createShape = function(bounds) { if (!this._halfExtents) this._halfExtents = bounds.getHalfExtents(); var vec3 = new CANNON$1.Vec3(); vec3.copy(this._halfExtents); return new CANNON$1.Box(vec3); }; /** * @classdesc * * A sphere-shaped collider. * * @constructor * * @param {number} [radius] The radius of the sphere. If omitted, will use the object bounds. * * @author derschmale <http://www.derschmale.com> */ function SphereCollider(radius, center) { Collider.call(this); this._radius = radius; this._center = center; } SphereCollider.prototype = Object.create(Collider.prototype); SphereCollider.prototype.volume = function() { var radius = this._radius; return .75 * Math.PI * radius * radius * radius; }; SphereCollider.prototype.createShape = function(bounds) { this._radius = this._radius || bounds.getRadius(); return new CANNON$1.Sphere(this._radius); }; /** * @classdesc * * Collision contains all data to describe a collision of 2 RigidBody components. * * @property rigidBody The RigidBody that collided with the collision message emitter. * @property entity The Entity that collided with the collision message emitter. * @propety contactPoints An Array of {@linkcode Contact} objects, describing the contacts in detail. * * @constructor * * @author derschmale <http://www.derschmale.com> */ function Collision() { /** * The RigidBody that collided with the rigid body broadcasting the collision message. */ this.rigidBody = null; /** * The entity that collided with the rigid body broadcasting the collision message. */ this.entity = null; /** * The world-space contact point of the collision for the rigid body broadcasting the collision message. */ this.contactPoint = new HX.Float4(0, 0, 0, 1); /** * The contact normal of the collision, pointing out of the rigid body broadcasting the collision message. */ this.contactNormal = new HX.Float4(0, 0, 0, 0); /** * The relative velocity between the two collisions (broadcaster.velocity - other.velocity) */ this.relativeVelocity = new HX.Float4(0, 0, 0, 0); } var invMatrix = new HX.Matrix4x4(); var worldQuat = new HX.Quaternion(); /** * @classdesc * RigidBody is a component allowing a scene graph object to have physics simulations applied to it. Requires * {@linkcode PhysicsSystem}. At this point, entities using RigidBody need to be added to the root of the scenegraph (or * have parents without transformations)! Broadcasts a "collision" message on the Entity when a collision occurs with a * Collision object as parameter. This Collision object is shared across collisions and therefor is only valid in the * callback method. * * @property {boolean} isKinematic When set to true, the user indicates the position of the object will be updated * manually as opposed to by the physics engine. * @property {boolean} ignoreRotation When set to true, the rigid body does not take on the rotation of its entity. This * is useful for a player controller camera. * @property {Number} ignoreRotation The mass of the target object. * @property {Number} linearDamping How much an object linear movement slows down over time * @property {Number} angularDamping How much an object rotational movement slows down over time * @property {PhysicsMaterial} material The PhysicsMaterial defining friction and restitution. * @property {Float4} angularVelocity The current angular velocity of the rigid body. * @property {Float4} linearVelocity The current linear velocity of the rigid body. * * @constructor * @param collider The Collider type describing the shape of how to object interacts with the world. If omitted, it will * take a shape based on the type of bounds assigned to the target object. * @param mass The mass of the target object. If omitted, it will venture a guess based on the bounding volume.* * @param material An optional PhysicsMaterial defining the friction and restitution parameters of the surface * * @author derschmale <http://www.derschmale.com> */ function RigidBody(collider, mass, material) { HX.Component.call(this); this._collider = collider; this._body = null; this._ignoreRotation = false; this._isKinematic = false; this._mass = mass; this._linearDamping = 0.01; this._angularDamping = 0.01; this._material = material; this._linearVelocity = new HX.Float4(); this._angularVelocity = new HX.Float4(); this._collision = new Collision(); this._onCollision = this._onCollision.bind(this); } /** * The name of the message broadcast by this component */ RigidBody.COLLISION_MESSAGE = "collision"; RigidBody.prototype = Object.create(HX.Component.prototype, { linearVelocity: { get: function() { // change to Float4 this._linearVelocity.copyFrom(this._body.velocity); return this._linearVelocity; }, set: function(value) { this._body.velocity.set(value.x, value.y, value.z); } }, angularVelocity: { get: function() { // change to Float4 this._angularVelocity.copyFrom(this._body.angularVelocity); return this._angularVelocity; }, set: function(value) { this._body.angularVelocity.set(value.x, value.y, value.z); } }, isKinematic: { get: function() { return this._isKinematic; }, set: function(value) { this._isKinematic = value; if (this._body) { this._body.type = CANNON.Body.KINEMATIC; this._body.allowSleep = false; this._body.wakeUp(); } } }, ignoreRotation: { get: function() { return this._ignoreRotation; }, set: function(value) { this._ignoreRotation = value; // disable rotational physics altogether if (this._body) this._body.fixedRotation = value; // this._body.angularDamping = value? 1.0 : this._angularDamping; } }, body: { get: function() { return this._body; } }, mass: { get: function() { return this._mass; }, set: function(value) { this._mass = value; if (this._body) { this._body.mass = value; this._body.updateMassProperties(); } } }, linearDamping: { get: function() { return this._linearDamping; }, set: function(value) { this._linearDamping = value; if (this._body) this._body.linearDamping = value; } }, angularDamping: { get: function() { return this._angularDamping; }, set: function(value) { this._angularDamping = value; // disable rotational physics altogether if ignoreRotation is set // if (this._body) // this._body.angularDamping = this._ignoreRotation? 1.0 : value; } }, material: { get: function() { return this._material; }, set: function(value) { this._material = value; if (this._body) this._body.material = value? value._cannonMaterial : null; } } }); RigidBody.prototype.addImpulse = function(v, pos) { if (pos) { this._body.applyImpulse(v, pos); } else { var vel = this._body.velocity; vel.x += v.x; vel.y += v.y; vel.z += v.z; } this._body.wakeUp(); }; RigidBody.prototype.addForce = function(v, pos) { if (pos) { this._body.applyForce(v, pos); } else { var f = this._body.force; f.x += v.x; f.y += v.y; f.z += v.z; } this._body.wakeUp(); }; RigidBody.prototype.onAdded = function() { this._createBody(); this._body.addEventListener("collide", this._onCollision); }; RigidBody.prototype.onRemoved = function() { this._body.removeEventListener("collide", this._onCollision); this._body = null; }; RigidBody.prototype.prepTransform = function() { var entity = this.entity; var body = this._body; var bodyPos = body.position; var bodyQuat = body.quaternion; var worldMatrix = entity.worldMatrix; worldMatrix.getColumn(3, bodyPos); if (this._ignoreRotation) bodyQuat.set(0, 0, 0, 1); else { var q; if (entity._isOnRoot) q = entity.rotation; else { q = worldQuat; q.fromMatrix(worldMatrix); } bodyQuat.copy(q); } }; RigidBody.prototype.applyTransform = function() { var body = this._body; // no need to update static and kinematic objects, since they don't get moved by the physics engine // also not required to update objects if they're not "awake" (means they haven't moved) if (this._mass === 0.0 || this._isKinematic || body.sleepState !== CANNON.Body.AWAKE) return; var entity = this.entity; // let's not invalidate the whole time entity.disableMatrixUpdates(); if (entity._isOnRoot) { entity.position = body.position; if (!this._ignoreRotation) entity.rotation = body.quaternion; } else { invMatrix.inverseAffineOf(entity._parent.worldMatrix); invMatrix.transformPoint(body.position, entity.position); // if (!this._ignoreRotation) invMatrix.transformQuaternion(body.quaternion, entity.rotation); } entity.enableMatrixUpdates(); }; RigidBody.prototype._createBody = function() { var entity = this.entity; var meshInstances = entity.components.meshInstance; var numMeshes = meshInstances? meshInstances.length : 0; // use the same bounding type if it's the only mesh var bounds = numMeshes === 1? meshInstances[0].mesh.bounds : entity.bounds; if (!this._collider) this._collider = bounds instanceof HX.BoundingAABB? new BoxCollider() : new SphereCollider(); this._body = this._collider.createRigidBody(bounds); this._body._hx_rigidBody = this; if (this._isKinematic) { this._body.type = CANNON.Body.KINEMATIC; this._body.allowSleep = false; } if (this._mass !== undefined) this._body.mass = this._mass; if (this._material !== undefined) this._body.material = this._material._cannonMaterial; this._body.linearDamping = this._linearDamping; this._body.angularDamping = this._angularDamping; this._body.position.copy(entity.position); this._body.fixedRotation = this._ignoreRotation; if (!this._ignoreRotation) this._body.quaternion.copy(entity.rotation); this._body.updateMassProperties(); }; RigidBody.prototype.clone = function() { var clone = new RigidBody(this._collider, this._mass, this._material); clone.linearDamping = this.linearDamping; clone.angularDamping = this.angularDamping; clone.isKinematic = this._isKinematic; return clone; }; RigidBody.prototype._onCollision = function(event) { // no use notifying about collisions if (!this.hasListeners(RigidBody.COLLISION_MESSAGE)) return; var collision = this._collision; var other = event.body._hx_rigidBody; var contact = event.contact; collision.rigidBody = other; collision.entity = other.entity; var b, r, v1, v2; var n = contact.ni; if (contact.bi === this._body) { v1 = contact.bi.velocity; v2 = contact.bj.velocity; b = contact.bi.position; r = contact.ri; collision.contactNormal.set(n.x, n.y, n.z); } else { v1 = contact.bj.velocity; v2 = contact.bi.velocity; b = contact.bj.position; r = contact.rj; collision.contactNormal.set(-n.x, -n.y, -n.z); } collision.relativeVelocity.set(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z, 0.0); collision.contactPoint.set(b.x + r.x, b.y + r.y, b.z + r.z, 1.0); this.broadcast(RigidBody.COLLISION_MESSAGE, collision); }; HX.Component.register("rigidBody", RigidBody); /** * @classdesc * PhysicsSystem is an {@linkcode EntitySystem} allowing physics simulations (based on cannonjs). * * @property fixedTimeStep If 0, it uses the frame delta times which is not recommended for stability reasons. * @constructor * * @author derschmale <http://www.derschmale.com> */ function PhysicsSystem() { HX.EntitySystem.call(this); this._world = new CANNON$1.World(); this._gravity = -9.81; // m/s² this._world.gravity.set(0, 0, this._gravity); this._world.solver.tolerance = .0001; this._world.solver.iterations = 10; this._fixedTimeStep = 1000/60; this._world.broadphase = new CANNON$1.SAPBroadphase(this._world); this._world.allowSleep = true; // this._world.broadphase = new CANNON.NaiveBroadphase(this._world); // this._world.quatNormalizeFast = true; // this._world.quatNormalizeSkip = 2; // this._world.addEventListener("collide", this._onCollision.bind(this)); this._components = []; } PhysicsSystem.prototype = Object.create(HX.EntitySystem.prototype, { gravity: { get: function() { return this._gravity; }, set: function(value) { this._gravity = value; if (value instanceof HX.Float4) this._world.gravity.set(value.x, value.y, value.z); else this._world.gravity.set(0, 0, value); } }, fixedTimeStep: { get: function() { return this._fixedTimeStep; }, set: function(value) { this._fixedTimeStep = value; } }, allowSleep: { get: function() { return this._world.allowSleep; }, set: function(value) { this._world.allowSleep = value; } } }); PhysicsSystem.prototype.onStarted = function() { this._colliders = this.getEntitySet([RigidBody]); this._colliders.onEntityAdded.bind(this._onEntityAdded, this); this._colliders.onEntityRemoved.bind(this._onEntityRemoved, this); var len = this._colliders.numEntities; for (var i = 0; i < len; ++i) { var entity = this._colliders.getEntity(i); this._onEntityAdded(entity); } }; PhysicsSystem.prototype.onStopped = function() { this._colliders.onEntityAdded.unbind(this._onEntityAdded); this._colliders.onEntityRemoved.unbind(this._onEntityRemoved); this._colliders.free(); this._colliders = null; }; PhysicsSystem.prototype._onEntityAdded = function(entity) { var component = entity.components.rigidBody[0]; // for faster access this._components.push(component); this._world.addBody(component.body); }; PhysicsSystem.prototype._onEntityRemoved = function(entity) { var component = entity.components.rigidBody[0]; this._world.removeBody(component.body); var index = this._components.indexOf(component); this._components.splice(index, 1); }; // we're updating here to enforce order of updates PhysicsSystem.prototype.onUpdate = function(dt) { var len = this._components.length; for (var i = 0; i < len; ++i) { this._components[i].prepTransform(); } this._world.step(this._fixedTimeStep * .001); for (i = 0; i < len; ++i) { this._components[i].applyTransform(); } }; /** * @classdesc * * A capsule-shaped collider. * * @constructor * * @param {number} [radius] The radius of the capsule. If omitted, will use the object bounds. * @param {number} [height] The height of the capsule. If omitted, will use the object bounds. * * @author derschmale <http://www.derschmale.com> */ function CapsuleCollider(radius, height, center) { Collider.call(this); this._radius = radius; this._height = height; this._center = center; if (this._height < 2.0 * this._radius) this._height = 2.0 * this._radius; } CapsuleCollider.prototype = Object.create(Collider.prototype); CapsuleCollider.prototype.volume = function() { var radius = this._radius; var cylHeight = this._height - 2 * this._radius; var sphereVol = .75 * Math.PI * radius * radius * radius; var cylVol = Math.PI * radius * radius * cylHeight; return cylVol + sphereVol; }; CapsuleCollider.prototype.createShape = function(bounds) { if (!this._height) this._height = bounds.halfExtents.y * 2.0; var cylHeight = this._height - 2 * this._radius; if (!this._radius) { var f = new HX.Float2(); f.set(bounds.halfExtents); // copy X and Y this._radius = f.length; } var shape = new CompoundShape(); var sphere = new CANNON$1.Sphere(this._radius); shape.addShape(sphere, new HX.Float4(0, 0, -cylHeight * .5)); shape.addShape(sphere, new HX.Float4(0, 0, cylHeight * .5)); shape.addShape(new CANNON$1.Cylinder(this._radius, this._radius, cylHeight, 10)); return shape; }; /** * @classdesc * * A capsule-shaped collider. * * @constructor * * @param {number} [radius] The radius of the cylinder. If omitted, will use the object bounds. * @param {number} [height] The height of the cylinder. If omitted, will use the object bounds. * * @author derschmale <http://www.derschmale.com> */ function CylinderCollider(radius, height, mainAxis, center) { Collider.call(this); this._radius = radius; this._height = height; this._center = center; if (mainAxis) { mainAxis.normalize(); this._orientation = HX.Quaternion.fromVectors(HX.Float4.Z_AXIS, mainAxis); } } CylinderCollider.prototype = Object.create(Collider.prototype); CylinderCollider.prototype.volume = function() { return Math.PI * this._radius * this._radius * this._height; }; CylinderCollider.prototype.createShape = function(bounds) { if (!this._radius) { var f = new HX.Float2(); f.set(bounds.halfExtent); // copy X and Y this._radius = f.length; } if (!this._height) this._height = bounds.halfExtent.z * 2.0; return new CANNON$1.Cylinder(this._radius, this._radius, this._height, 10); }; /** * @classdesc * * A box-shaped collider with the "walls" pointing to the inside * * @constructor * * @param {Float4} [thickness] The thickness of the box walls. Defaults to .1 * @param {Float4} [min] The minimum coordinates of the box in local object space. If omitted, will use the object bounds. * @param {Float4} [max] The maximum coordinates of the box in local object space. If omitted, will use the object bounds. * * @author derschmale <http://www.derschmale.com> */ function InvertedBoxCollider(thickness, min, max) { Collider.call(this); this._thickness = thickness || .1; if (min && max) { this._halfExtents = HX.Float4.subtract(max, min).scale(.5); this._center = HX.Float4.add(max, min).scale(.5); } } InvertedBoxCollider.prototype = Object.create(Collider.prototype); InvertedBoxCollider.prototype.volume = function() { return 8 * (this._halfExtents.x * this._halfExtents.y * this._halfExtents.z); }; InvertedBoxCollider.prototype.createShape = function(bounds) { if (!this._halfExtents) this._halfExtents = bounds.getHalfExtents(); var shape = new CompoundShape(); var t = this._thickness; var th = t * .5; var he = this._halfExtents; shape.addShape(new CANNON$1.Box(new CANNON$1.Vec3(th, he.y + t, he.z)), new CANNON$1.Vec3(he.x + th, 0, 0)); // posX shape.addShape(new CANNON$1.Box(new CANNON$1.Vec3(th, he.y + t, he.z)), new CANNON$1.Vec3(-(he.x + th), 0, 0)); // negX shape.addShape(new CANNON$1.Box(new CANNON$1.Vec3(he.x + t, th, he.z)), new CANNON$1.Vec3(0, he.y + th, 0)); // posY shape.addShape(new CANNON$1.Box(new CANNON$1.Vec3(he.x + t, th, he.z)), new CANNON$1.Vec3(0, -(he.y + th), 0)); // negY shape.addShape(new CANNON$1.Box(new CANNON$1.Vec3(he.x, he.y, th)), new CANNON$1.Vec3(0, 0, he.z + th)); // posZ shape.addShape(new CANNON$1.Box(new CANNON$1.Vec3(he.x, he.y, th)), new CANNON$1.Vec3(0, 0, -(he.z + th))); // negZ return shape; }; /** * @classdesc * * A collider along an infinite plane. * * @constructor * * @param {number} [height] The height of the sphere. If omitted, will use the object bounds. * * @author derschmale <http://www.derschmale.com> */ function InfinitePlaneCollider(height) { Collider.call(this); if (height) this._center = new HX.Float4(0, 0, height); } InfinitePlaneCollider.prototype = Object.create(Collider.prototype); InfinitePlaneCollider.prototype.volume = function() { return 0; }; InfinitePlaneCollider.prototype.createShape = function(bounds) { return new CANNON$1.Plane(); }; /** * HeightfieldCollider is a {@linkcode Collider} that works with heightfield data. * @param {Array|Texture2D} heightData An Array containing numbers, or a Texture2D containing texture data (this can be * slow because of the data that needs to be read back). * @param {number} worldSize The size of the height map width in world coordinates * @param {number} minHeight The minimum height in the heightmap (only used if heightData is a texture) * @param {number} maxHeight The maximum height in the heightmap (only used if heightData is a texture) * @param {boolean} rgbaEnc Indicates the data in the texture are [0 - 1] numbers encoded over the RGBA channels (only * used if heightData is a texture) * @constructor * * @author derschmale <http://www.derschmale.com> */ function HeightfieldCollider(heightData, worldSize, minHeight, maxHeight, rgbaEnc) { Collider.call(this); if (heightData instanceof HX.Texture2D) { if (maxHeight === undefined) maxHeight = 1; if (minHeight === undefined) minHeight = 0; this._heightData = this._convertHeightMap(heightData, maxHeight - minHeight, rgbaEnc); } else { this._heightData = heightData; minHeight = this._shiftHeightData(); } this._heightMapWidth = this._heightData.length; this._heightMapHeight = this._heightData[0].length; this._worldSize = worldSize; this._elementSize = this._worldSize / (this._heightMapWidth - 1); this._center = new HX.Float4(-this._elementSize * this._heightMapWidth * .5, -this._elementSize * this._heightMapHeight * .5, minHeight, 0); } HeightfieldCollider.prototype = Object.create(Collider.prototype); HeightfieldCollider.prototype.volume = function () { return 0; }; HeightfieldCollider.prototype.createShape = function (bounds) { return new CANNON$1.Heightfield(this._heightData, { elementSize: this._elementSize }); }; /** * @private * @ignore */ HeightfieldCollider.prototype._convertHeightMap = function (map, scale, rgbaEnc) { var w = map.width; var h = map.height; var data = HX.TextureUtils.getData(map); var arr = []; if (rgbaEnc) scale /= 255.0; for (var x = 0; x < w; ++x) { arr[x] = []; for (var y = 0; y < h; ++y) { // var y2 = h - y - 1; // var x2 = w - x - 1; var i = (x + y * w) << 2; var val = data[i]; if (rgbaEnc) val += data[i + 1] / 255.0 + data[i + 2] / 65025.0 + data[i + 3] / 16581375.0; arr[x][y] = val * scale; } } return arr; }; HeightfieldCollider.prototype._shiftHeightData = function() { var data = this._heightData; var w = data.width; var h = data.height; var minZ = 0.0; for (var x = 0; x < w; ++x) { for (var y = 0; y < h; ++y) { if (data[x][y] < minZ) { minZ = data[x][y]; } } } if (minZ === 0.0) return; for (x = 0; x < w; ++x) { for (y = 0; y < h; ++y) { data[x][y] += minZ; } } return minZ; }; /** * @classdesc * PhysicsMaterial represents the physical "material" a RigidBody is made of, defining friction and restitution ("bounciness"). * @param friction Defines how hard it is to move an object resting on this material. * @param restitution Defines how much an object that hits the material bounces. * @constructor * * @author derschmale <http://www.derschmale.com> */ function PhysicsMaterial(friction, restitution) { this._cannonMaterial = new CANNON$1.Material({ friction: friction, restitution: restitution }); } PhysicsMaterial.prototype = { /** * Defines how hard it is to move an object resting on this material. */ get friction() { return this._cannonMaterial.friction; }, set friction(value) { this._cannonMaterial.friction = value; }, /** * The "bounciness" of this material. */ get restitution() { return this._cannonMaterial.restitution; }, set restitution(value) { this._cannonMaterial.restitution = value; } }; exports.PhysicsSystem = PhysicsSystem; exports.RigidBody = RigidBody; exports.BoxCollider = BoxCollider; exports.CapsuleCollider = CapsuleCollider; exports.CylinderCollider = CylinderCollider; exports.InvertedBoxCollider = InvertedBoxCollider; exports.SphereCollider = SphereCollider; exports.InfinitePlaneCollider = InfinitePlaneCollider; exports.HeightfieldCollider = HeightfieldCollider; exports.PhysicsMaterial = PhysicsMaterial; exports.Collision = Collision; Object.defineProperty(exports, '__esModule', { value: true }); })));
{ "content_hash": "82c9825a3dd88b50b213c214f6377e81", "timestamp": "", "source": "github", "line_count": 1061, "max_line_length": 159, "avg_line_length": 27.809613572101792, "alnum_prop": 0.6219751914864773, "repo_name": "DerSchmale/helixjs", "id": "250f1ecfc754c88d43de6bb6dbf4d76f97786fc3", "size": "29507", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/helix-physics.js", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "91132" }, { "name": "HTML", "bytes": "4689" }, { "name": "JavaScript", "bytes": "2781739" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Nuovo Giorn. Bot. Ital. 8: 161 (1892) #### Original name Cytospora oleina Berl. ### Remarks null
{ "content_hash": "a79765625d8b2727b7002af9c65a696c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 37, "avg_line_length": 12.307692307692308, "alnum_prop": 0.6875, "repo_name": "mdoering/backbone", "id": "f4a467fe14952d23a5ff507a1d6ca73d02ca5221", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Valsaceae/Cytospora/Cytospora oleina/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
[![Gem Version](https://img.shields.io/gem/v/semantic_logger.svg)](https://rubygems.org/gems/semantic_logger) [![Build Status](https://travis-ci.org/rocketjob/semantic_logger.svg?branch=master)](https://travis-ci.org/rocketjob/semantic_logger) [![Downloads](https://img.shields.io/gem/dt/semantic_logger.svg)](https://rubygems.org/gems/semantic_logger) [![License](https://img.shields.io/badge/license-Apache%202.0-brightgreen.svg)](http://opensource.org/licenses/Apache-2.0) ![](https://img.shields.io/badge/status-Production%20Ready-blue.svg) [![Gitter chat](https://img.shields.io/badge/IRC%20(gitter)-Support-brightgreen.svg)](https://gitter.im/rocketjob/support) Low latency, high throughput, enterprise-scale logging system for Ruby * http://github.com/rocketjob/semantic_logger ## Documentation [Semantic Logger Guide](http://rocketjob.github.io/semantic_logger) [Reference Documentation](http://www.rubydoc.info/gems/semantic_logger/) ## Logging Destinations Logging to the following destinations are all supported "out-of-the-box": * File * Screen * MongoDB * BugSnag * NewRelic * Splunk * Syslog * Roll-your-own Semantic Logger is capable of logging thousands of lines per second without slowing down the application. Traditional logging systems make the application wait while the log information is being saved. Semantic Logger avoids this slowdown by pushing log events to an in-memory queue that is serviced by a separate thread that only handles saving log information to multiple destinations at the same time. ## Rails When running Rails, use [rails_semantic_logger](http://github.com/rocketjob/rails_semantic_logger) instead of Semantic Logger directly since it will automatically replace the Rails default logger with Semantic Logger. ## Supports Semantic Logger is tested and supported on the following Ruby platforms: - Ruby 2.1, 2.2, 2.3, and above - JRuby 1.7.23, 9.0.5 and above The following gems are only required when their corresponding appenders are being used, and are therefore not automatically included by this gem: - Bugsnag Appender: gem 'bugsnag' - MongoDB Appender: gem 'mongo' 1.9.2 or above - NewRelic Appender: gem 'newrelic_rpm' - Syslog Appender: gem 'syslog_protocol' 0.9.2 or above - Syslog Appender to a remote syslogng server over TCP or UDP: gem 'net_tcp_client' - Splunk Appender: gem 'splunk-sdk-ruby' ## Install gem install semantic_logger To configure a stand-alone application for Semantic Logger: ```ruby require 'semantic_logger' # Set the global default log level SemanticLogger.default_level = :trace # Log to a file, and use the colorized formatter SemanticLogger.add_appender(file_name: 'development.log', formatter: :color) ``` If running rails, see: [Semantic Logger Rails](http://rocketjob.github.io/semantic_logger/rails.html) ## Author [Reid Morrison](https://github.com/reidmorrison) [Contributors](https://github.com/rocketjob/semantic_logger/graphs/contributors) ## Versioning This project uses [Semantic Versioning](http://semver.org/).
{ "content_hash": "d77f1081bcbcd75d70e0172b455504a9", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 667, "avg_line_length": 38.8974358974359, "alnum_prop": 0.7722478576137113, "repo_name": "zach-taylor/semantic_logger", "id": "d6023bdc7b13f08a76bf8efb166886e5d7b707c2", "size": "3052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "217282" } ], "symlink_target": "" }
import { Component } from '@angular/core'; import { addDays, addMonths } from 'date-fns'; @Component({ selector: 'demo-datepicker', templateUrl: './datepicker.html', styleUrls: ['./datepicker.less'] }) export class DatePickerDemo { startDate = new Date(); endDate = addDays(new Date(), 7); selectedDate: Date = addMonths(new Date(), 1); }
{ "content_hash": "b8880a64a9ffcbe0d098453716ecd52f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 50, "avg_line_length": 28, "alnum_prop": 0.6538461538461539, "repo_name": "zxhfighter/measure", "id": "0f0299c3f53899ce61b19c306526b832be7e1842", "size": "364", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/demo/calendar/datepicker/datepicker.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "198547" }, { "name": "HTML", "bytes": "368918" }, { "name": "JavaScript", "bytes": "48656" }, { "name": "TypeScript", "bytes": "1183502" } ], "symlink_target": "" }
/** * @file templates/halconf.h * @brief HAL configuration header. * @details HAL configuration file, this file allows to enable or disable the * various device drivers from your application. You may also use * this file in order to override the device drivers default settings. * * @addtogroup HAL_CONF * @{ */ #ifndef _HALCONF_H_ #define _HALCONF_H_ #include "mcuconf.h" /** * @brief Enables the PAL subsystem. */ #if !defined(HAL_USE_PAL) || defined(__DOXYGEN__) #define HAL_USE_PAL TRUE #endif /** * @brief Enables the ADC subsystem. */ #if !defined(HAL_USE_ADC) || defined(__DOXYGEN__) #define HAL_USE_ADC TRUE #endif /** * @brief Enables the CAN subsystem. */ #if !defined(HAL_USE_CAN) || defined(__DOXYGEN__) #define HAL_USE_CAN FALSE #endif /** * @brief Enables the DAC subsystem. */ #if !defined(HAL_USE_DAC) || defined(__DOXYGEN__) #define HAL_USE_DAC FALSE #endif /** * @brief Enables the EXT subsystem. */ #if !defined(HAL_USE_EXT) || defined(__DOXYGEN__) #define HAL_USE_EXT FALSE #endif /** * @brief Enables the GPT subsystem. */ #if !defined(HAL_USE_GPT) || defined(__DOXYGEN__) #define HAL_USE_GPT FALSE #endif /** * @brief Enables the I2C subsystem. */ #if !defined(HAL_USE_I2C) || defined(__DOXYGEN__) #define HAL_USE_I2C FALSE #endif /** * @brief Enables the I2S subsystem. */ #if !defined(HAL_USE_I2S) || defined(__DOXYGEN__) #define HAL_USE_I2S FALSE #endif /** * @brief Enables the ICU subsystem. */ #if !defined(HAL_USE_ICU) || defined(__DOXYGEN__) #define HAL_USE_ICU FALSE #endif /** * @brief Enables the MAC subsystem. */ #if !defined(HAL_USE_MAC) || defined(__DOXYGEN__) #define HAL_USE_MAC FALSE #endif /** * @brief Enables the MMC_SPI subsystem. */ #if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__) #define HAL_USE_MMC_SPI FALSE #endif /** * @brief Enables the PWM subsystem. */ #if !defined(HAL_USE_PWM) || defined(__DOXYGEN__) #define HAL_USE_PWM FALSE #endif /** * @brief Enables the RTC subsystem. */ #if !defined(HAL_USE_RTC) || defined(__DOXYGEN__) #define HAL_USE_RTC FALSE #endif /** * @brief Enables the SDC subsystem. */ #if !defined(HAL_USE_SDC) || defined(__DOXYGEN__) #define HAL_USE_SDC FALSE #endif /** * @brief Enables the SERIAL subsystem. */ #if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__) #define HAL_USE_SERIAL FALSE #endif /** * @brief Enables the SERIAL over USB subsystem. */ #if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__) #define HAL_USE_SERIAL_USB FALSE #endif /** * @brief Enables the SPI subsystem. */ #if !defined(HAL_USE_SPI) || defined(__DOXYGEN__) #define HAL_USE_SPI TRUE #endif /** * @brief Enables the UART subsystem. */ #if !defined(HAL_USE_UART) || defined(__DOXYGEN__) #define HAL_USE_UART FALSE #endif /** * @brief Enables the USB subsystem. */ #if !defined(HAL_USE_USB) || defined(__DOXYGEN__) #define HAL_USE_USB FALSE #endif /** * @brief Enables the WDG subsystem. */ #if !defined(HAL_USE_WDG) || defined(__DOXYGEN__) #define HAL_USE_WDG FALSE #endif /*===========================================================================*/ /* ADC driver related settings. */ /*===========================================================================*/ /** * @brief Enables synchronous APIs. * @note Disabling this option saves both code and data space. */ #if !defined(ADC_USE_WAIT) || defined(__DOXYGEN__) #define ADC_USE_WAIT TRUE #endif /** * @brief Enables the @p adcAcquireBus() and @p adcReleaseBus() APIs. * @note Disabling this option saves both code and data space. */ #if !defined(ADC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) #define ADC_USE_MUTUAL_EXCLUSION TRUE #endif /*===========================================================================*/ /* CAN driver related settings. */ /*===========================================================================*/ /** * @brief Sleep mode related APIs inclusion switch. */ #if !defined(CAN_USE_SLEEP_MODE) || defined(__DOXYGEN__) #define CAN_USE_SLEEP_MODE TRUE #endif /*===========================================================================*/ /* I2C driver related settings. */ /*===========================================================================*/ /** * @brief Enables the mutual exclusion APIs on the I2C bus. */ #if !defined(I2C_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) #define I2C_USE_MUTUAL_EXCLUSION TRUE #endif /*===========================================================================*/ /* MAC driver related settings. */ /*===========================================================================*/ /** * @brief Enables an event sources for incoming packets. */ #if !defined(MAC_USE_ZERO_COPY) || defined(__DOXYGEN__) #define MAC_USE_ZERO_COPY FALSE #endif /** * @brief Enables an event sources for incoming packets. */ #if !defined(MAC_USE_EVENTS) || defined(__DOXYGEN__) #define MAC_USE_EVENTS TRUE #endif /*===========================================================================*/ /* MMC_SPI driver related settings. */ /*===========================================================================*/ /** * @brief Delays insertions. * @details If enabled this options inserts delays into the MMC waiting * routines releasing some extra CPU time for the threads with * lower priority, this may slow down the driver a bit however. * This option is recommended also if the SPI driver does not * use a DMA channel and heavily loads the CPU. */ #if !defined(MMC_NICE_WAITING) || defined(__DOXYGEN__) #define MMC_NICE_WAITING TRUE #endif /*===========================================================================*/ /* SDC driver related settings. */ /*===========================================================================*/ /** * @brief Number of initialization attempts before rejecting the card. * @note Attempts are performed at 10mS intervals. */ #if !defined(SDC_INIT_RETRY) || defined(__DOXYGEN__) #define SDC_INIT_RETRY 100 #endif /** * @brief Include support for MMC cards. * @note MMC support is not yet implemented so this option must be kept * at @p FALSE. */ #if !defined(SDC_MMC_SUPPORT) || defined(__DOXYGEN__) #define SDC_MMC_SUPPORT FALSE #endif /** * @brief Delays insertions. * @details If enabled this options inserts delays into the MMC waiting * routines releasing some extra CPU time for the threads with * lower priority, this may slow down the driver a bit however. */ #if !defined(SDC_NICE_WAITING) || defined(__DOXYGEN__) #define SDC_NICE_WAITING TRUE #endif /*===========================================================================*/ /* SERIAL driver related settings. */ /*===========================================================================*/ /** * @brief Default bit rate. * @details Configuration parameter, this is the baud rate selected for the * default configuration. */ #if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__) #define SERIAL_DEFAULT_BITRATE 38400 #endif /** * @brief Serial buffers size. * @details Configuration parameter, you can change the depth of the queue * buffers depending on the requirements of your application. * @note The default is 16 bytes for both the transmission and receive * buffers. */ #if !defined(SERIAL_BUFFERS_SIZE) || defined(__DOXYGEN__) #define SERIAL_BUFFERS_SIZE 16 #endif /*===========================================================================*/ /* SERIAL_USB driver related setting. */ /*===========================================================================*/ /** * @brief Serial over USB buffers size. * @details Configuration parameter, the buffer size must be a multiple of * the USB data endpoint maximum packet size. * @note The default is 256 bytes for both the transmission and receive * buffers. */ #if !defined(SERIAL_USB_BUFFERS_SIZE) || defined(__DOXYGEN__) #define SERIAL_USB_BUFFERS_SIZE 256 #endif /** * @brief Serial over USB number of buffers. * @note The default is 2 buffers. */ #if !defined(SERIAL_USB_BUFFERS_NUMBER) || defined(__DOXYGEN__) #define SERIAL_USB_BUFFERS_NUMBER 2 #endif /*===========================================================================*/ /* SPI driver related settings. */ /*===========================================================================*/ /** * @brief Enables synchronous APIs. * @note Disabling this option saves both code and data space. */ #if !defined(SPI_USE_WAIT) || defined(__DOXYGEN__) #define SPI_USE_WAIT TRUE #endif /** * @brief Enables the @p spiAcquireBus() and @p spiReleaseBus() APIs. * @note Disabling this option saves both code and data space. */ #if !defined(SPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) #define SPI_USE_MUTUAL_EXCLUSION TRUE #endif /*===========================================================================*/ /* UART driver related settings. */ /*===========================================================================*/ /** * @brief Enables synchronous APIs. * @note Disabling this option saves both code and data space. */ #if !defined(UART_USE_WAIT) || defined(__DOXYGEN__) #define UART_USE_WAIT FALSE #endif /** * @brief Enables the @p uartAcquireBus() and @p uartReleaseBus() APIs. * @note Disabling this option saves both code and data space. */ #if !defined(UART_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__) #define UART_USE_MUTUAL_EXCLUSION FALSE #endif /*===========================================================================*/ /* USB driver related settings. */ /*===========================================================================*/ /** * @brief Enables synchronous APIs. * @note Disabling this option saves both code and data space. */ #if !defined(USB_USE_WAIT) || defined(__DOXYGEN__) #define USB_USE_WAIT FALSE #endif #endif /* _HALCONF_H_ */ /** @} */
{ "content_hash": "2b9d58f9bdbbe5ab38c7ea6e33a64095", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 79, "avg_line_length": 29.877384196185286, "alnum_prop": 0.5046055631554948, "repo_name": "microwan/spc5-nil", "id": "c805eff977287b647661d087f7c5e939d2f5a226", "size": "11588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_code/dev_16.1.x/testhal/STM32/STM32F4xx/DMA_STORM/halconf.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "410791" }, { "name": "Batchfile", "bytes": "454" }, { "name": "C", "bytes": "67811905" }, { "name": "C++", "bytes": "11715445" }, { "name": "CSS", "bytes": "26156" }, { "name": "Emacs Lisp", "bytes": "1440" }, { "name": "FreeMarker", "bytes": "491901" }, { "name": "HTML", "bytes": "8049" }, { "name": "Makefile", "bytes": "1648916" }, { "name": "Objective-C", "bytes": "6091633" }, { "name": "Shell", "bytes": "11936" }, { "name": "XSLT", "bytes": "7139" } ], "symlink_target": "" }
--- id: rendering-connections title: Rendering Connections slug: /guided-tour/list-data/rendering-connections/ --- import DocsRating from '@site/src/core/DocsRating'; import FbSuspenseListAlternative from './fb/FbSuspenseListAlternative.md'; import FbRenderingConnectionsUsingSuspenseList from './fb/FbRenderingConnectionsUsingSuspenseList.md'; import {OssOnly, FbInternalOnly} from 'internaldocs-fb-helpers'; In Relay, in order to display a list of data that is backed by a GraphQL connection, first you need to declare a fragment that queries for a connection: ```js const {graphql} = require('RelayModern'); const userFragment = graphql` fragment UserFragment on User { name friends(after: $cursor, first: $count) @connection(key: "UserFragment_friends") { edges { node { ...FriendComponent } } } } `; ``` * In the example above, we're querying for the `friends` field, which is a connection; in other words, it adheres to the connection spec. Specifically, we can query the `edges` and `node`s in the connection; the `edges` usually contain information about the relationship between the entities, while the `node`s are the actual entities at the other end of the relationship; in this case, the `node`s are objects of type `User` representing the user's friends. * In order to indicate to Relay that we want to perform pagination over this connection, we need to mark the field with the `@connection` directive. We must also provide a *static* unique identifier for this connection, known as the `key`. We recommend the following naming convention for the connection key: `<fragment_name>_<field_name>`. * We will go into more detail later as to why it is necessary to mark the field as a `@connection` and give it a unique `key` in our [Updating Connections](../updating-connections/) section. In order to render this fragment which queries for a connection, we can use the `usePaginationFragment` Hook: <FbInternalOnly> <FbRenderingConnectionsUsingSuspenseList /> </FbInternalOnly> <OssOnly> ```js import type {FriendsListPaginationQuery} from 'FriendsListPaginationQuery.graphql'; import type {FriendsListComponent_user$key} from 'FriendsList_user.graphql'; const React = require('React'); const {Suspense} = require('React'); const {graphql, usePaginationFragment} = require('react-relay'); type Props = { user: FriendsListComponent_user$key, }; function FriendsListComponent(props: Props) { const {data} = usePaginationFragment<FriendsListPaginationQuery, _>( graphql` fragment FriendsListComponent_user on User @refetchable(queryName: "FriendsListPaginationQuery") { name friends(first: $count, after: $cursor) @connection(key: "FriendsList_user_friends") { edges { node { ...FriendComponent } } } } `, props.user, ); return ( <> {data.name != null ? <h1>Friends of {data.name}:</h1> : null} <div> {/* Extract each friend from the resulting data */} {(data.friends?.edges ?? []).map(edge => { const node = edge.node; return ( <Suspense fallback={<Glimmer />}> <FriendComponent user={node} /> </Suspense> ); })} </div> </> ); } module.exports = FriendsListComponent; ``` <FbSuspenseListAlternative /> * `usePaginationFragment` behaves the same way as a `useFragment` (see the [Fragments](../../rendering/fragments/) section), so our list of friends is available under `data.friends.edges.node`, as declared by the fragment. However, it also has a few additions: * It expects a fragment that is a connection field annotated with the `@connection` directive * It expects a fragment that is annotated with the `@refetchable` directive. Note that `@refetchable` directive can only be added to fragments that are "refetchable", that is, on fragments that are on `Viewer`, on `Query`, on any type that implements `Node` (i.e. a type that has an `id` field), or on a `@fetchable` type. <FbInternalOnly> For more info on `@fetchable` types, see [this post](https://fb.workplace.com/groups/graphql.fyi/permalink/1539541276187011/). </FbInternalOnly> * It takes two Flow type parameters: the type of the generated query (in our case `FriendsListPaginationQuery`), and a second type which can always be inferred, so you only need to pass underscore (`_`). </OssOnly> <DocsRating />
{ "content_hash": "e97092e33452bc19f0f8581eae790463", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 489, "avg_line_length": 41.870370370370374, "alnum_prop": 0.7014595311808934, "repo_name": "yungsters/relay", "id": "29f967f84efee4b5500ad961ca1ebef497e8159c", "size": "4522", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "website/versioned_docs/version-v11.0.0/guided-tour/list-data/rendering-connections.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "21802" }, { "name": "HTML", "bytes": "308" }, { "name": "JavaScript", "bytes": "2070265" }, { "name": "Shell", "bytes": "396" } ], "symlink_target": "" }
/** * A common implementations for JCommander. */ package com.asakusafw.utils.jcommander.common;
{ "content_hash": "54f59af75b08979d142df8e2cb39a09b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 46, "avg_line_length": 19.8, "alnum_prop": 0.7575757575757576, "repo_name": "asakusafw/asakusafw", "id": "1b89f533f7cf7c08b74ae0c6915b83104640114f", "size": "711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils-project/jcommander-wrapper/src/main/java/com/asakusafw/utils/jcommander/common/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "31" }, { "name": "CSS", "bytes": "650" }, { "name": "Groovy", "bytes": "277016" }, { "name": "Java", "bytes": "12812573" }, { "name": "Lex", "bytes": "12506" }, { "name": "Shell", "bytes": "10149" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Instantiation of custom element: custom element type is given as the value of the IS attribute</title> <meta name="author" title="Sergey G. Grekhov" href="mailto:sgrekhov@unipro.ru"> <meta name="author" title="Aleksei Yu. Semenov" href="mailto:a.semenov@unipro.ru"> <meta name="assert" content="The custom element type is given to a custom element at the time of its instantation in one of the two ways: ... 2. As the value of the IS attribute of the custom element."> <link rel="help" href="http://www.w3.org/TR/custom-elements/#instantiating-custom-elements"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="../testcommon.js"></script> </head> <body> <div id="log"></div> <script> test(function() { var doc = newHTMLDocument(); HTML5_ELEMENTS.forEach(function(tagName) { if (HTML5_DOCUMENT_ELEMENTS.indexOf(tagName) !== -1) { return; } var obj = doc.createElement(tagName); var name = 'x-a-' + tagName; var proto = Object.create(obj.constructor.prototype); var GeneratedConstructor = doc.registerElement(name, {prototype: proto, extends: tagName}); if (HTML5_TABLE_ELEMENTS.indexOf(tagName) !== -1) { doc.body.innerHTML = '<table>' + '<' + tagName + ' id="custom-element" is="' + name + '"></' + tagName + '>' + '</table>'; } else { doc.body.innerHTML = '<' + tagName + ' id="custom-element" is="' + name + '"></' + tagName + '>'; } var customElement = doc.querySelector('#custom-element'); assert_equals(Object.getPrototypeOf(customElement), GeneratedConstructor.prototype, 'Custom element type should be the type, specified as value of IS attribute'); }); }, 'Instantiation of custom element: custom element type is given as the value of ' + 'the IS attribute'); test(function() { var doc = newHTMLDocument(); HTML5_ELEMENTS.forEach(function(tagName) { if (HTML5_DOCUMENT_ELEMENTS.indexOf(tagName) !== -1) { return; } var obj = doc.createElement(tagName); var name = 'x-b-' + tagName; if (HTML5_TABLE_ELEMENTS.indexOf(tagName) !== -1) { doc.body.innerHTML = '<table>' + '<' + tagName + ' id="custom-element" is="' + name + '"></' + tagName + '>' + '</table>'; } else { doc.body.innerHTML = '<' + tagName + ' id="custom-element" is="' + name + '"></' + tagName + '>'; } var proto = Object.create(obj.constructor.prototype); var GeneratedConstructor = doc.registerElement(name, {prototype: proto, extends: tagName}); var customElement = doc.querySelector('#custom-element'); assert_equals(Object.getPrototypeOf(customElement), GeneratedConstructor.prototype, 'Custom element type should be the type, specified as value of IS attribute'); }); }, 'Instantiation of custom element: custom element type is given as the value ' + 'of the IS attribute. Custom element is unresolved at first'); </script> </body> </html>
{ "content_hash": "ac72f727a7dd5dbc5d11fc393e28583b", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 202, "avg_line_length": 44.67123287671233, "alnum_prop": 0.6105489113768783, "repo_name": "danakj/chromium", "id": "c18290d0e14cd59dd5162686e2f2198aee07eaca", "size": "3261", "binary": false, "copies": "63", "ref": "refs/heads/master", "path": "third_party/WebKit/LayoutTests/imported/wpt/custom-elements/v0/instantiating/custom-element-type-is-attribute.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>NBMRoom Class Reference</title> <link rel="stylesheet" href="../css/style.css"> <meta name="viewport" content="initial-scale=1, maximum-scale=1.4"> <meta name="generator" content="appledoc 2.2.1 (build 1334)"> </head> <body class="appledoc"> <header> <div class="container" class="hide-in-xcode"> <h1 id="library-title"> <a href="../index.html">KurentoToolbox </a> </h1> <p id="developer-home"> <a href="../index.html">Nubomedia TI</a> </p> </div> </header> <aside> <div class="container"> <nav> <ul id="header-buttons" role="toolbar"> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> <li id="on-this-page" role="navigation"> <label> On This Page <div class="chevron"> <div class="chevy chevron-left"></div> <div class="chevy chevron-right"></div> </div> <select id="jump-to"> <option value="top">Jump To&#133;</option> <option value="tasks">Tasks</option> <optgroup label="Properties"> <option value="//api/name/localPeer">localPeer</option> <option value="//api/name/name">name</option> <option value="//api/name/peers">peers</option> <option value="//api/name/url">url</option> </optgroup> <optgroup label="Instance Methods"> <option value="//api/name/initWithUsername:roomName:roomURL:">- initWithUsername:roomName:roomURL:</option> </optgroup> </select> </label> </li> </ul> </nav> </div> </aside> <article> <div id="overview_contents" class="container"> <div id="content"> <main role="main"> <h1 class="title">NBMRoom Class Reference</h1> <div class="section section-specification"><table cellspacing="0"><tbody> <tr> <th>Inherits from</th> <td>NSObject</td> </tr><tr> <th>Declared in</th> <td>NBMRoom.h</td> </tr> </tbody></table></div> <div class="section section-tasks"> <a title="Tasks" name="tasks"></a> <div class="task-list"> <div class="section-method"> <a name="//api/name/initWithUsername:roomName:roomURL:" title="initWithUsername:roomName:roomURL:"></a> <h3 class="method-title"><code><a href="#//api/name/initWithUsername:roomName:roomURL:">&ndash;&nbsp;initWithUsername:roomName:roomURL:</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection method-declaration"><code>- (instancetype)initWithUsername:(NSString *)<em>username</em> roomName:(NSString *)<em>name</em> roomURL:(NSURL *)<em>url</em></code></div> </div> </div> </div><div class="section-method"> <a name="//api/name/name" title="name"></a> <h3 class="method-title"><code><a href="#//api/name/name">&nbsp;&nbsp;name</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection method-declaration"><code>@property (nonatomic, copy, readonly) NSString *name</code></div> </div> </div> </div><div class="section-method"> <a name="//api/name/url" title="url"></a> <h3 class="method-title"><code><a href="#//api/name/url">&nbsp;&nbsp;url</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong, readonly) NSURL *url</code></div> </div> </div> </div><div class="section-method"> <a name="//api/name/localPeer" title="localPeer"></a> <h3 class="method-title"><code><a href="#//api/name/localPeer">&nbsp;&nbsp;localPeer</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection method-declaration"><code>@property (nonatomic, copy, readonly) NBMPeer *localPeer</code></div> </div> </div> </div><div class="section-method"> <a name="//api/name/peers" title="peers"></a> <h3 class="method-title"><code><a href="#//api/name/peers">&nbsp;&nbsp;peers</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong, readonly) NSSet *peers</code></div> </div> </div> </div> </div> </div> </main> <footer> <div class="footer-copyright"> <p class="copyright">Copyright &copy; 2016 Nubomedia TI. All rights reserved. Updated: 2016-02-18</p> <p class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.2.1 (build 1334)</a>.</p> </div> </footer> </div> </div> </article> <script src="../js/script.js"></script> </body> </html>
{ "content_hash": "aae5c4207c0d4f1b09452ecc90c05c71", "timestamp": "", "source": "github", "line_count": 224, "max_line_length": 199, "avg_line_length": 22.660714285714285, "alnum_prop": 0.6016548463356974, "repo_name": "ArtsiomHainetdzinau/Kurento-iOS", "id": "14ea37c67596151b9a8de86b02889ee75a3b091f", "size": "5076", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "docs/html/Classes/NBMRoom.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "877" }, { "name": "Objective-C", "bytes": "435405" }, { "name": "Ruby", "bytes": "7787" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2014, The Sporting Exchange Limited ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd"> <bean class="com.betfair.cougar.util.configuration.PropertyConfigurer"> <constructor-arg index="0" ref="cougar.core.EncryptorRegistry"/> <property name="defaultConfig" value="classpath:conf/cougar-transport-defaults.properties"/> <property name="configOverride" value="overrides.properties"/> <property name="placeholderPrefix" value="$COUGAR-TRANSPORT{"/> </bean> <!-- Initialise the RequestUUID Generator --> <bean class="com.betfair.cougar.util.RequestUUIDImpl"> <constructor-arg index="0" ref="$COUGAR-TRANSPORT{cougar.transport.uuidgenerator}"/> </bean> <bean id="defaultServerRequestUuidGenerator" class="com.betfair.cougar.util.UUIDGeneratorImpl"/> <bean id="protocolBindingRegistry" class="com.betfair.cougar.transport.impl.protocol.ProtocolBindingRegistryImpl"/> <bean id="abstractProtocolBinding" class="com.betfair.cougar.transport.impl.protocol.ProtocolBindingHelper" abstract="true" scope="prototype" init-method="init"> <property name="registry" ref="protocolBindingRegistry"/> </bean> <bean id="dehydratedExecutionContextResolution" class="com.betfair.cougar.transport.impl.DehydratedExecutionContextResolutionImpl"> </bean> <bean id="contextResolutionRegisterer" parent="cougar.core.OptionalGateRegisterer" lazy-init="false" scope="singleton"> <constructor-arg index="1" ref="dehydratedExecutionContextResolution"/> </bean> <bean id="dehydratedExecutionContextFactoryRegisterer" class="com.betfair.cougar.transport.impl.DehydratedExecutionContextFactoryRegisterer" abstract="true" init-method="init" lazy-init="false"> <constructor-arg index="0" ref="cougar.transport.ContextResolution"/> </bean> <alias name="protocolBindingRegistry" alias="cougar.transport.ProtocolBindingRegistry"/> <alias name="abstractProtocolBinding" alias="cougar.transport.AbstractProtocolBinding"/> <alias name="dehydratedExecutionContextResolution" alias="cougar.transport.ContextResolution"/> <alias name="dehydratedExecutionContextFactoryRegisterer" alias="cougar.transport.ContextRegisterer"/> </beans>
{ "content_hash": "07f998163a7b899b34914bb9016d1fd2", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 144, "avg_line_length": 51.317460317460316, "alnum_prop": 0.7503866377977111, "repo_name": "olupas/cougar", "id": "e7caecf79d413d3b10f1a10f1e9a0630cd969e4f", "size": "3233", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cougar-framework/cougar-transport-impl/src/main/resources/conf/module-config-cougar-transport.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "83394" }, { "name": "HTML", "bytes": "23595" }, { "name": "Java", "bytes": "9535986" }, { "name": "Shell", "bytes": "19139" }, { "name": "XSLT", "bytes": "57361" } ], "symlink_target": "" }
#pragma once // Dependencies #include "../ext/scalar_uint_sized.hpp" #include "../detail/setup.hpp" #ifndef GLM_ENABLE_EXPERIMENTAL # error "GLM: GLM_GTX_raw_data is an experimental extension and may change in the future. Use #define GLM_ENABLE_EXPERIMENTAL before including it, if you really want to use it." #endif #if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED) # pragma message("GLM: GLM_GTX_raw_data extension included") #endif namespace glm { /// @addtogroup gtx_raw_data /// @{ //! Type for byte numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint8 byte; //! Type for word numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint16 word; //! Type for dword numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint32 dword; //! Type for qword numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint64 qword; /// @} }// namespace glm #include "raw_data.inl"
{ "content_hash": "8949340960cfd6f5d93068245054ca49", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 177, "avg_line_length": 24.8, "alnum_prop": 0.6723790322580645, "repo_name": "vahlers/scg3", "id": "a0578dc3648e856c9106351d59ddb117514841b1", "size": "1274", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "scg3/extern/glm/glm/gtx/raw_data.hpp", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3109" }, { "name": "C++", "bytes": "642641" }, { "name": "CMake", "bytes": "9671" }, { "name": "GLSL", "bytes": "30448" } ], "symlink_target": "" }
package com.github.DNAProject.core.payload; import java.io.IOException; import com.github.DNAProject.common.Address; import com.github.DNAProject.core.transaction.TransactionType; import com.github.DNAProject.core.transaction.Transaction; import com.github.DNAProject.io.BinaryReader; import com.github.DNAProject.io.BinaryWriter; public class DeployCode extends Transaction { public byte[] code; public boolean needStorage; public String name; public String version; public String author; public String email; public String description; public DeployCode() { super(TransactionType.DeployCode); } @Override public void deserializeExclusiveData(BinaryReader reader) throws IOException { try { code = reader.readVarBytes(); needStorage = reader.readBoolean(); name = reader.readVarString(); version = reader.readVarString(); author = reader.readVarString(); email = reader.readVarString(); description = reader.readVarString(); } catch (Exception e) { e.printStackTrace(); } } @Override protected void serializeExclusiveData(BinaryWriter writer) throws IOException { writer.writeVarBytes(code); writer.writeBoolean(needStorage); writer.writeVarString(name); writer.writeVarString(version); writer.writeVarString(author); writer.writeVarString(email); writer.writeVarString(description); } @Override public Address[] getAddressU160ForVerifying() { return null; } }
{ "content_hash": "6e60cf23e8732f5767a99be6641bccee", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 83, "avg_line_length": 28.70175438596491, "alnum_prop": 0.6766503667481663, "repo_name": "DNAProject/DNASDKJava", "id": "ce6f9d2f3eeba68c3bcc15511518c3b5f848bd7f", "size": "2389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/github/DNAProject/core/payload/DeployCode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "810102" } ], "symlink_target": "" }
from twisted.internet.protocol import Protocol class HelloServerProtocol(Protocol): def connectionMade(self): print("connectionMade", self.transport.getHost(), self.transport.getPeer()) self.transport.write('how are you?' * 100) def dataReceived(self, data): print("dataReceived: {}".format(data)) if __name__ == '__main__': import sys from twisted.python import log from twisted.internet import reactor from twisted.internet.protocol import Factory from autobahn.twisted.websocket import WrappingWebSocketServerFactory log.startLogging(sys.stdout) wrappedFactory = Factory.forProtocol(HelloServerProtocol) factory = WrappingWebSocketServerFactory(wrappedFactory, "ws://127.0.0.1:9000", debug=False, enableCompression=False, autoFragmentSize=1024) reactor.listenTCP(9000, factory) reactor.run()
{ "content_hash": "1d8b14eba75ebae1d80dc6d82e8588d3", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 83, "avg_line_length": 31.147058823529413, "alnum_prop": 0.6052880075542965, "repo_name": "bencharb/AutobahnPython", "id": "1c6dd74142b2740e46b008b652cca5f16ced0dbb", "size": "2336", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/twisted/websocket/wrapping/server.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "3345" }, { "name": "Python", "bytes": "883272" } ], "symlink_target": "" }
FactoryGirl.define do factory :guide_category do #user name "Some Category Name" end end
{ "content_hash": "9b779175128939d764538c8459633538", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 29, "avg_line_length": 16.833333333333332, "alnum_prop": 0.7029702970297029, "repo_name": "RailsGEnthusiasts/RubyGameDev.com", "id": "04963f2d012a9038096ac0d43c8163010551efb5", "size": "101", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/factories/guide_category.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3147" }, { "name": "HTML", "bytes": "42985" }, { "name": "JavaScript", "bytes": "2121" }, { "name": "Ruby", "bytes": "104974" } ], "symlink_target": "" }
require 'sass' module Sass::Script class Color def to_s(opts = {}) return rgba_str if alpha? return smallest if options[:style] == :compressed #return COLOR_NAMES_REVERSE[rgb] if COLOR_NAMES_REVERSE[rgb] hex_str end end end
{ "content_hash": "6971cb39955781aa7c1ddf851a072c8e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 66, "avg_line_length": 22.583333333333332, "alnum_prop": 0.6199261992619927, "repo_name": "taikiken/sankaku.js", "id": "0199b1f66cf26328d34375967b4a0acbffb884f6", "size": "271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_build_css/sass_setting/color.rb", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "6260" }, { "name": "HTML", "bytes": "460129" }, { "name": "JavaScript", "bytes": "1111546" }, { "name": "Ruby", "bytes": "5262" } ], "symlink_target": "" }
"""Tests for tf.keras models using DistributionStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl.testing import parameterized import numpy as np from tensorflow.contrib.distribute.python import combinations from tensorflow.contrib.distribute.python import mirrored_strategy from tensorflow.contrib.distribute.python import tpu_strategy from tensorflow.python import keras from tensorflow.python.data.ops import dataset_ops from tensorflow.python.distribute import values from tensorflow.python.eager import test from tensorflow.python.estimator import keras as keras_lib from tensorflow.python.estimator import run_config as run_config_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.keras import testing_utils from tensorflow.python.keras.engine import distributed_training_utils from tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_keras from tensorflow.python.ops.parsing_ops import gen_parsing_ops from tensorflow.python.platform import gfile from tensorflow.python.summary.writer import writer_cache from tensorflow.python.training import gradient_descent from tensorflow.python.training import rmsprop _RANDOM_SEED = 1337 _TRAIN_SIZE = 200 _INPUT_SIZE = (10,) _NUM_CLASS = 2 # Note: Please make sure the tests in this file are also covered in # keras_backward_compat_test for features that are supported with both APIs. # TODO(anjalisridhar): Add a decorator that will allow us to run these tests as # part of the tf.keras unit tests suite. def simple_sequential_model(): model = keras.models.Sequential() model.add(keras.layers.Dense(16, activation='relu', input_shape=_INPUT_SIZE)) model.add(keras.layers.Dropout(0.1)) model.add(keras.layers.Dense(_NUM_CLASS, activation='softmax')) return model def simple_functional_model(): a = keras.layers.Input(shape=_INPUT_SIZE) b = keras.layers.Dense(16, activation='relu')(a) b = keras.layers.Dropout(0.1)(b) b = keras.layers.Dense(_NUM_CLASS, activation='softmax')(b) model = keras.models.Model(inputs=[a], outputs=[b]) return model def multi_inputs_multi_outputs_model(): input_a = keras.layers.Input(shape=(16,), name='input_a') input_b = keras.layers.Input(shape=(16,), name='input_b') input_m = keras.layers.Input(shape=(8,), dtype='string', name='input_m') dense = keras.layers.Dense(8, name='dense_1') interm_a = dense(input_a) # Read m interm_m = keras.layers.Lambda(gen_parsing_ops.string_to_number)(input_m) interm_s = keras.layers.Lambda(lambda k: k[0] * k[1])([interm_m, interm_a]) interm_b = dense(input_b) merged = keras.layers.concatenate([interm_s, interm_b], name='merge') output_c = keras.layers.Dense(3, activation='softmax', name='dense_2')(merged) output_d = keras.layers.Dense(2, activation='softmax', name='dense_3')(merged) model = keras.models.Model( inputs=[input_a, input_b, input_m], outputs=[output_c, output_d]) model.compile( loss='categorical_crossentropy', optimizer=gradient_descent.GradientDescentOptimizer(0.001), metrics={ 'dense_2': 'categorical_accuracy', 'dense_3': 'categorical_accuracy' }) return model def get_ds_train_input_fn(): np.random.seed(_RANDOM_SEED) (x_train, y_train), _ = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=_INPUT_SIZE, num_classes=_NUM_CLASS) y_train = keras.utils.to_categorical(y_train) dataset = dataset_ops.Dataset.from_tensor_slices((x_train, y_train)) dataset = dataset.batch(32) return dataset def get_ds_test_input_fn(): np.random.seed(_RANDOM_SEED) _, (x_test, y_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=_INPUT_SIZE, num_classes=_NUM_CLASS) y_test = keras.utils.to_categorical(y_test) dataset = dataset_ops.Dataset.from_tensor_slices((x_test, y_test)) dataset = dataset.batch(32) return dataset def get_multi_inputs_multi_outputs_data(): (a_train, c_train), (a_test, c_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(16,), num_classes=3, random_seed=_RANDOM_SEED) (b_train, d_train), (b_test, d_test) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(16,), num_classes=2, random_seed=_RANDOM_SEED) (m_train, _), (m_test, _) = testing_utils.get_test_data( train_samples=_TRAIN_SIZE, test_samples=50, input_shape=(8,), num_classes=2, random_seed=_RANDOM_SEED) c_train = keras.utils.to_categorical(c_train) c_test = keras.utils.to_categorical(c_test) d_train = keras.utils.to_categorical(d_train) d_test = keras.utils.to_categorical(d_test) train_data = { 'input_a': a_train, 'input_b': b_train, 'input_m': m_train, 'output_c': c_train, 'output_d': d_train } test_data = { 'input_a': a_test, 'input_b': b_test, 'input_m': m_test, 'output_c': c_test, 'output_d': d_test } return (train_data, test_data) def batch_wrapper(dataset, batch_size, distribution, repeat=None): if repeat: dataset = dataset.repeat(repeat) # TPUs currently require fully defined input shapes, drop_remainder ensures # the input will have fully defined shapes. if isinstance(distribution, tpu_strategy.TPUStrategy): return dataset.batch(batch_size, drop_remainder=True) else: return dataset.batch(batch_size) def get_model(): x = keras.layers.Input(shape=(3,), name='input') y = keras.layers.Dense(4, name='dense')(x) model = keras.Model(x, y) return model def get_dataset(distribution): inputs = np.zeros((10, 3), dtype=np.float32) targets = np.zeros((10, 4), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat(100) dataset = batch_wrapper(dataset, 10, distribution) return dataset def get_predict_dataset(distribution): inputs = np.zeros((10, 3), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices(inputs) dataset = dataset.repeat(100) dataset = batch_wrapper(dataset, 10, distribution) return dataset def multi_input_output_model(): a = keras.layers.Input(shape=(3,), name='input_a') b = keras.layers.Input(shape=(5,), name='input_b') # TODO(anjalisridhar): Change the output dimension of the second Dense layer # once the iterator output validation issue has been fixed. dense_1 = keras.layers.Dense(7, name='dense_1') dense_2 = keras.layers.Dense(7, name='dense_2') c = dense_1(a) d = dense_2(b) e = keras.layers.Dropout(0.5, name='dropout')(c) model = keras.models.Model([a, b], [d, e]) return model strategies_minus_tpu = [ combinations.default_strategy, combinations.one_device_strategy, combinations.mirrored_strategy_with_gpu_and_cpu, combinations.mirrored_strategy_with_two_gpus, combinations.core_mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_two_gpus] tpu_strategies = [ combinations.tpu_strategy, # steps_per_run=2 combinations.tpu_strategy_one_step] def strategy_minus_tpu_combinations(): return combinations.combine( distribution=strategies_minus_tpu, mode=['graph', 'eager']) def tpu_strategy_combinations(): return combinations.combine( distribution=tpu_strategies, mode=['graph']) def all_strategy_combinations(): return strategy_minus_tpu_combinations() + tpu_strategy_combinations() # TODO(priyag): Add v2 optimizers here. def strategy_and_optimizer_combinations(): return combinations.times( all_strategy_combinations(), combinations.combine( optimizer=[combinations.adagrad_optimizer_v1_fn, combinations.adam_optimizer_v1_fn, combinations.gradient_descent_optimizer_v1_fn, combinations.rmsprop_optimizer_v1_fn])) def strategy_for_numpy_input_combinations(): return combinations.combine( distribution=strategies_minus_tpu + tpu_strategies, mode=['graph']) class TestEstimatorDistributionStrategy(test_util.TensorFlowTestCase, parameterized.TestCase): def setUp(self): self._base_dir = os.path.join(self.get_temp_dir(), 'keras_mirrored_strategy_test') gfile.MakeDirs(self._base_dir) self._config = run_config_lib.RunConfig( tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir) def tearDown(self): writer_cache.FileWriterCache.clear() if os.path.isdir(self._base_dir): gfile.DeleteRecursively(self._base_dir) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.mirrored_strategy_with_two_gpus, combinations.core_mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_two_gpus], mode=['graph'])) def test_train_functional_with_distribution_strategy(self, distribution): keras_model = simple_functional_model() keras_model.compile( loss='categorical_crossentropy', metrics=[keras.metrics.CategoricalAccuracy()], optimizer=rmsprop.RMSPropOptimizer(learning_rate=0.01)) config = run_config_lib.RunConfig(tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir, train_distribute=distribution, eval_distribute=distribution) with self.cached_session(): est_keras = keras_lib.model_to_estimator( keras_model=keras_model, config=config) before_eval_results = est_keras.evaluate( input_fn=get_ds_test_input_fn, steps=1) est_keras.train(input_fn=get_ds_train_input_fn, steps=_TRAIN_SIZE / 16) after_eval_results = est_keras.evaluate(input_fn=get_ds_test_input_fn, steps=1) self.assertLess(after_eval_results['loss'], before_eval_results['loss']) writer_cache.FileWriterCache.clear() gfile.DeleteRecursively(self._config.model_dir) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.mirrored_strategy_with_two_gpus, combinations.core_mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_two_gpus], mode=['graph'])) def test_train_sequential_with_distribution_strategy(self, distribution): keras_model = simple_sequential_model() keras_model.compile( loss='categorical_crossentropy', metrics=[keras.metrics.CategoricalAccuracy()], optimizer=rmsprop.RMSPropOptimizer(learning_rate=0.01)) config = run_config_lib.RunConfig(tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir, train_distribute=distribution) with self.cached_session(): est_keras = keras_lib.model_to_estimator( keras_model=keras_model, config=config) before_eval_results = est_keras.evaluate( input_fn=get_ds_test_input_fn, steps=1) est_keras.train(input_fn=get_ds_train_input_fn, steps=_TRAIN_SIZE / 16) after_eval_results = est_keras.evaluate(input_fn=get_ds_test_input_fn, steps=1) self.assertLess(after_eval_results['loss'], before_eval_results['loss']) writer_cache.FileWriterCache.clear() gfile.DeleteRecursively(self._config.model_dir) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph'])) def test_multi_inputs_multi_outputs_with_input_fn_as_dict(self, distribution): train_data, test_data = get_multi_inputs_multi_outputs_data() def train_input_fn(): input_dict = { 'input_a': train_data['input_a'], 'input_b': train_data['input_b'], 'input_m': train_data['input_m'].astype(np.str) } output_dict = { 'dense_2': train_data['output_c'], 'dense_3': train_data['output_d'] } return dataset_ops.Dataset.from_tensor_slices((input_dict, output_dict)).batch(16) def eval_input_fn(): input_dict = { 'input_a': test_data['input_a'], 'input_b': test_data['input_b'], 'input_m': test_data['input_m'].astype(np.str) } output_dict = { 'dense_2': test_data['output_c'], 'dense_3': test_data['output_d'] } return dataset_ops.Dataset.from_tensor_slices((input_dict, output_dict)).batch(16) self.do_test_multi_inputs_multi_outputs_with_input_fn( distribution, train_input_fn, eval_input_fn) def do_test_multi_inputs_multi_outputs_with_input_fn( self, distribution, train_input_fn, eval_input_fn): config = run_config_lib.RunConfig( tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir, train_distribute=distribution) with self.cached_session(): model = multi_inputs_multi_outputs_model() est_keras = keras_lib.model_to_estimator(keras_model=model, config=config) baseline_eval_results = est_keras.evaluate( input_fn=eval_input_fn, steps=1) est_keras.train(input_fn=train_input_fn, steps=_TRAIN_SIZE / 16) eval_results = est_keras.evaluate(input_fn=eval_input_fn, steps=1) self.assertLess(eval_results['loss'], baseline_eval_results['loss']) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph'])) def test_keras_optimizer_with_distribution_strategy(self, distribution): keras_model = simple_sequential_model() keras_model.compile( loss='categorical_crossentropy', optimizer=keras.optimizers.rmsprop(lr=0.01)) config = run_config_lib.RunConfig(tf_random_seed=_RANDOM_SEED, model_dir=self._base_dir, train_distribute=distribution) with self.cached_session(): est_keras = keras_lib.model_to_estimator(keras_model=keras_model, config=config) with self.assertRaisesRegexp(ValueError, 'Only TensorFlow native optimizers are ' 'supported with DistributionStrategy.'): est_keras.train(input_fn=get_ds_train_input_fn, steps=_TRAIN_SIZE / 16) writer_cache.FileWriterCache.clear() gfile.DeleteRecursively(self._config.model_dir) class TestDistributionStrategyWithNumpyArrays(test.TestCase, parameterized.TestCase): @combinations.generate(strategy_for_numpy_input_combinations()) def test_creating_var_with_numpy_arrays(self, distribution): with self.cached_session(): x = np.asarray(np.random.random((64, 3)), dtype=np.float32) var_x = distributed_training_utils.get_var_for_numpy(distribution, x) val = self.evaluate(var_x.value()) # Verify that the numpy value is copied to the variable. self.assertAllEqual(x, val) @combinations.generate(strategy_for_numpy_input_combinations()) def test_calculating_input_params_no_steps_no_batch_size(self, distribution): # Calculate the per_replica_batch_size scaling factor for strategies # that use per_core_batch_size replica_scale_factor = 1.0 if not distributed_training_utils.global_batch_size_supported(distribution): replica_scale_factor = distribution.num_replicas_in_sync with self.cached_session(): # Input samples of different sizes input_20_samples = np.zeros((20, 3), dtype=np.float32) input_63_samples = np.zeros((63, 3), dtype=np.float32) input_64_samples = np.zeros((64, 3), dtype=np.float32) # Default global batch size 32 for input with 64 samples run in 2 steps steps, batch_size = distributed_training_utils.get_input_params( distribution, input_64_samples, steps=None, batch_size=None) self.assertEqual(batch_size, 32 // replica_scale_factor) self.assertEqual(steps, 2) # Computed global batch size 20 is lower than 32 if we pass less samples. steps, batch_size = distributed_training_utils.get_input_params( distribution, input_20_samples, steps=None, batch_size=None) self.assertEqual(batch_size, 20 // replica_scale_factor) self.assertEqual(steps, 1) # Default global batch size 32 cannot be used with 63 samples. with self.assertRaisesRegexp(ValueError, 'not divisible by batch size'): distributed_training_utils.get_input_params( distribution, input_63_samples, steps=None, batch_size=None) @combinations.generate(strategy_for_numpy_input_combinations()) def test_calculating_input_params_with_steps_no_batch_size(self, distribution): # Calculate the per_replica_batch_size scaling factor for strategies # that use per_core_batch_size replica_scale_factor = 1.0 if not distributed_training_utils.global_batch_size_supported(distribution): replica_scale_factor = distribution.num_replicas_in_sync with self.cached_session(): # Input samples of different sizes input_63_samples = np.zeros((63, 3), dtype=np.float32) input_64_samples = np.zeros((64, 3), dtype=np.float32) # Computed global batch size is correct for number of specified 1 step steps, batch_size = distributed_training_utils.get_input_params( distribution, input_64_samples, steps=1, batch_size=None) self.assertEqual(batch_size, 64 // replica_scale_factor) self.assertEqual(steps, 1) # Computed global batch size is correct for number of specified 2 steps steps, batch_size = distributed_training_utils.get_input_params( distribution, input_64_samples, steps=2, batch_size=None) self.assertEqual(batch_size, 32 // replica_scale_factor) self.assertEqual(steps, 2) # All samples can not be consumed in specified number of steps with self.assertRaisesRegexp(ValueError, 'not divisible by steps'): distributed_training_utils.get_input_params( distribution, input_63_samples, steps=2, batch_size=None) # This cases is different for different strategies due to the # difference in supported batch size being global or per-replica. if replica_scale_factor == 1: # Computed global batch size is correct even if not sharadable steps, batch_size = distributed_training_utils.get_input_params( distribution, input_63_samples, steps=3, batch_size=None) self.assertEqual(batch_size, 21) self.assertEqual(steps, 3) else: # Computed global batch size can not be sharded across replicas with self.assertRaisesRegexp(ValueError, 'could not be sharded evenly ' 'across the sync replicas'): distributed_training_utils.get_input_params( distribution, input_63_samples, steps=1, batch_size=None) @combinations.generate(strategy_for_numpy_input_combinations()) def test_calculating_input_params_no_steps_with_batch_size(self, distribution): # Calculate the per_replica_batch_size scaling factor for strategies # that use per_core_batch_size replica_scale_factor = 1.0 if not distributed_training_utils.global_batch_size_supported(distribution): replica_scale_factor = distribution.num_replicas_in_sync with self.cached_session(): input_64_samples = np.zeros((64, 3), dtype=np.float32) # Computed steps is correct for specified batch size steps, batch_size = distributed_training_utils.get_input_params( distribution, input_64_samples, steps=None, batch_size=16) self.assertEqual(batch_size, 16) self.assertEqual(steps, 4 // replica_scale_factor) # Computed steps is correct for specified batch size steps, batch_size = distributed_training_utils.get_input_params( distribution, input_64_samples, steps=None, batch_size=32) self.assertEqual(batch_size, 32) self.assertEqual(steps, 2 // replica_scale_factor) # Number of samples is not divisible by the global batch size with self.assertRaisesRegexp(ValueError, 'not divisible by batch size'): distributed_training_utils.get_input_params( distribution, input_64_samples, steps=None, batch_size=20) # Number of samples is not divisible by the global batch size with self.assertRaisesRegexp(ValueError, 'not divisible by batch size'): distributed_training_utils.get_input_params( distribution, input_64_samples, steps=None, batch_size=3) @combinations.generate(strategy_for_numpy_input_combinations()) def test_calculating_input_params_with_steps_with_batch_size(self, distribution): with self.cached_session(): input_64_samples = np.zeros((64, 3), dtype=np.float32) # No change to steps and batch size if both specified and feasible steps, batch_size = distributed_training_utils.get_input_params( distribution, input_64_samples, steps=5, batch_size=3) self.assertEqual(batch_size, 3) self.assertEqual(steps, 5) # Number of samples is less than global batch size * steps with self.assertRaisesRegexp(ValueError, 'less than samples required'): distributed_training_utils.get_input_params( distribution, input_64_samples, steps=10, batch_size=13) @combinations.generate(strategy_for_numpy_input_combinations()) def test_calling_model_with_numpy_arrays(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae'] model.compile(optimizer, loss, metrics=metrics) inputs = np.zeros((64, 3), dtype=np.float32) targets = np.zeros((64, 4), dtype=np.float32) # Call fit with validation data model.fit(inputs, targets, epochs=1, batch_size=2, verbose=0, validation_data=(inputs, targets)) # TODO(anjalisridhar): We need tests for when the batch size and steps are # smaller and results in a 0 batch_size and steps value. model.evaluate(inputs, targets) # with steps model.evaluate(inputs, targets, steps=2) # with batch_size model.evaluate(inputs, targets, batch_size=8) model.predict(inputs) # with steps model.predict(inputs, steps=2) # with batch_size model.predict(inputs, batch_size=8) @combinations.generate(strategy_for_numpy_input_combinations()) def test_calling_model_with_nested_numpy_arrays(self, distribution): with self.cached_session(): with distribution.scope(): model = multi_input_output_model() optimizer = gradient_descent.GradientDescentOptimizer( learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss) input_a_np = np.asarray(np.random.random((64, 3)), dtype=np.float32) input_b_np = np.asarray(np.random.random((64, 5)), dtype=np.float32) inputs = [input_a_np, input_b_np] output_d_np = np.asarray(np.random.random((64, 7)), dtype=np.float32) output_e_np = np.asarray(np.random.random((64, 7)), dtype=np.float32) targets = [output_d_np, output_e_np] # Call fit with validation data model.fit(inputs, targets, epochs=1, batch_size=8, verbose=0) # TODO(anjalisridhar): We need tests for when the batch size and steps are # smaller and results in a 0 batch_size and steps value. model.evaluate(inputs, targets) # with steps model.evaluate(inputs, targets, steps=2) # with batch_size model.evaluate(inputs, targets, batch_size=8) model.predict(inputs) # with steps model.predict(inputs, steps=2) # with batch_size model.predict(inputs, batch_size=8) @combinations.generate(combinations.combine( distribution=strategies_minus_tpu, mode=['graph'])) def test_numpy_with_sample_weights(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss) inputs = np.zeros((20, 3), np.float32) targets = np.zeros((20, 4), np.float32) sample_weights = np.ones((20), np.float32) model.fit(inputs, targets, sample_weight=sample_weights, epochs=1, steps_per_epoch=2, verbose=1) @combinations.generate(strategy_for_numpy_input_combinations()) def test_flatten_predict_outputs(self, distribution): with self.cached_session(): with distribution.scope(): model = multi_input_output_model() optimizer = gradient_descent.GradientDescentOptimizer( learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss) # We take 6 input samples with each input having a dimension of 3 or 5. input_a_np = np.asarray(np.random.random((6, 3)), dtype=np.float32) input_b_np = np.asarray(np.random.random((6, 5)), dtype=np.float32) inputs = [input_a_np, input_b_np] outs = model.predict(inputs, steps=1) # `predict` a list that is equal in length to the number of model outputs. # In this test our model has two outputs and each element of `outs` # corresponds to all the samples of one of the model outputs. self.assertLen(outs, 2) # Each of the output samples have a dimension of 7. We should process all # the available input samples(6). self.assertAllEqual([6, 7], outs[0].shape) self.assertAllEqual([6, 7], outs[1].shape) class TestDistributionStrategyWithDatasets(test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_calling_model_on_same_dataset(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae', keras.metrics.CategoricalAccuracy()] model.compile(optimizer, loss, metrics=metrics) dataset = get_dataset(distribution) # Call fit with validation data model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, validation_data=dataset, validation_steps=2) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, validation_data=dataset, validation_steps=2) model.predict(get_predict_dataset(distribution), steps=2) @combinations.generate(all_strategy_combinations()) def test_model_interleaved_eval_same_as_direct_eval(self, distribution): with self.cached_session(): with distribution.scope(): user_controlled_model = get_model() user_controlled_model.compile( gradient_descent.GradientDescentOptimizer(0.001), loss='mse', metrics=['mae', keras.metrics.CategoricalAccuracy()]) interleaved_model = get_model() interleaved_model.set_weights(user_controlled_model.get_weights()) interleaved_model.compile( gradient_descent.GradientDescentOptimizer(0.001), loss='mse', metrics=['mae', keras.metrics.CategoricalAccuracy()]) dataset = get_dataset(distribution) # Call fit with validation interleaved interleaved_output = interleaved_model.fit( dataset, epochs=2, steps_per_epoch=2, verbose=1, validation_data=dataset, validation_steps=2, shuffle=False) # Manually control the validation running after each epoch. user_controlled_output = [] for _ in range(2): user_controlled_model.fit( dataset, epochs=1, steps_per_epoch=2, verbose=1, shuffle=False) user_controlled_output.append( user_controlled_model.evaluate(dataset, steps=2)) self.assertEqual(interleaved_output.history['val_loss'], [x[0] for x in user_controlled_output]) self.assertEqual(interleaved_output.history['val_mean_absolute_error'], [x[1] for x in user_controlled_output]) self.assertEqual(interleaved_output.history['val_categorical_accuracy'], [x[2] for x in user_controlled_output]) # TODO(priyag): Enable this test for TPU. Currently tuples/dict don't work # as clone_model's input_tensors argument only seems to accept list and not # tuples or dict. @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_fit_with_tuple_and_dict_dataset_inputs(self, distribution): with self.cached_session(): with distribution.scope(): model = multi_input_output_model() optimizer = gradient_descent.GradientDescentOptimizer( learning_rate=0.001) loss = 'mse' metrics = ['mae', keras.metrics.CategoricalAccuracy()] model.compile(optimizer, loss, metrics=metrics) input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 5)) output_d_np = np.random.random((10, 7)) output_e_np = np.random.random((10, 7)) # Test with tuples dataset_tuple = dataset_ops.Dataset.from_tensor_slices(( (input_a_np, input_b_np), (output_d_np, output_e_np))) dataset_tuple = dataset_tuple.repeat(100) dataset_tuple = dataset_tuple.batch(10) model.fit(dataset_tuple, epochs=1, steps_per_epoch=2, verbose=1) # Test with dict dataset_dict = dataset_ops.Dataset.from_tensor_slices(( {'input_a': input_a_np, 'input_b': input_b_np}, (output_d_np, output_e_np))) dataset_dict = dataset_dict.repeat(100) dataset_dict = dataset_dict.batch(10) model.fit(dataset_dict, epochs=1, steps_per_epoch=2, verbose=1) @combinations.generate(all_strategy_combinations()) def test_fit_eval_and_predict_methods_on_dataset(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae', keras.metrics.CategoricalAccuracy()] model.compile(optimizer, loss, metrics=metrics) dataset = get_dataset(distribution) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) model.evaluate(dataset, steps=2, verbose=1) model.predict(get_predict_dataset(distribution), steps=2) @combinations.generate(strategy_and_optimizer_combinations()) def test_fit_eval_and_predict_with_optimizer(self, distribution, optimizer): with self.cached_session(): with distribution.scope(): model = get_model() loss = 'mse' model.compile(optimizer(), loss) dataset = get_dataset(distribution) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) model.evaluate(dataset, steps=2, verbose=1) model.predict(get_predict_dataset(distribution), steps=2) @combinations.generate(strategy_minus_tpu_combinations()) def test_dataset_with_sample_weights(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss) inputs = np.zeros((10, 3), np.float32) targets = np.zeros((10, 4), np.float32) sample_weights = np.ones((10), np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets, sample_weights)) dataset = dataset.repeat() dataset = dataset.batch(10) model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) model.evaluate(dataset, steps=2, verbose=1) model.predict(dataset, steps=2) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) # TODO(b/120943676, b/120957836): Re-enable once the validation code is # restored. def DISABLED_test_dataset_wrong_input_shape(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss) # Wrong input shape inputs = np.zeros((10, 5), dtype=np.float32) targets = np.zeros((10, 4), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat(100) dataset = dataset.batch(10) with self.assertRaisesRegexp(ValueError, 'expected input to have shape'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0) @combinations.generate(combinations.combine( distribution=[combinations.mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) # TODO(b/120943676, b/120957836): Re-enable once the validation code is # restored. def DISABLED_test_dataset_no_batch_input_validation(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss) # User forgets to batch the dataset inputs = np.zeros((10, 3), dtype=np.float32) targets = np.zeros((10, 4), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat(100) with self.assertRaisesRegexp(ValueError, 'expected input to have shape'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0) @combinations.generate(combinations.combine( distribution=[combinations.tpu_strategy_one_step], mode=['graph'])) def test_dataset_input_shape_fully_defined(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = rmsprop.RMSPropOptimizer(learning_rate=0.001) loss = 'mse' model.compile(optimizer, loss) dataset = get_dataset(distribution) # Input shapes are not fully known. Batch dimension is unknown as we are # not using the drop_remainder argument. dataset = dataset.repeat(100).batch(10) with self.assertRaisesRegexp(ValueError, 'requires fully defined shapes'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.mirrored_strategy_with_two_gpus, combinations.core_mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_two_gpus], mode=['graph', 'eager'])) def test_learning_phase_value(self, distribution): # TODO(anjalisridhar): Modify this test to use Lambdas since we can compare # meaningful values. Currently we don't pass the learning phase if the # Lambda layer uses the learning phase. with self.cached_session(): with distribution.scope(): x = keras.layers.Input(shape=(1,), name='input') y = keras.layers.Dense(1, kernel_initializer='ones')(x) z = keras.layers.Dropout(0.9999)(y) model = keras.Model(x, z) initial_weights = model.get_weights() optimizer = gradient_descent.GradientDescentOptimizer(0.005) loss = 'mse' metrics = ['acc'] model.compile(optimizer, loss, metrics=metrics) batch_size = 8 if isinstance(distribution, mirrored_strategy.CoreMirroredStrategy): # CoreMirroredStrategy uses global batch size. batch_size = 8 * distribution.num_replicas_in_sync inputs = np.ones((10, 1), dtype=np.float32) targets = np.ones((10, 1), dtype=np.float32) dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) dataset = dataset.repeat().batch(batch_size) hist = model.fit(dataset, epochs=1, steps_per_epoch=20, verbose=1) self.assertAlmostEqual(hist.history['acc'][0], 0, 0) with distribution.scope(): model.set_weights(initial_weights) # TODO(psv/anjalisridhar): Enable these lines after we fix b/117431185. # evaluate_output = model.evaluate(dataset, steps=20) # self.assertAlmostEqual(evaluate_output[1], 1, 0) inputs = np.ones((10, 1), dtype=np.float32) predict_dataset = dataset_ops.Dataset.from_tensor_slices(inputs) predict_dataset = predict_dataset.repeat().batch(batch_size) output = model.predict(predict_dataset, steps=10) # `predict` runs for 10 steps ref_output = np.ones((160, 1), dtype=np.float32) self.assertArrayNear(output, ref_output, 1e-1) @combinations.generate(all_strategy_combinations()) def testOptimizerWithCallbacks(self, distribution): with self.cached_session(): # TODO(b/120946189): Investigate why default strategy + eager fails. if '_Default' in distribution.__class__.__name__: self.skipTest('Disable the test for default strategy.') with distribution.scope(): model = get_model() optimizer = gradient_descent_keras.SGD(0.01) loss = 'mse' model.compile(optimizer, loss) dataset = get_dataset(distribution) def schedule(_): return 0.001 model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, callbacks=[keras.callbacks.LearningRateScheduler(schedule)]) self.assertAllClose(0.001, keras.backend.get_value(model.optimizer.lr)) class TestDistributionStrategyErrorCases(test.TestCase, parameterized.TestCase): @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_validating_dataset_input_tensors_with_shape_mismatch(self, distribution): with self.cached_session(): a = constant_op.constant([1, 2], shape=(1, 2)) b = constant_op.constant([[1, 2], [1, 2]], shape=(2, 2)) device_map = values.ReplicaDeviceMap(('/device:CPU:0', '/device:GPU:0')) x = values.DistributedValues(device_map, (a, b)) y = values.DistributedValues(device_map, (a, a)) # Removed device and input tensor shape details from the error message # since the order of the device and the corresponding input tensor shape # is not deterministic over different runs. with self.assertRaisesRegexp(ValueError, 'Input tensor shapes do not match for ' 'distributed tensor inputs ' 'DistributedValues:.+'): with distribution.scope(): distributed_training_utils.validate_distributed_dataset_inputs( distribution, x, y) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_validating_dataset_input_tensors_with_dtype_mismatch(self, distribution): with self.cached_session(): a = constant_op.constant([1, 2], shape=(1, 2), dtype=dtypes.int32) b = constant_op.constant([1, 2], shape=(1, 2), dtype=dtypes.float64) device_map = values.ReplicaDeviceMap(('/device:CPU:0', '/device:GPU:0')) x = values.DistributedValues(device_map, (a, b)) y = values.DistributedValues(device_map, (a, a)) # Removed device and input tensor dtype details from the error message # since the order of the device and the corresponding input tensor dtype # is not deterministic over different runs. with self.assertRaisesRegexp(ValueError, 'Input tensor dtypes do not match for ' 'distributed tensor inputs ' 'DistributedValues:.+'): with distribution.scope(): distributed_training_utils.validate_distributed_dataset_inputs( distribution, x, y) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_unsupported_features(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae'] model.compile(optimizer, loss, metrics=metrics) dataset = get_dataset(distribution) # Test with validation split with self.assertRaisesRegexp( ValueError, '`validation_split` argument is not ' 'supported when input `x` is a dataset or a ' 'dataset iterator.+'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, validation_split=0.5, validation_steps=2) # Test with sample weight. sample_weight = np.random.random((10,)) with self.assertRaisesRegexp( ValueError, '`sample_weight` argument is not supported when input ' '`x` is a dataset or a dataset iterator.'): model.fit( dataset, epochs=1, steps_per_epoch=2, verbose=0, sample_weight=sample_weight) # Test with not specifying the `steps` argument. with self.assertRaisesRegexp( ValueError, 'you should specify the `steps_per_epoch` argument'): model.fit(dataset, epochs=1, verbose=0) with self.assertRaisesRegexp(ValueError, 'you should specify the `steps` argument'): model.evaluate(dataset, verbose=0) with self.assertRaisesRegexp(ValueError, 'you should specify the `steps` argument'): model.predict(dataset, verbose=0) @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_calling_with_unsupported_predefined_callbacks(self, distribution): with self.cached_session(): with distribution.scope(): model = get_model() optimizer = gradient_descent.GradientDescentOptimizer(0.001) loss = 'mse' metrics = ['mae'] model.compile(optimizer, loss, metrics=metrics) dataset = get_dataset(distribution) def schedule(_): return 0.001 with self.assertRaisesRegexp(ValueError, 'You must specify a Keras Optimizer V2 when ' 'using'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, callbacks=[keras.callbacks.LearningRateScheduler(schedule)]) with self.assertRaisesRegexp(ValueError, 'You must specify a Keras Optimizer V2 when ' 'using'): model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=0, callbacks=[keras.callbacks.ReduceLROnPlateau()]) class TestDistributionStrategyWithLossMasking(test.TestCase, parameterized.TestCase): # TODO(priyag): Enable all strategies for this test. Currently it does not # work for TPU due to some invalid datatype. @combinations.generate(combinations.combine( distribution=[ combinations.mirrored_strategy_with_gpu_and_cpu, combinations.core_mirrored_strategy_with_gpu_and_cpu], mode=['graph', 'eager'])) def test_masking(self, distribution): with self.cached_session(): np.random.seed(1337) x = np.array([[[1], [1]], [[0], [0]]]) with distribution.scope(): model = keras.models.Sequential() model.add(keras.layers.Masking(mask_value=0, input_shape=(2, 1))) model.add( keras.layers.TimeDistributed( keras.layers.Dense(1, kernel_initializer='one'))) model.compile(loss='mse', optimizer=gradient_descent.GradientDescentOptimizer(0.01)) y = np.array([[[1], [1]], [[1], [1]]]) dataset = dataset_ops.Dataset.from_tensor_slices((x, y)) dataset = dataset.repeat(100) dataset = dataset.batch(10) hist = model.fit(x=dataset, epochs=1, steps_per_epoch=2) self.assertEqual(hist.history['loss'][0], 0) class TestDistributionStrategyWithNormalizationLayer( test.TestCase, parameterized.TestCase): @combinations.generate(all_strategy_combinations()) def test_batchnorm_correctness(self, distribution): with self.cached_session(): with distribution.scope(): model = keras.models.Sequential() norm = keras.layers.BatchNormalization(input_shape=(10,), momentum=0.8) model.add(norm) model.compile(loss='mse', optimizer=gradient_descent.GradientDescentOptimizer(0.01)) # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10)) x = x.astype('float32') dataset = dataset_ops.Dataset.from_tensor_slices((x, x)) dataset = dataset.repeat(100) dataset = batch_wrapper(dataset, 32, distribution) predict_dataset = dataset_ops.Dataset.from_tensor_slices(x) predict_dataset = predict_dataset.repeat(100) predict_dataset = batch_wrapper(predict_dataset, 32, distribution) model.fit(dataset, epochs=4, verbose=0, steps_per_epoch=10) out = model.predict(predict_dataset, steps=2) out -= keras.backend.eval(norm.beta) out /= keras.backend.eval(norm.gamma) np.testing.assert_allclose(out.mean(), 0.0, atol=1e-1) np.testing.assert_allclose(out.std(), 1.0, atol=1e-1) if __name__ == '__main__': test.main()
{ "content_hash": "5cced43cb9e87d1bffee71cc4d8a4dea", "timestamp": "", "source": "github", "line_count": 1138, "max_line_length": 91, "avg_line_length": 41.83743409490334, "alnum_prop": 0.6543865913339354, "repo_name": "Bismarrck/tensorflow", "id": "84e9aea228352e0a6010fe95529407818d020b5f", "size": "48300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/contrib/distribute/python/keras_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4882" }, { "name": "Batchfile", "bytes": "10132" }, { "name": "C", "bytes": "493885" }, { "name": "C#", "bytes": "8446" }, { "name": "C++", "bytes": "53117668" }, { "name": "CMake", "bytes": "207176" }, { "name": "Dockerfile", "bytes": "39024" }, { "name": "Go", "bytes": "1303624" }, { "name": "HTML", "bytes": "4680032" }, { "name": "Java", "bytes": "893928" }, { "name": "Jupyter Notebook", "bytes": "2657814" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "68402" }, { "name": "Objective-C", "bytes": "16140" }, { "name": "Objective-C++", "bytes": "102511" }, { "name": "PHP", "bytes": "5172" }, { "name": "Pascal", "bytes": "221" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "43480067" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "838" }, { "name": "Shell", "bytes": "497472" }, { "name": "Smarty", "bytes": "6976" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="Underdomain" table="underdomain"> <id name="id" type="integer" column="id"> <generator strategy="IDENTITY"/> </id> <field name="label" type="string" column="label" length="45" nullable="true"/> <many-to-one field="domain" target-entity="Domain"> <join-columns> <join-column name="domain_id" referenced-column-name="id"/> </join-columns> </many-to-one> </entity> </doctrine-mapping>
{ "content_hash": "bfce70077a8128b6b1abbad8434a0c01", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 276, "avg_line_length": 54.42857142857143, "alnum_prop": 0.6902887139107612, "repo_name": "wbi0737/wbisocial", "id": "3ae0b1410a98eacf821b625258e73aceb076f7c7", "size": "762", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Wbi/ForumBundle/Resources/config/doctrine/metadata/orm/Underdomain.orm.xml", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "114747" }, { "name": "PHP", "bytes": "100640" } ], "symlink_target": "" }
using Microsoft.CodeAnalysis.CodeFixes; using System.Collections.Immutable; using System.Threading.Tasks; namespace Microsoft.NetCore.Analyzers.Runtime { /// <summary> /// CA2215: Dispose Methods Should Call Base Class Dispose /// </summary> public abstract class DisposeMethodsShouldCallBaseClassDisposeFixer : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(DisposeMethodsShouldCallBaseClassDispose.RuleId); public sealed override FixAllProvider GetFixAllProvider() { // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers return WellKnownFixAllProviders.BatchFixer; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { // Fixer not yet implemented. return Task.CompletedTask; } } }
{ "content_hash": "56285a38ccb10e9afc5c225609d09cb4", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 157, "avg_line_length": 36.370370370370374, "alnum_prop": 0.7169042769857433, "repo_name": "dotnet/roslyn-analyzers", "id": "9f0670d1993f221055caacffb56b0f41bbd322b4", "size": "1128", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeMethodsShouldCallBaseClassDispose.Fixer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2423" }, { "name": "C#", "bytes": "15365655" }, { "name": "CMake", "bytes": "12939" }, { "name": "PowerShell", "bytes": "181309" }, { "name": "Shell", "bytes": "115733" }, { "name": "Visual Basic .NET", "bytes": "276464" } ], "symlink_target": "" }
SimpleForm.setup do |config| # Wrappers are used by the form builder to generate a # complete input. You can remove any component from the # wrapper, change the order or even add your own to the # stack. The options given below are used to wrap the # whole input. config.wrappers :default, class: :input, hint_class: :field_with_hint, error_class: :field_with_errors do |b| ## Extensions enabled by default # Any of these extensions can be disabled for a # given input by passing: `f.input EXTENSION_NAME => false`. # You can make any of these extensions optional by # renaming `b.use` to `b.optional`. # Determines whether to use HTML5 (:email, :url, ...) # and required attributes b.use :html5 # Calculates placeholders automatically from I18n # You can also pass a string as f.input placeholder: "Placeholder" b.use :placeholder ## Optional extensions # They are disabled unless you pass `f.input EXTENSION_NAME => true` # to the input. If so, they will retrieve the values from the model # if any exists. If you want to enable any of those # extensions by default, you can change `b.optional` to `b.use`. # Calculates maxlength from length validations for string inputs b.optional :maxlength # Calculates pattern from format validations for string inputs b.optional :pattern # Calculates min and max from length validations for numeric inputs b.optional :min_max # Calculates readonly automatically from readonly attributes b.optional :readonly ## Inputs b.use :label_input b.use :hint, wrap_with: { tag: :span, class: :hint } b.use :error, wrap_with: { tag: :span, class: :error } ## full_messages_for # If you want to display the full error message for the attribute, you can # use the component :full_error, like: # # b.use :full_error, wrap_with: { tag: :span, class: :error } end # The default wrapper to be used by the FormBuilder. config.default_wrapper = :default # Define the way to render check boxes / radio buttons with labels. # Defaults to :nested for bootstrap config. # inline: input + label # nested: label > input config.boolean_style = :nested # Default class for buttons config.button_class = 'btn' # Method used to tidy up errors. Specify any Rails Array method. # :first lists the first message for each field. # Use :to_sentence to list all errors for each field. config.error_method = :first # Default tag used for error notification helper. config.error_notification_tag = :div # CSS class to add for error notification helper. config.error_notification_class = 'error_notification' # ID to add for error notification helper. # config.error_notification_id = nil # Series of attempts to detect a default label method for collection. # config.collection_label_methods = [ :to_label, :name, :title, :to_s ] # Series of attempts to detect a default value method for collection. # config.collection_value_methods = [ :id, :to_s ] # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none. # config.collection_wrapper_tag = nil # You can define the class to use on all collection wrappers. Defaulting to none. # config.collection_wrapper_class = nil # You can wrap each item in a collection of radio/check boxes with a tag, # defaulting to :span. # config.item_wrapper_tag = :span # You can define a class to use in all item wrappers. Defaulting to none. # config.item_wrapper_class = nil # How the label text should be generated altogether with the required text. # config.label_text = lambda { |label, required, explicit_label| "#{required} #{label}" } # You can define the class to use on all labels. Default is nil. # config.label_class = nil # You can define the default class to be used on forms. Can be overriden # with `html: { :class }`. Defaulting to none. # config.default_form_class = nil # You can define which elements should obtain additional classes # config.generate_additional_classes_for = [:wrapper, :label, :input] # Whether attributes are required by default (or not). Default is true. # config.required_by_default = true # Tell browsers whether to use the native HTML5 validations (novalidate form option). # These validations are enabled in SimpleForm's internal config but disabled by default # in this configuration, which is recommended due to some quirks from different browsers. # To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations, # change this configuration to true. config.browser_validations = false # Collection of methods to detect if a file type was given. # config.file_methods = [ :mounted_as, :file?, :public_filename ] # Custom mappings for input types. This should be a hash containing a regexp # to match as key, and the input type that will be used when the field name # matches the regexp as value. # config.input_mappings = { /count/ => :integer } # Custom wrappers for input types. This should be a hash containing an input # type as key and the wrapper that will be used for all inputs with specified type. # config.wrapper_mappings = { string: :prepend } # Namespaces where SimpleForm should look for custom input classes that # override default inputs. # config.custom_inputs_namespaces << "CustomInputs" # Default priority for time_zone inputs. # config.time_zone_priority = nil # Default priority for country inputs. # config.country_priority = nil # When false, do not use translations for labels. # config.translate_labels = true # Automatically discover new inputs in Rails' autoload path. # config.inputs_discovery = true # Cache SimpleForm inputs discovery # config.cache_discovery = !Rails.env.development? # Default class for inputs # config.input_class = nil # Define the default class of the input wrapper of the boolean input. config.boolean_label_class = 'checkbox' # Defines if the default input wrapper class should be included in radio # collection wrappers. # config.include_default_input_wrapper_class = true # Defines which i18n scope will be used in Simple Form. # config.i18n_scope = 'simple_form' end
{ "content_hash": "2112dfc07aef85e98bed16002b7a4d7b", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 93, "avg_line_length": 38.55487804878049, "alnum_prop": 0.7162739206073067, "repo_name": "skoona/SknServices", "id": "e00d50ad4030f9c71ba1636945c648fa2333fa0e", "size": "6396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/initializers/simple_form.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18733" }, { "name": "HTML", "bytes": "222948" }, { "name": "JavaScript", "bytes": "131833" }, { "name": "Ruby", "bytes": "461206" }, { "name": "Shell", "bytes": "342" } ], "symlink_target": "" }
<!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"> <title>Jorge Sanz - Portfolio Webpage</title> <!-- Bootstrap --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <link href="css/main.css" rel="stylesheet"> <!-- Icons --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Fonts --> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,600,400italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Cousine:400,700' rel='stylesheet' type='text/css'> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </head> <body> <!-- Navbar --> <nav class="navbar navbar-inverse navbar-fixed-top" id="top-navbar"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">JS</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul id="navbar-menu" class="nav navbar-nav navbar-right"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <!-- Header --> <div id="header" class="jumbotron"> <div class="container"> <img src="/img/header/jorge.jpg" id="avatar" class="img-circle center-block"> <p id="name">Jorge Sanz</p> <p id="i-love">I <i class="material-icons" id="heart">favorite</i> <span class="element"></span></p> </div> </div> <!-- About --> <div id="about"> <div class="container"> <div id="about-me-content"> <div class="row"> <div class="col-md-6" id="about-me-first-half"> <p class="about-me-label" id="about-me-label">ABOUT ME.</p> <div id="about-me-labels-container"> <p class="about-me-label about-me-roles">SOFTWARE ENGINEER.</p> <p class="about-me-label about-me-roles">TECH ENTHUSIAST.</p> <p class="about-me-label about-me-roles">DESIGNER.</p> <p class="about-me-label about-me-roles">CREATIVE.</p> <p class="about-me-label about-me-roles">ENTREPRENEUR.</p> <p class="about-me-label about-me-roles">BUSINESS GEEK.</p> </div> </div> <div class="col-md-6"> </div> </div> </div> </div> </div> <!-- Portfolio --> <div id="portfolio-container" class="container"> <!-- Example row of columns --> <div> <p id="work-label">WORK.</p> <div id="projects-container"> <div class="row"> <div class="col-md-4 project"> <a href="http://jorge-sanz.github.io/tribute-page/"><img class="project-preview-image" src="./img/portfolio/steve-jobs.png"></a> <a href="http://jorge-sanz.github.io/tribute-page/"><p class="project-title">Tribute Page</p></a> </div> <div class="col-md-4"> <a href="http://jorge-sanz.github.io/"><img class="project-preview-image" src="./img/portfolio/portfolio-webpage.png"></a> <a href="http://jorge-sanz.github.io/"><p class="project-title">Personal Portfolio</p></a> </div> <div class="col-md-4"> </div> </div> </div> </div> </div> <!-- Pictures --> <div id="pictures-container" class="container-fluid"> <img class="img-responsive" id="me-picture" src="./img/pics/me.jpg"/> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="/js/jquery-2.2.4.min.js"></script> <script src="/js/typed.js"></script> <script> $(function(){ $(".element").typed({ strings: ["Software", "Mobile", "Web", "AI", "Open Source", "Design", "Creating."], typeSpeed: 60, backSpeed: 30, }); }); </script> </body> </html>
{ "content_hash": "45fcbd48b2eeda6cd14ac9a93fde8e8c", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 154, "avg_line_length": 39.75409836065574, "alnum_prop": 0.5492783505154639, "repo_name": "jorge-sanz/jorge-sanz.github.io", "id": "a9ec2cb81265b9e83532861d7d8ca0be0bdd4db2", "size": "4850", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2580" }, { "name": "HTML", "bytes": "4850" }, { "name": "JavaScript", "bytes": "15615" } ], "symlink_target": "" }
namespace syncer { DataTypeDebugInfoEmitter::DataTypeDebugInfoEmitter( ModelType type, base::ObserverList<TypeDebugInfoObserver>* observers) : type_(type), type_debug_info_observers_(observers) {} DataTypeDebugInfoEmitter::~DataTypeDebugInfoEmitter() {} const CommitCounters& DataTypeDebugInfoEmitter::GetCommitCounters() const { return commit_counters_; } CommitCounters* DataTypeDebugInfoEmitter::GetMutableCommitCounters() { return &commit_counters_; } void DataTypeDebugInfoEmitter::EmitCommitCountersUpdate() { for (auto& observer : *type_debug_info_observers_) observer.OnCommitCountersUpdated(type_, commit_counters_); } const UpdateCounters& DataTypeDebugInfoEmitter::GetUpdateCounters() const { return update_counters_; } UpdateCounters* DataTypeDebugInfoEmitter::GetMutableUpdateCounters() { return &update_counters_; } void DataTypeDebugInfoEmitter::EmitUpdateCountersUpdate() { for (auto& observer : *type_debug_info_observers_) observer.OnUpdateCountersUpdated(type_, update_counters_); } } // namespace syncer
{ "content_hash": "8e78d5c3dd88df510e793c8a0cda05ea", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 75, "avg_line_length": 29.61111111111111, "alnum_prop": 0.7823639774859287, "repo_name": "Samsung/ChromiumGStreamerBackend", "id": "68c3a174b84917287b0e2bea211063188fe9dbf0", "size": "1377", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "components/sync/engine_impl/cycle/data_type_debug_info_emitter.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.douwe.notes.projection; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Kenfack Valmy-Roi <roykenvalmy@gmail.com> */ @XmlRootElement public class AuthAccessElement implements Serializable{ public static final String PARAM_AUTH_ID = "auth-id"; public static final String PARAM_AUTH_TOKEN = "auth-token"; private String authId; private String authToken; private String authPermission; public AuthAccessElement() { } public AuthAccessElement(String authId, String authToken, String authPermission) { this.authId = authId; this.authToken = authToken; this.authPermission = authPermission; } public String getAuthId() { return authId; } public void setAuthId(String authId) { this.authId = authId; } public String getAuthToken() { return authToken; } public void setAuthToken(String authToken) { this.authToken = authToken; } public String getAuthPermission() { return authPermission; } public void setAuthPermission(String authPermission) { this.authPermission = authPermission; } }
{ "content_hash": "a8671a8a3a49bf7f3ccf4b0580ad9c49", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 86, "avg_line_length": 22.685185185185187, "alnum_prop": 0.6718367346938775, "repo_name": "infotel-iss/notesBackend", "id": "bf0a61062d4e0e740c92b04fcc711c64c0112399", "size": "1225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/douwe/notes/projection/AuthAccessElement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12357" }, { "name": "HTML", "bytes": "147209" }, { "name": "Java", "bytes": "718770" }, { "name": "JavaScript", "bytes": "347997" } ], "symlink_target": "" }
import ChoiceQuestionBase from './ChoiceQuestionBase'; /** 設問:複数選択肢 */ export default class CheckboxQuestion extends ChoiceQuestionBase { constructor(props) { super(props, 'checkbox'); } }
{ "content_hash": "1af1389d356de78f9a07032a34af3f61", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 66, "avg_line_length": 24.75, "alnum_prop": 0.7373737373737373, "repo_name": "jirokun/survey-designer-js", "id": "62e9124921b5ff0bcc13442c0ed6d979b52d2abc", "size": "214", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/runtime/components/questions/CheckboxQuestion.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1004803" }, { "name": "Less", "bytes": "15659" }, { "name": "SCSS", "bytes": "41755" } ], "symlink_target": "" }
package org.jzb.execution.infrastructure.persistence.jpa; import org.jzb.execution.domain.Enlist; import org.jzb.execution.domain.EnlistFeedback; import org.jzb.execution.domain.repository.EnlistFeedbackRepository; import javax.enterprise.context.ApplicationScoped; import java.util.stream.Stream; /** * Created by jzb on 17-2-27. */ @ApplicationScoped public class JpaEnlistFeedbackRepository extends JpaCURDRepository<EnlistFeedback, String> implements EnlistFeedbackRepository { @Override public Stream<EnlistFeedback> queryBy(Enlist enlist) { return em.createNamedQuery("EnlistFeedback.queryByEnlist") .setParameter("enlist", enlist) .getResultList() .stream(); } }
{ "content_hash": "ad7234691197b56316a3d589e7c39278", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 128, "avg_line_length": 33.77272727272727, "alnum_prop": 0.746971736204576, "repo_name": "ixtf/japp-execution", "id": "84be6630c9ceded62e56377a00991bc7d945a2ad", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/main/java/org/jzb/execution/infrastructure/persistence/jpa/JpaEnlistFeedbackRepository.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "18480" }, { "name": "Dockerfile", "bytes": "263" }, { "name": "HTML", "bytes": "102279" }, { "name": "Java", "bytes": "586492" }, { "name": "JavaScript", "bytes": "1644" }, { "name": "TypeScript", "bytes": "530073" } ], "symlink_target": "" }
"""Init module for TensorFlow Model Analysis model_agnostic_eval.""" from tensorflow_model_analysis.model_agnostic_eval import model_agnostic_evaluate_graph from tensorflow_model_analysis.model_agnostic_eval import model_agnostic_extractor from tensorflow_model_analysis.model_agnostic_eval import model_agnostic_predict
{ "content_hash": "24acc19fd6a2061a4ed58e08b1f7199d", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 87, "avg_line_length": 64.4, "alnum_prop": 0.8416149068322981, "repo_name": "tensorflow/model-analysis", "id": "8d784bf9fb55f515fed2e6c1e393506f504c7caf", "size": "897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow_model_analysis/model_agnostic_eval/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "125312" }, { "name": "JavaScript", "bytes": "1415355" }, { "name": "Python", "bytes": "3261298" }, { "name": "Shell", "bytes": "813" }, { "name": "Starlark", "bytes": "11590" } ], "symlink_target": "" }
namespace content { IndexedDBLevelDBEnv::IndexedDBLevelDBEnv() : ChromiumEnv("LevelDBEnv.IDB", storage::CreateFilesystemProxy()) {} IndexedDBLevelDBEnv* IndexedDBLevelDBEnv::Get() { static base::NoDestructor<IndexedDBLevelDBEnv> g_leveldb_env; return g_leveldb_env.get(); } } // namespace content
{ "content_hash": "03f83104ce04c528ba7b703589895558", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 72, "avg_line_length": 28.09090909090909, "alnum_prop": 0.7605177993527508, "repo_name": "chromium/chromium", "id": "20aa0a1a258d7a4f4ce150ac192807583f901835", "size": "616", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "content/browser/indexed_db/indexed_db_leveldb_env.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.apache.camel.jsonpath; import java.io.File; import java.util.Map; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class JsonPathSplitWriteAsStringMapTest extends CamelTestSupport { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .split().jsonpathWriteAsString("$.content") .to("mock:line") .to("log:line") .end(); } }; } @Test public void testSplitToJSon() throws Exception { MockEndpoint mock = getMockEndpoint("mock:line"); mock.expectedMessageCount(2); template.sendBody("direct:start", new File("src/test/resources/content-map.json")); assertMockEndpointsSatisfied(); Map.Entry<?, ?> row = mock.getReceivedExchanges().get(0).getIn().getBody(Map.Entry.class); assertEquals("foo", row.getKey()); assertEquals("{\"action\":\"CU\",\"id\":123,\"modifiedTime\":\"2015-07-28T11:40:09.520+02:00\"}", row.getValue()); row = mock.getReceivedExchanges().get(1).getIn().getBody(Map.Entry.class); assertEquals("bar", row.getKey()); assertEquals("{\"action\":\"CU\",\"id\":456,\"modifiedTime\":\"2015-07-28T11:42:29.510+02:00\"}", row.getValue()); } }
{ "content_hash": "a4582a4ad184ee10c83e05f46a795c5f", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 122, "avg_line_length": 34.0625, "alnum_prop": 0.618960244648318, "repo_name": "cunningt/camel", "id": "b826d80b8ccbf9970234defc9541e177c08bf7b6", "size": "2437", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitWriteAsStringMapTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6695" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Dockerfile", "bytes": "5676" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "396363" }, { "name": "HTML", "bytes": "212954" }, { "name": "Java", "bytes": "113234282" }, { "name": "JavaScript", "bytes": "103655" }, { "name": "Jsonnet", "bytes": "1734" }, { "name": "Kotlin", "bytes": "41869" }, { "name": "Mustache", "bytes": "525" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Ruby", "bytes": "88" }, { "name": "Shell", "bytes": "15221" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "699" }, { "name": "XSLT", "bytes": "276597" } ], "symlink_target": "" }
CampaignRetargetingListPage object holds results (list of all entities) of mutate method on Target List settings for campaign layer. ### Service + [CampaignRetargetingListService](../../services/CampaignRetargetingListService.md) ### Namespace [CampaignRetargetingListService#Namespace](../../services/CampaignRetargetingListService.md#namespace) ### Inheritance + [ListReturnValue](../Common/ListReturnValue.md) <table> <tr> <th>Field</th> <th>Type</th> <th>Description</th> </tr> <tr> <td>values[0..1000]</td> <td><a href="CampaignRetargetingListValues.md">CampaignRetargetingListValues</a></td> <td>Result of mutate method (list of all entities)</td> </tr> </table> <a rel="license" href="http://creativecommons.org/licenses/by-nd/2.1/jp/"><img alt="クリエイティブ・コモンズ・ライセンス" style="border-width:0" src="https://i.creativecommons.org/l/by-nd/2.1/jp/88x31.png" /></a><br />この 作品 は <a rel="license" href="http://creativecommons.org/licenses/by-nd/2.1/jp/">クリエイティブ・コモンズ 表示 - 改変禁止 2.1 日本 ライセンスの下に提供されています。</a>
{ "content_hash": "394d74104af6aecb1485fd40fa656219", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 333, "avg_line_length": 40.96, "alnum_prop": 0.728515625, "repo_name": "yahoojp-marketing/sponsored-search-api-documents", "id": "f3a88e2101b477f5b393c1702c9ee729f89d26d2", "size": "1181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/en/api_reference/data/CampaignRetargetingList/CampaignRetargetingListReturnValue.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.sweethearts.spring.example; import com.sweethearts.spring.example.respository.AccountRepository; import com.sweethearts.spring.example.respository.BookmarkRepository; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = RestApplication.class) @WebAppConfiguration public class BookmarkRestControllerTest { private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); private MockMvc mockMvc; private String userName = "bdussault"; private HttpMessageConverter mappingJackson2HttpMessageConverter; private Account account; private List<Bookmark> bookmarkList = new ArrayList<>(); @Autowired private BookmarkRepository bookmarkRepository; @Autowired private AccountRepository accountRepository; @Autowired private WebApplicationContext webApplicationContext; @Autowired void setConverters(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.asList(converters) .stream() .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter) .findAny() .get(); Assert.assertNotNull("the JSON message converter must not be null", this.mappingJackson2HttpMessageConverter); } @Before public void setUp() throws Exception { this.mockMvc = webAppContextSetup(webApplicationContext).build(); this.bookmarkRepository.deleteAllInBatch(); this.accountRepository.deleteAllInBatch(); this.account = accountRepository.save(new Account(userName, "password")); this.bookmarkList.add(bookmarkRepository.save(new Bookmark(account, "http://bookmark.com/1/" + userName, "A description"))); this.bookmarkList.add(bookmarkRepository.save(new Bookmark(account, "http://bookmark.com/2/" + userName, "A description"))); } @Test public void userNotFound() throws Exception { mockMvc.perform(post("/george/bookmarks/") .content(this.json(new Bookmark())) .contentType(contentType)) .andExpect(status().isNotFound()); } @Test public void readSingleBookmark() throws Exception { mockMvc.perform(get("/" + userName + "/bookmarks/" + this.bookmarkList.get(0).getId())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.id", is(this.bookmarkList.get(0).getId().intValue()))) .andExpect(jsonPath("$.uri", is("http://bookmark.com/1/" + userName))) .andExpect(jsonPath("$.description", is("A description"))); } protected String json(Object o) throws IOException { MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage(); this.mappingJackson2HttpMessageConverter.write( o, MediaType.APPLICATION_JSON, mockHttpOutputMessage); return mockHttpOutputMessage.getBodyAsString(); } }
{ "content_hash": "ffb67c8cf83bd05a23c91d4f04d97a86", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 126, "avg_line_length": 38.148148148148145, "alnum_prop": 0.7983009708737864, "repo_name": "zzragida/SpringExamples", "id": "5168bc938a48cb8595288de0285f81d06d95c4da", "size": "4120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RestBookmark/src/test/java/com/sweethearts/spring/example/BookmarkRestControllerTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "570" }, { "name": "Java", "bytes": "31368" } ], "symlink_target": "" }
FROM ghost # Default environment variables ENV GHOST_URL http://pracujeibloguje.pl ENV GHOST_HOME /usr/src/ghost ENV THEMES_HOME $GHOST_HOME/content/themes ADD config.example.js $GHOST_HOME/ ADD ghostium $THEMES_HOME/ghostium/ # Fix ownership in src RUN chown -R user $GHOST_SOURCE/content
{ "content_hash": "389504af03cd6698344da5f84c2bf453", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 42, "avg_line_length": 24.416666666666668, "alnum_prop": 0.7849829351535836, "repo_name": "sdwsk/search-examples", "id": "cbbae175abd4885e3b429d9ffcb194cfa95b3c39", "size": "293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docker/dockerfiles.bkp/old/blog/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33000" }, { "name": "Groovy", "bytes": "51466" }, { "name": "HTML", "bytes": "39428" }, { "name": "Java", "bytes": "1552" }, { "name": "JavaScript", "bytes": "45815" }, { "name": "Python", "bytes": "368" }, { "name": "Ruby", "bytes": "77" }, { "name": "Shell", "bytes": "389" }, { "name": "XSLT", "bytes": "24966" } ], "symlink_target": "" }
Spreadsheet converter framework for Lua from .NET ----- ## Usage ``` $ convsheet (XLSXFile) (SheetID) (Options) (Options): -csv: Output CSV files -dir=PATH: Set output directory ``` ----- ## Acknowledgment NPOI - Xslx file reading - https://npoi.codeplex.com/ Moonsharp - Useful Lua implementation in .NET - http://www.moonsharp.org/
{ "content_hash": "ba2c6823e95e77b3b439b1148a8bcaef", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 73, "avg_line_length": 15.478260869565217, "alnum_prop": 0.6629213483146067, "repo_name": "futsuki/convsheet", "id": "c06d6abaf7ea35c20bda6ca4b90645b5de555555", "size": "368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "33537" }, { "name": "Lua", "bytes": "2480" } ], "symlink_target": "" }
#ifndef _TCULIBDRM_HPP #define _TCULIBDRM_HPP /*! * \file * \brief Drm utilities. *//*--------------------------------------------------------------------*/ #if DEQP_SUPPORT_DRM && !defined (CTS_USES_VULKANSC) #include "deDynamicLibrary.hpp" #include "deUniquePtr.hpp" #include <xf86drm.h> #include <xf86drmMode.h> namespace tcu { class LibDrm : protected de::DynamicLibrary { typedef void (*FdDeleter) (int*); typedef void (*PFNDRMMODEFREERESOURCESPROC) (drmModeRes*); typedef void (*PFNDRMMODEFREECONNECTORPROC) (drmModeConnector*); typedef void (*PFNDRMMODEFREEENCODERPROC) (drmModeEncoder*); public: typedef de::UniquePtr<int, FdDeleter> FdPtr; typedef de::UniquePtr<drmModeRes, PFNDRMMODEFREERESOURCESPROC> ResPtr; typedef de::UniquePtr<drmModeConnector, PFNDRMMODEFREECONNECTORPROC> ConnectorPtr; typedef de::UniquePtr<drmModeEncoder, PFNDRMMODEFREEENCODERPROC> EncoderPtr; LibDrm (void); virtual ~LibDrm (void); drmDevicePtr* getDevices (int *pNumDevices) const; const char* findDeviceNode (drmDevicePtr *devices, int count, deInt64 major, deInt64 minor) const; void freeDevices (drmDevicePtr *devices, int count) const; FdPtr openFd (const char* node) const; ResPtr getResources (int fd) const; ConnectorPtr getConnector (int fd, deUint32 connectorId) const; EncoderPtr getEncoder (int fd, deUint32 encoderId) const; FdPtr createLease (int fd, const deUint32 *objects, int numObjects, int flags) const; int authMagic (int fd, drm_magic_t magic) const; private: int intGetDevices(drmDevicePtr devices[], int maxDevices) const; static const char* libDrmFiles[]; typedef int (*PFNDRMGETDEVICES2PROC) (deUint32, drmDevicePtr[], int); typedef int (*PFNDRMGETDEVICESPROC) (drmDevicePtr[], int); typedef void (*PFNDRMFREEDEVICESPROC) (drmDevicePtr[], int); typedef drmModeRes* (*PFNDRMMODEGETRESOURCESPROC) (int); typedef drmModeConnector* (*PFNDRMMODEGETCONNECTORPROC) (int, deUint32); typedef drmModeEncoder* (*PFNDRMMODEGETENCODERPROC) (int, deUint32); typedef int (*PFNDRMMODECREATELEASEPROC) (int, const deUint32*, int, int, deUint32*); typedef int (*PFNDRMAUTHMAGIC) (int, drm_magic_t); PFNDRMGETDEVICES2PROC pGetDevices2; PFNDRMGETDEVICESPROC pGetDevices; PFNDRMFREEDEVICESPROC pFreeDevices; PFNDRMMODEGETRESOURCESPROC pGetResources; PFNDRMMODEGETCONNECTORPROC pGetConnector; PFNDRMMODEGETENCODERPROC pGetEncoder; PFNDRMMODEFREERESOURCESPROC pFreeResources; PFNDRMMODEFREECONNECTORPROC pFreeConnector; PFNDRMMODEFREEENCODERPROC pFreeEncoder; PFNDRMMODECREATELEASEPROC pCreateLease; PFNDRMAUTHMAGIC pAuthMagic; }; } // tcu #endif // DEQP_SUPPORT_DRM && !defined (CTS_USES_VULKANSC) #endif // _TCULIBDRM_HPP
{ "content_hash": "cbe92c564d9fd144686509c83eacb2d3", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 100, "avg_line_length": 35.58441558441559, "alnum_prop": 0.7456204379562044, "repo_name": "KhronosGroup/VK-GL-CTS", "id": "2868392524b46f805a0984578362346564d637da", "size": "3501", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "framework/common/tcuLibDrm.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "320" }, { "name": "C", "bytes": "603883" }, { "name": "C++", "bytes": "23597354" }, { "name": "CMake", "bytes": "120882" }, { "name": "HTML", "bytes": "67517" }, { "name": "Java", "bytes": "246628" }, { "name": "Makefile", "bytes": "89529" }, { "name": "Objective-C", "bytes": "10922" }, { "name": "Objective-C++", "bytes": "19107" }, { "name": "Python", "bytes": "644096" }, { "name": "Shell", "bytes": "2672" } ], "symlink_target": "" }
// Provides control sap.ui.ux3.OverlayContainer. sap.ui.define(['jquery.sap.global', './Overlay', './library'], function(jQuery, Overlay, library) { "use strict"; /** * Constructor for a new OverlayContainer. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * Is to be embedded into the Overlay control as content container * @extends sap.ui.ux3.Overlay * * @author SAP SE * @version 1.36.6 * * @constructor * @public * @alias sap.ui.ux3.OverlayContainer * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var OverlayContainer = Overlay.extend("sap.ui.ux3.OverlayContainer", /** @lends sap.ui.ux3.OverlayContainer.prototype */ { metadata : { library : "sap.ui.ux3", defaultAggregation : "content", aggregations : { /** * Aggregation for content */ content : {type : "sap.ui.core.Control", multiple : true, singularName : "content"} } }}); /** * Focus Last Element * * @private */ OverlayContainer.prototype._setFocusLast = function() { var oFocus = this.$("content").lastFocusableDomRef(); if (!oFocus && this.getCloseButtonVisible()) { oFocus = this.getDomRef("close"); } else if (!oFocus && this.getOpenButtonVisible()) { oFocus = this.getDomRef("openNew"); } jQuery.sap.focus(oFocus); }; /** * Focus First Element * * @private */ OverlayContainer.prototype._setFocusFirst = function() { if (this.getOpenButtonVisible()) { jQuery.sap.focus(this.getDomRef("openNew")); } else if (this.getCloseButtonVisible()) { jQuery.sap.focus(this.getDomRef("close")); } else { jQuery.sap.focus(this.$("content").firstFocusableDomRef()); } }; return OverlayContainer; }, /* bExport= */ true);
{ "content_hash": "a0ecc72f943602edddaf86dc5f55e80d", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 136, "avg_line_length": 25.794520547945204, "alnum_prop": 0.6648964418481147, "repo_name": "zaveryukha/openui5_demo", "id": "04e0e227963cdd15c4a43c0f4bdf00989d060973", "size": "2068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc_root/resources/sap_library/sap/ui/ux3/OverlayContainer-dbg.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4638706" }, { "name": "HTML", "bytes": "77356" }, { "name": "JavaScript", "bytes": "32024699" }, { "name": "Nginx", "bytes": "1629" } ], "symlink_target": "" }
// <copyright file="TransportSubscriptionCardPriceCalculator.cs" company="Automate The Planet Ltd."> // Copyright 2016 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>http://automatetheplanet.com/</site> using System; namespace TestingTechniques.UnitTests { public static class TransportSubscriptionCardPriceCalculator { /* * >= 5 years - free * 5 >= 18 years - 20 lv * > 18 - 40 lv * >= 65 - 5 lv */ public static decimal CalculateSubscriptionPrice(string ageInput) { var subscriptionPrice = default(decimal); var age = default(int); var isInteger = int.TryParse(ageInput, out age); if (!isInteger) { throw new ArgumentException("The age input should be an integer value between 0 - 122."); } if (age <= 0) { throw new ArgumentException("The age should be greater than zero."); } else if (age > 0 && age <= 5) { subscriptionPrice = 0; } else if (age > 5 && age <= 18) { subscriptionPrice = 20; } else if (age > 18 && age < 65) { subscriptionPrice = 40; } else if (age >= 65 && age <= 122) { subscriptionPrice = 5; } else { throw new ArgumentException("The age should be smaller than 123."); } return subscriptionPrice; } } }
{ "content_hash": "d2fc631027bc42064ed7b02834c8ec0c", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 105, "avg_line_length": 33.5, "alnum_prop": 0.5581184984170059, "repo_name": "angelovstanton/AutomateThePlanet", "id": "9b5dd4b3c3a6b86a1365025db40d0a5177cba880", "size": "2213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dotnet/TestingTechniques-Series/TestingTechniques.UnitTests/TransportSubscriptionCardPriceCalculator.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "5412058" }, { "name": "Gherkin", "bytes": "5274" }, { "name": "HTML", "bytes": "144064" }, { "name": "JavaScript", "bytes": "1250402" }, { "name": "PowerShell", "bytes": "33290" }, { "name": "Puppet", "bytes": "112" } ], "symlink_target": "" }
package com.enonic.plugin; import com.enonic.cms.api.client.Client; import com.enonic.cms.api.plugin.PluginConfig; import com.enonic.cms.api.plugin.PluginEnvironment; import com.enonic.cms.api.plugin.ext.http.HttpAutoLogin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.List; @Component public class AutoLoginImpl extends HttpAutoLogin { Logger LOG = LoggerFactory.getLogger(getClass()); @Autowired Client client; @Autowired PluginEnvironment pluginEnvironment; PluginConfig pluginConfig; @Autowired public void setPluginConfig(List<PluginConfig> pluginConfig) { //TODO: temporary necessary hack with List<PluginConfig> autowireing here this.pluginConfig = pluginConfig.get(0); } public AutoLoginImpl(){ setDisplayName("Example HttpAutoLogin implementation"); setUrlPattern("/site/0/.*"); } @Override public String getAuthenticatedUser(HttpServletRequest request) throws Exception { LOG.info(getDisplayName()); LOG.info("Login admin on site 0"); client.logout(); //return "default\\username" //user USERSTORE\\USERNAME syntax except for admin/anonymous return "admin"; } }
{ "content_hash": "5e546ff47623e8dfb5d82e06f0ba0161", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 97, "avg_line_length": 29.72340425531915, "alnum_prop": 0.7351467430207588, "repo_name": "enonic/maven-cms-archetype", "id": "fcc9cb106a71e64efca649959c76863a8dfe63c8", "size": "1397", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/archetype-resources/src/main/java/com/enonic/plugin/AutoLoginImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3851" }, { "name": "Java", "bytes": "22809" }, { "name": "JavaScript", "bytes": "937" } ], "symlink_target": "" }
YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {EventHandle} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {EventHandle} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {EventHandle} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor === DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor === DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ /** * This event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * Flag for the default function to execute only if the * firing event is the current target. This happens only * when using custom event delegation and setting the * flag to `true` mimics the behavior of event delegation * in the DOM. * * @property defaultTargetOnly * @type Boolean * @default false */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ preventable : true, /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ bubbles : true, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } if (when) { return (when === 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when), firedWith; if (this.fireOnce && this.fired) { firedWith = this.firedWith; // It's a little ugly for this to know about facades, // but given the current breakup, not much choice without // moving a whole lot of stuff around. if (this.emitFacade && this._addFacadeToArgs) { this._addFacadeToArgs(firedWith); } if (this.async) { setTimeout(Y.bind(this._notify, this, s, firedWith), 0); } else { this._notify(s, firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {Number} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { this._broadcast(args); } return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped === 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast === 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {Number} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {Number} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; } if (subs) { i = YArray.indexOf(subs, s, 0); if (s && subs[i] === s) { subs.splice(i, 1); } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn === fn) && this.context === context); } else { return (this.fn === fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {Number} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }, /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t === '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre] The prefix. Defaults to this._yuievt.config.prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {Boolean} True if the whole lifecycle of the event went through, * false if at any point the event propagation was halted. */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, 'patched-v3.16.0', {"requires": ["oop"]});
{ "content_hash": "fb661fd046e891dae6ef5fbcadc85970", "timestamp": "", "source": "github", "line_count": 2486, "max_line_length": 131, "avg_line_length": 30.478680611423975, "alnum_prop": 0.5571466279530157, "repo_name": "voxarlabs/gesturescatalog", "id": "24716d0960ca427690f8a07560fb482c9ec89a1a", "size": "75770", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "alloyui/build/event-custom-base/event-custom-base-debug.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "411385" }, { "name": "HTML", "bytes": "21174" }, { "name": "JavaScript", "bytes": "14673251" }, { "name": "Python", "bytes": "899" }, { "name": "Ruby", "bytes": "885" } ], "symlink_target": "" }
Embulk::JavaPlugin.register_filter( "left_outer_join_json_table", "org.embulk.filter.left_outer_join_json_table.LeftOuterJoinJsonTableFilterPlugin", File.expand_path('../../../../classpath', __FILE__))
{ "content_hash": "da0c63259d2926a97dbf0412bd86f09d", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 114, "avg_line_length": 68.66666666666667, "alnum_prop": 0.7281553398058253, "repo_name": "civitaspo/embulk-filter-left_outer_join_json_table", "id": "7ac70b931b985549c9ef173271758671a5a3f8fb", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/embulk/filter/left_outer_join_json_table.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "12362" }, { "name": "Ruby", "bytes": "206" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IEMobile 7]><html class="iem7 no-js" lang="en" dir="ltr"><![endif]--> <!--[if lt IE 7]><html class="lt-ie9 lt-ie8 lt-ie7 no-js" lang="en" dir="ltr"><![endif]--> <!--[if (IE 7)&(!IEMobile)]><html class="lt-ie9 lt-ie8 no-js" lang="en" dir="ltr"><![endif]--> <!--[if IE 8]><html class="lt-ie9 no-js" lang="en" dir="ltr"><![endif]--> <!--[if (gt IE 8)|(gt IEMobile 7)]><!--> <html class="no-js not-oldie" lang="en" dir="ltr"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="HandheldFriendly" content="true" /> <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" /> <meta name="MobileOptimized" content="width" /> <meta http-equiv="cleartype" content="on" /> <meta http-equiv="ImageToolbar" content="false" /> <meta name="viewport" content="width=device-width" /> <meta name="version" content="20161218" /> <!--googleon: all--> <meta name="DC.description" content="" /> <meta name="DC.title" content="" /> <title> Overcoming Consumers’ Barriers to the Adoption of Sustainable Lighting: Considering CFLs and LEDs Across the Life Course| Research Project Database | Grantee Research Project | ORD | US EPA</title> <!--googleoff: snippet--> <meta name="keywords" content="" /> <link rel="shortlink" href="" /> <link rel="canonical" href="" /> <meta name="DC.creator" content="" /> <meta name="DC.language" content="en" /> <meta name="DC.Subject.epachannel" content="" /> <meta name="DC.type" content="" /> <meta name="DC.date.created" content="" /> <meta name="DC.date.modified" content="2009-08-24" /> <!--googleoff: all--> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" /> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" /> <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" /> <!--[if lt IE 9]><link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/ie.css" media="all" /><![endif]--> <link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" /> <link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" /> <link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" /> <!--[if lt IE 9]><script src="https://www.epa.gov/sites/all/themes/epa/js/html5.js"></script><![endif]--> <style type="text/css"> /*This style needed for highlight link. Please do not remove*/ .hlText { font-family: "Arial"; color: red; font-weight: bold; font-style: italic; background-color: yellow; } .tblClass { font-size:smaller; min-width: 10%; line-height: normal; } </style> </head> <!-- NOTE, figure out body classes! --> <body class="node-type-(web-area|page|document|webform) (microsite|resource-directory)" > <!-- Google Tag Manager --> <noscript> <iframe src="//www.googletagmanager.com/ns.html?id=GTM-L8ZB" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-L8ZB');</script> <!-- End Google Tag Manager --> <div class="skip-links"><a href="#main-content" class="skip-link element-invisible element-focusable">Jump to main content</a></div> <header class="masthead clearfix" role="banner"> <img class="site-logo" src="https://www.epa.gov/sites/all/themes/epa/logo.png" alt="" /> <hgroup class="site-name-and-slogan"> <h1 class="site-name"><a href="https://www.epa.gov/" title="Go to the home page" rel="home"><span>US EPA</span></a></h1> <div class="site-slogan">United States Environmental Protection Agency</div> </hgroup> <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch"> <label class="element-hidden" for="search-box">Search</label> <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/> <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button> <input type="hidden" name="fld" value="" /> <input type="hidden" name="areaname" value="" /> <input type="hidden" name="areacontacts" value="" /> <input type="hidden" name="areasearchurl" value="" /> <input type="hidden" name="typeofsearch" value="epa" /> <input type="hidden" name="result_template" value="2col.ftl" /> <input type="hidden" name="filter" value="sample4filt.hts" /> </form> </header> <section id="main-content" class="main-content clearfix" role="main"> <div class="region-preface clearfix"> <div id="block-pane-epa-web-area-connect" class="block block-pane contextual-links-region"> <ul class="menu utility-menu"> <li class="menu-item"><a href="https://www.epa.gov/research-grants/forms/contact-us-about-research-grants" class="menu-link contact-us">Contact Us</a></li> </ul> </div> </div> <div class="main-column clearfix"> <!--googleon: all--> <div class="panel-pane pane-node-content" > <div class="pane-content"> <div class="node node-page clearfix view-mode-full"> <div class="box multi related-info right clear-right" style="max-width:300px; font-size:14px;"><!--googleoff: index--> <h5 class="pane-title">Project Research Results</h5> <div class="pane-content"> <ul> <li><a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.abstractDetail/abstract/9011/report/F">Final Report</a></li> </ul> </div> <!-- RFA Search start --> <h5 class="pane-title">Related Information</h5> <div class="pane-content"> <ul><li><a href="https://www.epa.gov/research-grants/">Research Grants</a></li> <li><a href="https://www.epa.gov/P3">P3: Student Design Competition</a></li> <li><a href="https://www.epa.gov/research-fellowships/">Research Fellowships</a></li> <li><a href="https://www.epa.gov/sbir/">Small Business Innovation Research (SBIR)</a></li> <li><a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/search.welcome">Grantee Research Project Results Search</a></li> </ul> </div> <!-- RFA Search End --><!--googleon: index--> </div> <a name="content"></a> <h2> Overcoming Consumers’ Barriers to the Adoption of Sustainable Lighting: Considering CFLs and LEDs Across the Life Course</h2> <b>EPA Grant Number:</b> SU834333<br /> <b>Title:</b> Overcoming Consumers’ Barriers to the Adoption of Sustainable Lighting: Considering CFLs and LEDs Across the Life Course<br /> <b>Investigators:</b> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/12283"> Hebert, Paulette </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/12286"> Chaney, Sylvia </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/12284"> Johnston, Jan </a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/12285"> Stall-Meadows, Celia </a> <br /> <strong>Institution:</strong> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.institutionInfo/institution/3170"> <b>Oklahoma State University</b> </a> <br /> <strong>EPA Project Officer:</strong> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.investigatorInfo/investigator/55"> Nolt-Helms, Cynthia </a> <br /> <b>Phase:</b> I<br /> <b>Project Period:</b> August 15, 2009 through August 14, 2010 <br /> <b>Project Amount:</b> $10,000 <br /> <b>RFA:</b> P3 Awards: A National Student Design Competition for Sustainability Focusing on People, Prosperity and the Planet (2009) <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.rfatext/rfa_id/497">RFA Text</a>&nbsp;|&nbsp; <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/recipients.display/rfa_id/497">Recipients Lists</a> <br /> <b>Research Category:</b> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/963">Pollution Prevention/Sustainable Development</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1086">P3 Challenge Area - Built Environment</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1087">P3 Challenge Area - Energy</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1176">P3 Awards</a> , <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.researchCategory/rc_id/1175">Sustainability</a> <br /> <br> <h3>Objective:</h3> <p>To promote informed consideration of sustainable residential lighting by consumers across the life course and to disseminate this to a broad audience.</p> <p></p> <h3>Approach:</h3> <p>Pre-test and post-test consumer surveys will be administered flanking educational field demonstrations and hands-on experiences at prepared sites. These will be supplemented through the collection of consumer response sheets regarding visual perceptions and task performance at the sites and through the documentation of the field settings through light level and ultraviolet measurements, computer modeling, and still and video photography. </p> <p></p> <h3>Expected Results:</h3> <p>An increase in intentions to purchase sustainable lighting is expected for those involved in the study and also for those who are exposed to this project through the dissemination of educational tools based on this work. </p> <p></p> <h3>Supplemental Keywords:</h3> <i>willingness-to-pay, measurement methods, elderly, decision making,</i> <p /> <P><h3>Progress and Final Reports:</h3> <a href="https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.abstractDetail/abstract/9011/report/F">Final Report</a><br> </P> </div> </div> </div> <div id="block-epa-og-footer" class="block block-epa-og"> <p class="pagetop"><a href="#content">Top of Page</a></p> <!--googleoff: all--> <p id="epa-og-footer"> The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA. Conclusions drawn by the principal investigators have not been reviewed by the Agency. </p> </div> <!--googleoff: all--> </div> </section> <nav class="nav simple-nav simple-main-nav" role="navigation"> <div class="nav__inner"> <h2 class="element-invisible">Main menu</h2> <ul class="menu" role="menu"> <li class="menu-item" id="menu-learn" role="presentation"><a href="https://www.epa.gov/environmental-topics" title="Learn about EPA's environmental topics to help protect the environment in your home, workplace, and community and EPA&#039;s research mission is to conduct leading-edge research and foster the sound use of science and technology." class="menu-link" role="menuitem">Environmental Topics</a></li> <li class="menu-item" id="menu-lawsregs" role="presentation"><a href="https://www.epa.gov/laws-regulations" title="Laws written by Congress provide the authority for EPA to write regulations. Regulations explain the technical, operational, and legal details necessary to implement laws." class="menu-link" role="menuitem">Laws &amp; Regulations</a></li> <li class="menu-item" id="menu-about" role="presentation"><a href="https://www.epa.gov/aboutepa" title="Learn more about: our mission and what we do, how we are organized, and our history." class="menu-link" role="menuitem">About EPA</a></li> </ul> </div> </nav> <footer class="main-footer clearfix" role="contentinfo"> <div class="main-footer__inner"> <div class="region-footer"> <div class="block block-pane block-pane-epa-global-footer"> <div class="row cols-3"> <div class="col size-1of3"> <div class="col__title">Discover.</div> <ul class="menu"> <li><a href="https://www.epa.gov/accessibility">Accessibility</a></li> <li><a href="https://www.epa.gov/aboutepa/administrator-gina-mccarthy">EPA Administrator</a></li> <li><a href="https://www.epa.gov/planandbudget">Budget &amp; Performance</a></li> <li><a href="https://www.epa.gov/contracts">Contracting</a></li> <li><a href="https://www.epa.gov/home/grants-and-other-funding-opportunities">Grants</a></li> <li><a href="https://www.epa.gov/ocr/whistleblower-protections-epa-and-how-they-relate-non-disclosure-agreements-signed-epa-employees">No FEAR Act Data</a></li> <li><a href="https://www.epa.gov/home/privacy-and-security-notice">Privacy and Security</a></li> </ul> </div> <div class="col size-1of3"> <div class="col__title">Connect.</div> <ul class="menu"> <li><a href="https://www.data.gov/">Data.gov</a></li> <li><a href="https://www.epa.gov/office-inspector-general/about-epas-office-inspector-general">Inspector General</a></li> <li><a href="https://www.epa.gov/careers">Jobs</a></li> <li><a href="https://www.epa.gov/newsroom">Newsroom</a></li> <li><a href="https://www.whitehouse.gov/open">Open Government</a></li> <li><a href="http://www.regulations.gov/">Regulations.gov</a></li> <li><a href="https://www.epa.gov/newsroom/email-subscriptions">Subscribe</a></li> <li><a href="https://www.usa.gov/">USA.gov</a></li> <li><a href="https://www.whitehouse.gov/">White House</a></li> </ul> </div> <div class="col size-1of3"> <div class="col__title">Ask.</div> <ul class="menu"> <li><a href="https://www.epa.gov/home/forms/contact-us">Contact Us</a></li> <li><a href="https://www.epa.gov/home/epa-hotlines">Hotlines</a></li> <li><a href="https://www.epa.gov/foia">FOIA Requests</a></li> <li><a href="https://www.epa.gov/home/frequent-questions-specific-epa-programstopics">Frequent Questions</a></li> </ul> <div class="col__title">Follow.</div> <ul class="social-menu"> <li><a class="menu-link social-facebook" href="https://www.facebook.com/EPA">Facebook</a></li> <li><a class="menu-link social-twitter" href="https://twitter.com/epa">Twitter</a></li> <li><a class="menu-link social-youtube" href="https://www.youtube.com/user/USEPAgov">YouTube</a></li> <li><a class="menu-link social-flickr" href="https://www.flickr.com/photos/usepagov">Flickr</a></li> <li><a class="menu-link social-instagram" href="https://instagram.com/epagov">Instagram</a></li> </ul> <p class="last-updated">Last updated on Monday, August 24, 2009</p> </div> </div> </div> </div> </div> </footer> <script src="https://www.epa.gov/sites/all/libraries/template2/jquery.js"></script> <script src="https://www.epa.gov/sites/all/libraries/template/js.js"></script> <script src="https://www.epa.gov/sites/all/modules/custom/epa_core/js/alert.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.core.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.widget.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.position.min.js"></script> <script src="https://www.epa.gov/sites/all/modules/contrib/jquery_update/replace/ui/ui/minified/jquery.ui.autocomplete.min.js"></script> <!--[if lt IE 9]><script src="https://www.epa.gov/sites/all/themes/epa/js/ie.js"></script><![endif]--> <!-- REMOVE if not using --> <script language=javascript> <!-- // Activate cloak // pressing enter will not default submit the first defined button but the programmed defined button function chkCDVal(cdVal) { var isErr = true; try{ var CDParts = cdVal.split(','); var st = CDParts[0]; var cd = CDParts[1]; var objRegExp = new RegExp('[0-9][0-9]'); if (!isNaN(st)) { isErr = false; } if (!objRegExp.test(cd) || (cd.length>3)){ isErr = false; } } catch(err){ isErr = false; } return isErr; } function checkCongDist(cdtxt) { //alert(cdtxt.value); if (!chkCDVal(cdtxt.value)) { alert('Congressional District MUST be in the following format: state, district; example: Virginia, 08'); return false; } else { return true; } } function fnTrapKD(btn, event) { var btn = getObject(btn); if (document.all) { if (event.keyCode == 13) { event.returnValue=false;event.cancel = true;btn.click(); } } else { if (event.which == 13) { event.returnValue=false;event.cancelBubble = true;btn.click(); } } } function CheckFilter() { if (document.searchform.presetTopic.options[document.searchform.presetTopic.selectedIndex].value == 'NA'){ alert('You must select a subtopic. \n This item is not selectable'); document.searchform.presetTopic.options[0].selected = true; } } function openHelpWindow(url,title,scrollable) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars='+scrollable+',menubar=no,status=no'); win.focus(); } function openNewWindow(url,title,scrollable) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars='+scrollable+',menubar=no,status=no'); } function openNewWindow(url,title) { var win = window.open(url,"title",'width=300,height=220,left=320,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNewMapWindow(url,title) { var win = window.open(url,"title",'width=800,height=450,left=320,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNoticeWindow(url,title) { var win = window.open(url,"title",'width=300,height=150,left=500,top=150,resizable=1,scrollbars=no,menubar=no,status=no'); } function openNewSearchWindow(site,subj) { title = 'window'; var win = window.open('https://cfpub.epa.gov/ncer_abstracts/index.cfm/fuseaction/display.pubsearch/site/' + site + '/redirect/' + subj,"title",'width=640,height=480,resizable=1,scrollbars=yes,menubar=yes,status=no'); } function autoCheck(name) { document.forms['thisForm'].elements[name].checked = true; } function alertUser() { var ok = alert("This search might take longer than expected. Please refrain from hitting the refresh or reload button on your browser. The search results will appear after the search is complete. Thank you."); } function closePopupWindow(redirectUrl) { opener.location = redirectUrl; opener.focus(); this.close(); } //--> </script> </body> </html>
{ "content_hash": "421cba12845ba45aa1425dc6dc0e6912", "timestamp": "", "source": "github", "line_count": 424, "max_line_length": 460, "avg_line_length": 50.990566037735846, "alnum_prop": 0.6206753006475486, "repo_name": "1wheel/scraping", "id": "f5bce5efa82f1c806690d81a8e7e5f0dc8c08952", "size": "21626", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "epa-grants/research/raw/09011.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4406" }, { "name": "DIGITAL Command Language", "bytes": "381196" }, { "name": "HTML", "bytes": "2546703681" }, { "name": "JavaScript", "bytes": "620077" }, { "name": "Jupyter Notebook", "bytes": "14020" } ], "symlink_target": "" }
using Facebook.Scrumptious.Windows8.ViewModel; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237 namespace Facebook.Scrumptious.Windows8.Views { /// <summary> /// A basic page that provides characteristics common to most applications. /// </summary> public sealed partial class Restaurants : Facebook.Scrumptious.Windows8.Common.LayoutAwarePage { public Restaurants() { this.InitializeComponent(); } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="pageState">An empty dictionary to be populated with serializable state.</param> protected override void SaveState(Dictionary<String, Object> pageState) { } protected override void OnNavigatedFrom(NavigationEventArgs e) { if (this.restaurantsListBox.SelectedIndex >= 0) { FacebookData.SelectedRestaurant = (Location)this.restaurantsListBox.SelectedItem; FacebookData.IsRestaurantSelected = true; } base.OnNavigatedFrom(e); } } }
{ "content_hash": "9c08e4436e99483e7087b1468945a9a4", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 107, "avg_line_length": 39.78125, "alnum_prop": 0.657109190887667, "repo_name": "facebook-csharp-sdk/facebook-windows8-sample", "id": "2d4e4c17438fce1ac002c76f5ff116c1dea9783b", "size": "2548", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Facebook.Scrumptious.Windows8/Views/Restaurants.xaml.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "97615" } ], "symlink_target": "" }
package org.apache.poi.hslf.record; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.util.BitField; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.POILogger; /** * General holder for PersistPtrFullBlock and PersistPtrIncrementalBlock * records. We need to handle them specially, since we have to go around * updating UserEditAtoms if they shuffle about on disk * These hold references to where slides "live". If the position of a slide * moves, then we have update all of these. If we come up with a new version * of a slide, then we have to add one of these to the end of the chain * (via CurrentUserAtom and UserEditAtom) pointing to the new slide location * * @author Nick Burch */ public final class PersistPtrHolder extends PositionDependentRecordAtom { private final byte[] _header; private byte[] _ptrData; // Will need to update this once we allow updates to _slideLocations private long _type; /** * Holds the lookup for slides to their position on disk. * You always need to check the most recent PersistPtrHolder * that knows about a given slide to find the right location */ private Map<Integer,Integer> _slideLocations; private static final BitField persistIdFld = new BitField(0X000FFFFF); private static final BitField cntPersistFld = new BitField(0XFFF00000); /** * Return the value we were given at creation, be it 6001 or 6002 */ @Override public long getRecordType() { return _type; } /** * Get the list of slides that this PersistPtrHolder knows about. * (They will be the keys in the map for looking up the positions * of these slides) */ public int[] getKnownSlideIDs() { int[] ids = new int[_slideLocations.size()]; int i = 0; for (Integer slideId : _slideLocations.keySet()) { ids[i++] = slideId; } return ids; } /** * Get the lookup from slide numbers to byte offsets, for the slides * known about by this PersistPtrHolder. */ public Map<Integer,Integer> getSlideLocationsLookup() { return Collections.unmodifiableMap(_slideLocations); } /** * Create a new holder for a PersistPtr record */ protected PersistPtrHolder(byte[] source, int start, int len) { // Sanity Checking - including whole header, so treat // length as based of 0, not 8 (including header size based) if(len < 8) { len = 8; } // Treat as an atom, grab and hold everything _header = new byte[8]; System.arraycopy(source,start,_header,0,8); _type = LittleEndian.getUShort(_header,2); // Try to make sense of the data part: // Data part is made up of a number of these sets: // 32 bit info value // 12 bits count of # of entries // base number for these entries // count * 32 bit offsets // Repeat as many times as you have data _slideLocations = new HashMap<Integer,Integer>(); _ptrData = new byte[len-8]; System.arraycopy(source,start+8,_ptrData,0,_ptrData.length); int pos = 0; while(pos < _ptrData.length) { // Grab the info field int info = LittleEndian.getInt(_ptrData,pos); // First 20 bits = offset number // Remaining 12 bits = offset count int offset_no = persistIdFld.getValue(info); int offset_count = cntPersistFld.getValue(info); // Wind on by the 4 byte info header pos += 4; // Grab the offsets for each of the sheets for(int i=0; i<offset_count; i++) { int sheet_no = offset_no + i; int sheet_offset = (int)LittleEndian.getUInt(_ptrData,pos); _slideLocations.put(sheet_no, sheet_offset); // Wind on by 4 bytes per sheet found pos += 4; } } } /** * remove all slide references * * Convenience method provided, for easier reviewing of invocations */ public void clear() { _slideLocations.clear(); } /** * Adds a new slide, notes or similar, to be looked up by this. */ public void addSlideLookup(int slideID, int posOnDisk) { if (_slideLocations.containsKey(slideID)) { throw new CorruptPowerPointFileException("A record with persistId "+slideID+" already exists."); } _slideLocations.put(slideID, posOnDisk); } /** * At write-out time, update the references to the sheets to their * new positions */ @Override public void updateOtherRecordReferences(Map<Integer,Integer> oldToNewReferencesLookup) { // Loop over all the slides we know about // Find where they used to live, and where they now live for (Entry<Integer,Integer> me : _slideLocations.entrySet()) { Integer oldPos = me.getValue(); Integer newPos = oldToNewReferencesLookup.get(oldPos); if (newPos == null) { Integer id = me.getKey(); logger.log(POILogger.WARN, "Couldn't find the new location of the \"slide\" with id " + id + " that used to be at " + oldPos); logger.log(POILogger.WARN, "Not updating the position of it, you probably won't be able to find it any more (if you ever could!)"); } else { me.setValue(newPos); } } } private void normalizePersistDirectory() { TreeMap<Integer,Integer> orderedSlideLocations = new TreeMap<Integer,Integer>(_slideLocations); @SuppressWarnings("resource") BufAccessBAOS bos = new BufAccessBAOS(); // NOSONAR byte intbuf[] = new byte[4]; int lastPersistEntry = -1; int lastSlideId = -1; for (Entry<Integer,Integer> me : orderedSlideLocations.entrySet()) { int nextSlideId = me.getKey(); int offset = me.getValue(); try { // Building the info block // First 20 bits = offset number = slide ID (persistIdFld, i.e. first slide ID of a continuous group) // Remaining 12 bits = offset count = 1 (cntPersistFld, i.e. continuous entries in a group) if (lastSlideId+1 == nextSlideId) { // use existing PersistDirectoryEntry, need to increase entry count assert(lastPersistEntry != -1); int infoBlock = LittleEndian.getInt(bos.getBuf(), lastPersistEntry); int entryCnt = cntPersistFld.getValue(infoBlock); infoBlock = cntPersistFld.setValue(infoBlock, entryCnt+1); LittleEndian.putInt(bos.getBuf(), lastPersistEntry, infoBlock); } else { // start new PersistDirectoryEntry lastPersistEntry = bos.size(); int infoBlock = persistIdFld.setValue(0, nextSlideId); infoBlock = cntPersistFld.setValue(infoBlock, 1); LittleEndian.putInt(intbuf, 0, infoBlock); bos.write(intbuf); } // Add to the ptrData offset lookup hash LittleEndian.putInt(intbuf, 0, offset); bos.write(intbuf); lastSlideId = nextSlideId; } catch (IOException e) { // ByteArrayOutputStream is very unlikely throwing a IO exception (maybe because of OOM ...) throw new HSLFException(e); } } // Save the new ptr data _ptrData = bos.toByteArray(); // Update the atom header LittleEndian.putInt(_header,4,bos.size()); } /** * Write the contents of the record back, so it can be written * to disk */ @Override public void writeOut(OutputStream out) throws IOException { normalizePersistDirectory(); out.write(_header); out.write(_ptrData); } private static class BufAccessBAOS extends ByteArrayOutputStream { public byte[] getBuf() { return buf; } } }
{ "content_hash": "4c4aedbca268da8a0bf82679f9553941", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 147, "avg_line_length": 35.22943722943723, "alnum_prop": 0.6415581223887933, "repo_name": "lvweiwolf/poi-3.16", "id": "8a1c48269697d2655184c3ef442e4b9778f003a2", "size": "9072", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1527" }, { "name": "CSS", "bytes": "1982" }, { "name": "Groovy", "bytes": "16130" }, { "name": "HTML", "bytes": "43874" }, { "name": "Java", "bytes": "23030825" }, { "name": "Makefile", "bytes": "8711" }, { "name": "Ruby", "bytes": "5262" }, { "name": "Shell", "bytes": "5209" }, { "name": "Visual Basic", "bytes": "816" }, { "name": "XSLT", "bytes": "77838" } ], "symlink_target": "" }
package server import akka.actor.{ActorRef, ActorSystem} import java.net.InetSocketAddress import scala.collection.mutable.ArrayBuffer /** * Created with IntelliJ IDEA. * User: pavel * Date: 16.12.13 * Time: 18:45 */ class Server(val host : String, val port : Int) { val system = ActorSystem("async-io-server") val endpoint = new InetSocketAddress(host, port) val subscribers = ArrayBuffer.empty[ActorRef] system.actorOf(ServerService.props(endpoint, subscribers), "server-service") readLine("Hit any key to exit") system.shutdown() system.awaitTermination() }
{ "content_hash": "f15ec76ba281cf530a23501f7df30bce", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 78, "avg_line_length": 25.391304347826086, "alnum_prop": 0.7397260273972602, "repo_name": "zmactep/hpcource", "id": "e5e900e5bdb7ee24b0bf22aa6b7119baf1876af7", "size": "584", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "async_io/src/main/scala/server/Server.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "9198" } ], "symlink_target": "" }
SYNONYM #### According to GRIN Taxonomy for Plants #### Published in Trudy Imp. S. -Peterburgsk. Bot. Sada 3(2):43. 1875 (Allior. monogr. 43. ) #### Original name null ### Remarks null
{ "content_hash": "648e7021052bddd39b36f062cc1f36ee", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 74, "avg_line_length": 14.461538461538462, "alnum_prop": 0.6702127659574468, "repo_name": "mdoering/backbone", "id": "3676b34ed1fd5e94d35e0210f8bc61da9ae4c55b", "size": "264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Allium/Allium ampeloprasum/ Syn. Allium scorodoprasum babingtonii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
{% extends "dashboard/layout/layout.html" %} {% block content %} <div class="content-page"> <div class="content"> <div class="container"> <div class="row"> <div class="col-sm-4"> <a href="{{ url_for('dashboard.add_patient') }}" class="btn btn-success btn-md waves-effect waves-light m-b-30"><i class="md md-add"></i> Add Patients</a> </div><!-- end col --> </div> <div class="row"> {% for patients in patient_list %} <div class="col-md-4"> <div class="text-center card-box"> <div class="dropdown pull-right"> <a href="#" class="dropdown-toggle card-drop" data-toggle="dropdown" aria-expanded="false"> <i class="zmdi zmdi-more-vert"></i> </a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Edit</a></li> <li><a href="#">Delete</a></li> <li><a href="#">Block</a></li> </ul> </div> <div> <img src="{{ url_for('static', filename='landing/images/icon.png')}}" class="img-circle thumb-xl img-thumbnail m-b-10" alt="profile-image"> <div class="text-center"> <p class="text-muted font-13"><strong>Full Name :</strong><span class="m-l-15">{{ patients.first_name }} {{ patients.last_name }}</span></p> <p class="text-muted font-13"><strong>Email :</strong> <span class="m-l-15">{{ patients.email }}</span></p> </div> <a href="{{ url_for('dashboard.patient') }}?pID={{ patients.user_id }}" class="btn btn-custom btn-rounded waves-effect waves-light">View More</a> <button type="button" class="btn btn-danger btn-rounded waves-effect waves-light">Remove Patient</button> </div> </div> </div> <!-- end col --> {% endfor %} </div> </div> </div> <!-- content --> <footer class="footer"> 2017 © Norman Bot. </footer> </div> <!-- Modal Add Category --> <div class="modal fade none-border" id="add-category"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title"><strong>Add a category </strong></h4> </div> <div class="modal-body"> <div class="custom-modal-text text-left"> <form role="form"> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="position">Position</label> <input type="text" class="form-control" id="position" placeholder="Enter position"> </div> <div class="form-group"> <label for="company">Company</label> <input type="text" class="form-control" id="company" placeholder="Enter company"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email"> </div> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button> <button type="button" class="btn btn-danger waves-effect waves-light save-category" data-dismiss="modal">Save</button> </div> </div> </div> </div> {% endblock %}
{ "content_hash": "29bea0dcd3a1b6e68fc73b5dda51c1be", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 187, "avg_line_length": 61.21649484536083, "alnum_prop": 0.3361401145166723, "repo_name": "Olamyy/Norman", "id": "8bc92e1c67e046cabc45408e8a44e775f1f44881", "size": "5939", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Norman/templates/dashboard/admin/view-patient.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "416457" }, { "name": "CoffeeScript", "bytes": "542" }, { "name": "HTML", "bytes": "1580421" }, { "name": "JavaScript", "bytes": "1168744" }, { "name": "Python", "bytes": "143924" }, { "name": "Shell", "bytes": "2" }, { "name": "TeX", "bytes": "212" } ], "symlink_target": "" }
class CreateEvents < ActiveRecord::Migration def self.up create_table :events do |t| t.string "name" t.text "description" t.boolean "publish" t.datetime "start_time" t.datetime "end_time" t.timestamps end end def self.down drop_table :events end end
{ "content_hash": "194bdef6e9ff4a27cce3baa4862778ce", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 44, "avg_line_length": 18.823529411764707, "alnum_prop": 0.6, "repo_name": "briandoll/Rit", "id": "f3b40885b0228060e72d853702451fea168fa13d", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20091028234745_create_events.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "30563" }, { "name": "Ruby", "bytes": "167840" } ], "symlink_target": "" }
@interface AlertsModel : NSObject @property NSInteger AlertId; @property (nonatomic, strong) NSString *AlertName; @property (nonatomic, strong) NSString *AlertMsg; @property (nonatomic, strong) NSDate *AlertDtm; @property NSInteger Importance; @end
{ "content_hash": "8e722e3d6b0380908e505fb2deb32cfb", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 50, "avg_line_length": 27.88888888888889, "alnum_prop": 0.7888446215139442, "repo_name": "hylander0/theGoodPush_iOS_Client", "id": "aeccacd542506323bd6f5f4df7baa415ce764c22", "size": "430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "theGoodPush/theGoodPush/Services/Models/AlertsModel.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "71504" }, { "name": "JavaScript", "bytes": "1998" }, { "name": "Objective-C", "bytes": "568571" }, { "name": "Shell", "bytes": "3328" } ], "symlink_target": "" }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@egjs/component'), require('@egjs/imready'), require('@egjs/axes')) : typeof define === 'function' && define.amd ? define(['@egjs/component', '@egjs/imready', '@egjs/axes'], factory) : (global = global || self, (global.eg = global.eg || {}, global.eg.Flicking = factory(global.eg.Component, global.ImReady, global.eg.Axes))); }(this, (function (Component, ImReady, Axes) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var MOVE_TYPE = { SNAP: "snap", FREE_SCROLL: "freeScroll" }; var DEFAULT_MOVE_TYPE_OPTIONS = { snap: { type: "snap", count: 1 }, freeScroll: { type: "freeScroll" } }; var isBrowser = typeof document !== "undefined"; /** * Default options for creating Flicking. * @ko 플리킹을 만들 때 사용하는 기본 옵션들 * @private * @memberof eg.Flicking */ var DEFAULT_OPTIONS = { classPrefix: "eg-flick", deceleration: 0.0075, horizontal: true, circular: false, infinite: false, infiniteThreshold: 0, lastIndex: Infinity, threshold: 40, duration: 100, panelEffect: function (x) { return 1 - Math.pow(1 - x, 3); }, defaultIndex: 0, inputType: ["touch", "mouse"], thresholdAngle: 45, bounce: 10, autoResize: false, adaptive: false, zIndex: 2000, bound: false, overflow: false, hanger: "50%", anchor: "50%", gap: 0, moveType: DEFAULT_MOVE_TYPE_OPTIONS.snap, useOffset: false, isEqualSize: false, isConstantSize: false, renderOnlyVisible: false, renderExternal: false, resizeOnContentsReady: false, iOSEdgeSwipeThreshold: 30, collectStatistics: true }; var DEFAULT_VIEWPORT_CSS = { position: "relative", zIndex: DEFAULT_OPTIONS.zIndex, overflow: "hidden" }; var DEFAULT_CAMERA_CSS = { width: "100%", height: "100%", willChange: "transform" }; var DEFAULT_PANEL_CSS = { position: "absolute" }; var EVENTS = { HOLD_START: "holdStart", HOLD_END: "holdEnd", MOVE_START: "moveStart", MOVE: "move", MOVE_END: "moveEnd", CHANGE: "change", RESTORE: "restore", SELECT: "select", NEED_PANEL: "needPanel", VISIBLE_CHANGE: "visibleChange", CONTENT_ERROR: "contentError" }; var AXES_EVENTS = { HOLD: "hold", CHANGE: "change", RELEASE: "release", ANIMATION_END: "animationEnd", FINISH: "finish" }; var STATE_TYPE = { IDLE: 0, HOLDING: 1, DRAGGING: 2, ANIMATING: 3, DISABLED: 4 }; var DIRECTION = { PREV: "PREV", NEXT: "NEXT" }; var FLICKING_METHODS = { prev: true, next: true, moveTo: true, getIndex: true, getAllPanels: true, getCurrentPanel: true, getElement: true, getSize: true, getPanel: true, getPanelCount: true, getStatus: true, getVisiblePanels: true, enableInput: true, disableInput: true, destroy: true, resize: true, setStatus: true, isPlaying: true }; // Check whether browser supports transform: translate3d // https://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support var checkTranslateSupport = function () { var transforms = { webkitTransform: "-webkit-transform", msTransform: "-ms-transform", MozTransform: "-moz-transform", OTransform: "-o-transform", transform: "transform" }; if (!isBrowser) { return { name: transforms.transform, has3d: true }; } var supportedStyle = document.documentElement.style; var transformName = ""; for (var prefixedTransform in transforms) { if (prefixedTransform in supportedStyle) { transformName = prefixedTransform; } } if (!transformName) { throw new Error("Browser doesn't support CSS3 2D Transforms."); } var el = document.createElement("div"); document.documentElement.insertBefore(el, null); el.style[transformName] = "translate3d(1px, 1px, 1px)"; var styleVal = window.getComputedStyle(el).getPropertyValue(transforms[transformName]); el.parentElement.removeChild(el); var transformInfo = { name: transformName, has3d: styleVal.length > 0 && styleVal !== "none" }; checkTranslateSupport = function () { return transformInfo; }; return transformInfo; }; var TRANSFORM = checkTranslateSupport(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ function merge(target) { var srcs = []; for (var _i = 1; _i < arguments.length; _i++) { srcs[_i - 1] = arguments[_i]; } srcs.forEach(function (source) { Object.keys(source).forEach(function (key) { var value = source[key]; target[key] = value; }); }); return target; } function parseElement(element) { if (!Array.isArray(element)) { element = [element]; } var elements = []; element.forEach(function (el) { if (isString(el)) { var tempDiv = document.createElement("div"); tempDiv.innerHTML = el; elements.push.apply(elements, toArray(tempDiv.children)); while (tempDiv.firstChild) { tempDiv.removeChild(tempDiv.firstChild); } } else { elements.push(el); } }); return elements; } function isString(value) { return typeof value === "string"; } // Get class list of element as string array function addClass(element, className) { if (element.classList) { element.classList.add(className); } else { if (!hasClass(element, className)) { element.className = (element.className + " " + className).replace(/\s{2,}/g, " "); } } } function hasClass(element, className) { if (element.classList) { return element.classList.contains(className); } else { return element.className.split(" ").indexOf(className) >= 0; } } function applyCSS(element, cssObj) { Object.keys(cssObj).forEach(function (property) { element.style[property] = cssObj[property]; }); } function clamp(val, min, max) { return Math.max(Math.min(val, max), min); } // Min: inclusive, Max: exclusive function isBetween(val, min, max) { return val >= min && val <= max; } function toArray(iterable) { return [].slice.call(iterable); } function isArray(arr) { return arr && arr.constructor === Array; } function parseArithmeticExpression(cssValue, base, defaultVal) { // Set base / 2 to default value, if it's undefined var defaultValue = defaultVal != null ? defaultVal : base / 2; var cssRegex = /(?:(\+|\-)\s*)?(\d+(?:\.\d+)?(%|px)?)/g; if (typeof cssValue === "number") { return clamp(cssValue, 0, base); } var idx = 0; var calculatedValue = 0; var matchResult = cssRegex.exec(cssValue); while (matchResult != null) { var sign = matchResult[1]; var value = matchResult[2]; var unit = matchResult[3]; var parsedValue = parseFloat(value); if (idx <= 0) { sign = sign || "+"; } // Return default value for values not in good form if (!sign) { return defaultValue; } if (unit === "%") { parsedValue = parsedValue / 100 * base; } calculatedValue += sign === "+" ? parsedValue : -parsedValue; // Match next occurrence ++idx; matchResult = cssRegex.exec(cssValue); } // None-matched if (idx === 0) { return defaultValue; } // Clamp between 0 ~ base return clamp(calculatedValue, 0, base); } function getProgress(pos, range) { // start, anchor, end // -1 , 0 , 1 var min = range[0], center = range[1], max = range[2]; if (pos > center && max - center) { // 0 ~ 1 return (pos - center) / (max - center); } else if (pos < center && center - min) { // -1 ~ 0 return (pos - center) / (center - min); } else if (pos !== center && max - min) { return (pos - min) / (max - min); } return 0; } function findIndex(iterable, callback) { for (var i = 0; i < iterable.length; i += 1) { var element = iterable[i]; if (element && callback(element)) { return i; } } return -1; } // return [0, 1, ...., max - 1] function counter(max) { var counterArray = []; for (var i = 0; i < max; i += 1) { counterArray[i] = i; } return counterArray; } // Circulate number between range [min, max] /* * "indexed" means min and max is not same, so if it's true "min - 1" should be max * While if it's false, "min - 1" should be "max - 1" * use `indexed: true` when it should be used for circulating integers like index * or `indexed: false` when it should be used for something like positions. */ function circulate(value, min, max, indexed) { var size = indexed ? max - min + 1 : max - min; if (value < min) { var offset = indexed ? (min - value - 1) % size : (min - value) % size; value = max - offset; } else if (value > max) { var offset = indexed ? (value - max - 1) % size : (value - max) % size; value = min + offset; } return value; } function restoreStyle(element, originalStyle) { originalStyle.className ? element.setAttribute("class", originalStyle.className) : element.removeAttribute("class"); originalStyle.style ? element.setAttribute("style", originalStyle.style) : element.removeAttribute("style"); } /** * Decorator that makes the method of flicking available in the framework. * @ko 프레임워크에서 플리킹의 메소드를 사용할 수 있게 하는 데코레이터. * @memberof eg.Flicking * @private * @example * ```js * import Flicking, { withFlickingMethods } from "@egjs/flicking"; * * class Flicking extends React.Component<Partial<FlickingProps & FlickingOptions>> { * &#64;withFlickingMethods * private flicking: Flicking; * } * ``` */ function withFlickingMethods(prototype, flickingName) { Object.keys(FLICKING_METHODS).forEach(function (name) { if (prototype[name]) { return; } prototype[name] = function () { var _a; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var result = (_a = this[flickingName])[name].apply(_a, args); // fix `this` type to return your own `flicking` instance to the instance using the decorator. if (result === this[flickingName]) { return this; } else { return result; } }; }); } function getBbox(element, useOffset) { var bbox; if (useOffset) { bbox = { x: 0, y: 0, width: element.offsetWidth, height: element.offsetHeight }; } else { var clientRect = element.getBoundingClientRect(); bbox = { x: clientRect.left, y: clientRect.top, width: clientRect.width, height: clientRect.height }; } return bbox; } /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var Panel = /*#__PURE__*/ function () { function Panel(element, index, viewport) { this.viewport = viewport; this.prevSibling = null; this.nextSibling = null; this.clonedPanels = []; this.state = { index: index, position: 0, relativeAnchorPosition: 0, size: 0, isClone: false, isVirtual: false, cloneIndex: -1, originalStyle: { className: "", style: "" }, cachedBbox: null }; this.setElement(element); } var __proto = Panel.prototype; __proto.resize = function (givenBbox) { var state = this.state; var options = this.viewport.options; var bbox = givenBbox ? givenBbox : this.getBbox(); this.state.cachedBbox = bbox; var prevSize = state.size; state.size = options.horizontal ? bbox.width : bbox.height; if (prevSize !== state.size) { state.relativeAnchorPosition = parseArithmeticExpression(options.anchor, state.size); } if (!state.isClone) { this.clonedPanels.forEach(function (panel) { var cloneState = panel.state; cloneState.size = state.size; cloneState.cachedBbox = state.cachedBbox; cloneState.relativeAnchorPosition = state.relativeAnchorPosition; }); } }; __proto.unCacheBbox = function () { this.state.cachedBbox = null; }; __proto.getProgress = function () { var viewport = this.viewport; var options = viewport.options; var panelCount = viewport.panelManager.getPanelCount(); var scrollAreaSize = viewport.getScrollAreaSize(); var relativeIndex = (options.circular ? Math.floor(this.getPosition() / scrollAreaSize) * panelCount : 0) + this.getIndex(); var progress = relativeIndex - viewport.getCurrentProgress(); return progress; }; __proto.getOutsetProgress = function () { var viewport = this.viewport; var outsetRange = [-this.getSize(), viewport.getRelativeHangerPosition() - this.getRelativeAnchorPosition(), viewport.getSize()]; var relativePanelPosition = this.getPosition() - viewport.getCameraPosition(); var outsetProgress = getProgress(relativePanelPosition, outsetRange); return outsetProgress; }; __proto.getVisibleRatio = function () { var viewport = this.viewport; var panelSize = this.getSize(); var relativePanelPosition = this.getPosition() - viewport.getCameraPosition(); var rightRelativePanelPosition = relativePanelPosition + panelSize; var visibleSize = Math.min(viewport.getSize(), rightRelativePanelPosition) - Math.max(relativePanelPosition, 0); var visibleRatio = visibleSize >= 0 ? visibleSize / panelSize : 0; return visibleRatio; }; __proto.focus = function (duration) { var viewport = this.viewport; var currentPanel = viewport.getCurrentPanel(); var hangerPosition = viewport.getHangerPosition(); var anchorPosition = this.getAnchorPosition(); if (hangerPosition === anchorPosition || !currentPanel) { return; } var currentPosition = currentPanel.getPosition(); var eventType = currentPosition === this.getPosition() ? "" : EVENTS.CHANGE; viewport.moveTo(this, viewport.findEstimatedPosition(this), eventType, null, duration); }; __proto.update = function (updateFunction, shouldResize) { if (updateFunction === void 0) { updateFunction = null; } if (shouldResize === void 0) { shouldResize = true; } var identicalPanels = this.getIdenticalPanels(); if (updateFunction) { identicalPanels.forEach(function (eachPanel) { updateFunction(eachPanel.getElement()); }); } if (shouldResize) { identicalPanels.forEach(function (eachPanel) { eachPanel.unCacheBbox(); }); this.viewport.addVisiblePanel(this); this.viewport.resize(); } }; __proto.prev = function () { var viewport = this.viewport; var options = viewport.options; var prevSibling = this.prevSibling; if (!prevSibling) { return null; } var currentIndex = this.getIndex(); var currentPosition = this.getPosition(); var prevPanelIndex = prevSibling.getIndex(); var prevPanelPosition = prevSibling.getPosition(); var prevPanelSize = prevSibling.getSize(); var hasEmptyPanelBetween = currentIndex - prevPanelIndex > 1; var notYetMinPanel = options.infinite && currentIndex > 0 && prevPanelIndex > currentIndex; if (hasEmptyPanelBetween || notYetMinPanel) { // Empty panel exists between return null; } var newPosition = currentPosition - prevPanelSize - options.gap; var prevPanel = prevSibling; if (prevPanelPosition !== newPosition) { prevPanel = prevSibling.clone(prevSibling.getCloneIndex(), true); prevPanel.setPosition(newPosition); } return prevPanel; }; __proto.next = function () { var viewport = this.viewport; var options = viewport.options; var nextSibling = this.nextSibling; var lastIndex = viewport.panelManager.getLastIndex(); if (!nextSibling) { return null; } var currentIndex = this.getIndex(); var currentPosition = this.getPosition(); var nextPanelIndex = nextSibling.getIndex(); var nextPanelPosition = nextSibling.getPosition(); var hasEmptyPanelBetween = nextPanelIndex - currentIndex > 1; var notYetMaxPanel = options.infinite && currentIndex < lastIndex && nextPanelIndex < currentIndex; if (hasEmptyPanelBetween || notYetMaxPanel) { return null; } var newPosition = currentPosition + this.getSize() + options.gap; var nextPanel = nextSibling; if (nextPanelPosition !== newPosition) { nextPanel = nextSibling.clone(nextSibling.getCloneIndex(), true); nextPanel.setPosition(newPosition); } return nextPanel; }; __proto.insertBefore = function (element) { var viewport = this.viewport; var parsedElements = parseElement(element); var firstPanel = viewport.panelManager.firstPanel(); var prevSibling = this.prevSibling; // Finding correct inserting index // While it should insert removing empty spaces, // It also should have to be bigger than prevSibling' s index var targetIndex = prevSibling && firstPanel.getIndex() !== this.getIndex() ? Math.max(prevSibling.getIndex() + 1, this.getIndex() - parsedElements.length) : Math.max(this.getIndex() - parsedElements.length, 0); return viewport.insert(targetIndex, parsedElements); }; __proto.insertAfter = function (element) { return this.viewport.insert(this.getIndex() + 1, element); }; __proto.remove = function () { this.viewport.remove(this.getIndex()); return this; }; __proto.destroy = function (option) { if (!option.preserveUI) { var originalStyle = this.state.originalStyle; restoreStyle(this.element, originalStyle); } // release resources for (var x in this) { this[x] = null; } }; __proto.getElement = function () { return this.element; }; __proto.getAnchorPosition = function () { return this.state.position + this.state.relativeAnchorPosition; }; __proto.getRelativeAnchorPosition = function () { return this.state.relativeAnchorPosition; }; __proto.getIndex = function () { return this.state.index; }; __proto.getPosition = function () { return this.state.position; }; __proto.getSize = function () { return this.state.size; }; __proto.getBbox = function () { var state = this.state; var viewport = this.viewport; var element = this.element; var options = viewport.options; if (!element) { state.cachedBbox = { x: 0, y: 0, width: 0, height: 0 }; } else if (!state.cachedBbox) { var wasVisible = Boolean(element.parentNode); var cameraElement = viewport.getCameraElement(); if (!wasVisible) { cameraElement.appendChild(element); viewport.addVisiblePanel(this); } state.cachedBbox = getBbox(element, options.useOffset); if (!wasVisible && viewport.options.renderExternal) { cameraElement.removeChild(element); } } return state.cachedBbox; }; __proto.isClone = function () { return this.state.isClone; }; __proto.getOverlappedClass = function (classes) { var element = this.element; for (var _i = 0, classes_1 = classes; _i < classes_1.length; _i++) { var className = classes_1[_i]; if (hasClass(element, className)) { return className; } } }; __proto.getCloneIndex = function () { return this.state.cloneIndex; }; __proto.getClonedPanels = function () { var state = this.state; return state.isClone ? this.original.getClonedPanels() : this.clonedPanels; }; __proto.getIdenticalPanels = function () { var state = this.state; return state.isClone ? this.original.getIdenticalPanels() : __spreadArrays([this], this.clonedPanels); }; __proto.getOriginalPanel = function () { return this.state.isClone ? this.original : this; }; __proto.setIndex = function (index) { var state = this.state; state.index = index; this.clonedPanels.forEach(function (panel) { return panel.state.index = index; }); }; __proto.setPosition = function (pos) { this.state.position = pos; return this; }; __proto.setPositionCSS = function (offset) { if (offset === void 0) { offset = 0; } if (!this.element) { return; } var state = this.state; var pos = state.position; var options = this.viewport.options; var elementStyle = this.element.style; var currentElementStyle = options.horizontal ? elementStyle.left : elementStyle.top; var styleToApply = pos - offset + "px"; if (!state.isVirtual && currentElementStyle !== styleToApply) { options.horizontal ? elementStyle.left = styleToApply : elementStyle.top = styleToApply; } }; __proto.clone = function (cloneIndex, isVirtual, element) { if (isVirtual === void 0) { isVirtual = false; } var state = this.state; var viewport = this.viewport; var cloneElement = element; if (!cloneElement && this.element) { cloneElement = isVirtual ? this.element : this.element.cloneNode(true); } var clonedPanel = new Panel(cloneElement, state.index, viewport); var clonedState = clonedPanel.state; clonedPanel.original = state.isClone ? this.original : this; clonedState.isClone = true; clonedState.isVirtual = isVirtual; clonedState.cloneIndex = cloneIndex; // Inherit some state values clonedState.size = state.size; clonedState.relativeAnchorPosition = state.relativeAnchorPosition; clonedState.originalStyle = state.originalStyle; clonedState.cachedBbox = state.cachedBbox; if (!isVirtual) { this.clonedPanels.push(clonedPanel); } else { clonedPanel.prevSibling = this.prevSibling; clonedPanel.nextSibling = this.nextSibling; } return clonedPanel; }; __proto.removeElement = function () { if (!this.viewport.options.renderExternal) { var element = this.element; element.parentNode && element.parentNode.removeChild(element); } // Do the same thing for clones if (!this.state.isClone) { this.removeClonedPanelsAfter(0); } }; __proto.removeClonedPanelsAfter = function (start) { var options = this.viewport.options; var removingPanels = this.clonedPanels.splice(start); if (!options.renderExternal) { removingPanels.forEach(function (panel) { panel.removeElement(); }); } }; __proto.setElement = function (element) { if (!element) { return; } var currentElement = this.element; if (element !== currentElement) { var options = this.viewport.options; if (currentElement) { if (options.horizontal) { element.style.left = currentElement.style.left; } else { element.style.top = currentElement.style.top; } } else { var originalStyle = this.state.originalStyle; originalStyle.className = element.getAttribute("class"); originalStyle.style = element.getAttribute("style"); } this.element = element; if (options.classPrefix) { addClass(element, options.classPrefix + "-panel"); } // Update size info after applying panel css applyCSS(this.element, DEFAULT_PANEL_CSS); } }; return Panel; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var PanelManager = /*#__PURE__*/ function () { function PanelManager(cameraElement, options) { this.cameraElement = cameraElement; this.panels = []; this.clones = []; this.range = { min: -1, max: -1 }; this.length = 0; this.cloneCount = 0; this.options = options; this.lastIndex = options.lastIndex; } var __proto = PanelManager.prototype; __proto.firstPanel = function () { return this.panels[this.range.min]; }; __proto.lastPanel = function () { return this.panels[this.range.max]; }; __proto.allPanels = function () { return __spreadArrays(this.panels, this.clones.reduce(function (allClones, clones) { return __spreadArrays(allClones, clones); }, [])); }; __proto.originalPanels = function () { return this.panels; }; __proto.clonedPanels = function () { return this.clones; }; __proto.replacePanels = function (newPanels, newClones) { this.panels = newPanels; this.clones = newClones; this.range = { min: findIndex(newPanels, function (panel) { return Boolean(panel); }), max: newPanels.length - 1 }; this.length = newPanels.filter(function (panel) { return Boolean(panel); }).length; }; __proto.has = function (index) { return !!this.panels[index]; }; __proto.get = function (index) { return this.panels[index]; }; __proto.getPanelCount = function () { return this.length; }; __proto.getLastIndex = function () { return this.lastIndex; }; __proto.getRange = function () { return this.range; }; __proto.getCloneCount = function () { return this.cloneCount; }; __proto.setLastIndex = function (lastIndex) { this.lastIndex = lastIndex; var firstPanel = this.firstPanel(); var lastPanel = this.lastPanel(); if (!firstPanel || !lastPanel) { return; // no meaning of updating range & length } // Remove panels above new last index var range = this.range; if (lastPanel.getIndex() > lastIndex) { var removingPanels = this.panels.splice(lastIndex + 1); this.length -= removingPanels.length; var firstRemovedPanel = removingPanels.filter(function (panel) { return !!panel; })[0]; var possibleLastPanel = firstRemovedPanel.prevSibling; if (possibleLastPanel) { range.max = possibleLastPanel.getIndex(); } else { range.min = -1; range.max = -1; } if (this.shouldRender()) { removingPanels.forEach(function (panel) { return panel.removeElement(); }); } } }; __proto.setCloneCount = function (cloneCount) { this.cloneCount = cloneCount; }; // Insert at index // Returns pushed elements from index, inserting at 'empty' position doesn't push elements behind it __proto.insert = function (index, newPanels) { var panels = this.panels; var range = this.range; var isCircular = this.options.circular; var lastIndex = this.lastIndex; // Find first panel that index is greater than inserting index var nextSibling = this.findFirstPanelFrom(index); // if it's null, element will be inserted at last position // https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax var firstPanel = this.firstPanel(); var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element this.insertNewPanels(newPanels, siblingElement); var pushedIndex = newPanels.length; // Like when setting index 50 while visible panels are 0, 1, 2 if (index > range.max) { newPanels.forEach(function (panel, offset) { panels[index + offset] = panel; }); } else { var panelsAfterIndex = panels.slice(index, index + newPanels.length); // Find empty from beginning var emptyPanelCount = findIndex(panelsAfterIndex, function (panel) { return !!panel; }); if (emptyPanelCount < 0) { // All empty emptyPanelCount = panelsAfterIndex.length; } pushedIndex = newPanels.length - emptyPanelCount; // Insert removing empty panels panels.splice.apply(panels, __spreadArrays([index, emptyPanelCount], newPanels)); // Remove panels after last index if (panels.length > lastIndex + 1) { var removedPanels = panels.splice(lastIndex + 1).filter(function (panel) { return Boolean(panel); }); this.length -= removedPanels.length; // Find first var newLastIndex = lastIndex - findIndex(this.panels.concat().reverse(), function (panel) { return !!panel; }); // Can be filled with empty after newLastIndex this.panels.splice(newLastIndex + 1); this.range.max = newLastIndex; if (this.shouldRender()) { removedPanels.forEach(function (panel) { return panel.removeElement(); }); } } } // Update index of previous panels if (pushedIndex > 0) { panels.slice(index + newPanels.length).forEach(function (panel) { panel.setIndex(panel.getIndex() + pushedIndex); }); } // Update state this.length += newPanels.length; this.updateIndex(index); if (isCircular) { this.addNewClones(index, newPanels, newPanels.length - pushedIndex, nextSibling); var clones = this.clones; var panelCount_1 = this.panels.length; if (clones[0] && clones[0].length > lastIndex + 1) { clones.forEach(function (cloneSet) { cloneSet.splice(panelCount_1); }); } } return pushedIndex; }; __proto.replace = function (index, newPanels) { var panels = this.panels; var range = this.range; var options = this.options; var isCircular = options.circular; // Find first panel that index is greater than inserting index var nextSibling = this.findFirstPanelFrom(index + newPanels.length); // if it's null, element will be inserted at last position // https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax var firstPanel = this.firstPanel(); var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element this.insertNewPanels(newPanels, siblingElement); if (index > range.max) { // Temporarily insert null at index to use splice() panels[index] = null; } var replacedPanels = panels.splice.apply(panels, __spreadArrays([index, newPanels.length], newPanels)); var wasNonEmptyCount = replacedPanels.filter(function (panel) { return Boolean(panel); }).length; // Suppose inserting [1, 2, 3] at 0 position when there were [empty, 1] // So length should be increased by 3(inserting panels) - 1(non-empty panels) this.length += newPanels.length - wasNonEmptyCount; this.updateIndex(index); if (isCircular) { this.addNewClones(index, newPanels, newPanels.length, nextSibling); } if (this.shouldRender()) { replacedPanels.forEach(function (panel) { return panel && panel.removeElement(); }); } return replacedPanels; }; __proto.remove = function (index, deleteCount) { if (deleteCount === void 0) { deleteCount = 1; } var isCircular = this.options.circular; var panels = this.panels; var clones = this.clones; // Delete count should be equal or larger than 0 deleteCount = Math.max(deleteCount, 0); var deletedPanels = panels.splice(index, deleteCount).filter(function (panel) { return !!panel; }); if (this.shouldRender()) { deletedPanels.forEach(function (panel) { return panel.removeElement(); }); } if (isCircular) { clones.forEach(function (cloneSet) { cloneSet.splice(index, deleteCount); }); } // Update indexes panels.slice(index).forEach(function (panel) { panel.setIndex(panel.getIndex() - deleteCount); }); // Check last panel is empty var lastIndex = panels.length - 1; if (!panels[lastIndex]) { var reversedPanels = panels.concat().reverse(); var nonEmptyIndexFromLast = findIndex(reversedPanels, function (panel) { return !!panel; }); lastIndex = nonEmptyIndexFromLast < 0 ? -1 // All empty : lastIndex - nonEmptyIndexFromLast; // Remove all empty panels from last panels.splice(lastIndex + 1); if (isCircular) { clones.forEach(function (cloneSet) { cloneSet.splice(lastIndex + 1); }); } } // Update range & length this.range = { min: findIndex(panels, function (panel) { return !!panel; }), max: lastIndex }; this.length -= deletedPanels.length; if (this.length <= 0) { // Reset clones this.clones = []; this.cloneCount = 0; } return deletedPanels; }; __proto.chainAllPanels = function () { var allPanels = this.allPanels().filter(function (panel) { return !!panel; }); var allPanelsCount = allPanels.length; if (allPanelsCount <= 1) { return; } allPanels.slice(1, allPanels.length - 1).forEach(function (panel, idx) { var prevPanel = allPanels[idx]; var nextPanel = allPanels[idx + 2]; panel.prevSibling = prevPanel; panel.nextSibling = nextPanel; }); var firstPanel = allPanels[0]; var lastPanel = allPanels[allPanelsCount - 1]; firstPanel.prevSibling = null; firstPanel.nextSibling = allPanels[1]; lastPanel.prevSibling = allPanels[allPanelsCount - 2]; lastPanel.nextSibling = null; if (this.options.circular) { firstPanel.prevSibling = lastPanel; lastPanel.nextSibling = firstPanel; } }; __proto.insertClones = function (cloneIndex, index, clonedPanels, deleteCount) { if (deleteCount === void 0) { deleteCount = 0; } var clones = this.clones; var lastIndex = this.lastIndex; if (!clones[cloneIndex]) { var newClones_1 = []; clonedPanels.forEach(function (panel, offset) { newClones_1[index + offset] = panel; }); clones[cloneIndex] = newClones_1; } else { var insertTarget_1 = clones[cloneIndex]; if (index >= insertTarget_1.length) { clonedPanels.forEach(function (panel, offset) { insertTarget_1[index + offset] = panel; }); } else { insertTarget_1.splice.apply(insertTarget_1, __spreadArrays([index, deleteCount], clonedPanels)); // Remove panels after last index if (clonedPanels.length > lastIndex + 1) { clonedPanels.splice(lastIndex + 1); } } } }; // clones are operating in set __proto.removeClonesAfter = function (cloneIndex) { var panels = this.panels; panels.forEach(function (panel) { panel.removeClonedPanelsAfter(cloneIndex); }); this.clones.splice(cloneIndex); }; __proto.findPanelOf = function (element) { var allPanels = this.allPanels(); for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) { var panel = allPanels_1[_i]; if (!panel) { continue; } var panelElement = panel.getElement(); if (panelElement.contains(element)) { return panel; } } }; __proto.findFirstPanelFrom = function (index) { for (var _i = 0, _a = this.panels.slice(index); _i < _a.length; _i++) { var panel = _a[_i]; if (panel && panel.getIndex() >= index && panel.getElement().parentNode) { return panel; } } }; __proto.addNewClones = function (index, originalPanels, deleteCount, nextSibling) { var _this = this; var cameraElement = this.cameraElement; var cloneCount = this.getCloneCount(); var lastPanel = this.lastPanel(); var lastPanelClones = lastPanel ? lastPanel.getClonedPanels() : []; var nextSiblingClones = nextSibling ? nextSibling.getClonedPanels() : []; var _loop_1 = function (cloneIndex) { var cloneNextSibling = nextSiblingClones[cloneIndex]; var lastPanelSibling = lastPanelClones[cloneIndex]; var cloneSiblingElement = cloneNextSibling ? cloneNextSibling.getElement() : lastPanelSibling ? lastPanelSibling.getElement().nextElementSibling : null; var newClones = originalPanels.map(function (panel) { var clone = panel.clone(cloneIndex); if (_this.shouldRender()) { cameraElement.insertBefore(clone.getElement(), cloneSiblingElement); } return clone; }); this_1.insertClones(cloneIndex, index, newClones, deleteCount); }; var this_1 = this; for (var _i = 0, _a = counter(cloneCount); _i < _a.length; _i++) { var cloneIndex = _a[_i]; _loop_1(cloneIndex); } }; __proto.updateIndex = function (insertingIndex) { var panels = this.panels; var range = this.range; var newLastIndex = panels.length - 1; if (newLastIndex > range.max) { range.max = newLastIndex; } if (insertingIndex < range.min || range.min < 0) { range.min = insertingIndex; } }; __proto.insertNewPanels = function (newPanels, siblingElement) { if (this.shouldRender()) { var fragment_1 = document.createDocumentFragment(); newPanels.forEach(function (panel) { return fragment_1.appendChild(panel.getElement()); }); this.cameraElement.insertBefore(fragment_1, siblingElement); } }; __proto.shouldRender = function () { var options = this.options; return !options.renderExternal && !options.renderOnlyVisible; }; return PanelManager; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var State = /*#__PURE__*/ function () { function State() { this.delta = 0; this.direction = null; this.targetPanel = null; this.lastPosition = 0; } var __proto = State.prototype; __proto.onEnter = function (prevState) { this.delta = prevState.delta; this.direction = prevState.direction; this.targetPanel = prevState.targetPanel; this.lastPosition = prevState.lastPosition; }; __proto.onExit = function (nextState) {// DO NOTHING }; __proto.onHold = function (e, context) {// DO NOTHING }; __proto.onChange = function (e, context) {// DO NOTHING }; __proto.onRelease = function (e, context) {// DO NOTHING }; __proto.onAnimationEnd = function (e, context) {// DO NOTHING }; __proto.onFinish = function (e, context) {// DO NOTHING }; return State; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var IdleState = /*#__PURE__*/ function (_super) { __extends(IdleState, _super); function IdleState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.IDLE; _this.holding = false; _this.playing = false; return _this; } var __proto = IdleState.prototype; __proto.onEnter = function () { this.direction = null; this.targetPanel = null; this.delta = 0; this.lastPosition = 0; }; __proto.onHold = function (e, _a) { var flicking = _a.flicking, viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; // Shouldn't do any action until any panels on flicking area if (flicking.getPanelCount() <= 0) { if (viewport.options.infinite) { viewport.moveCamera(viewport.getCameraPosition(), e); } transitTo(STATE_TYPE.DISABLED); return; } this.lastPosition = viewport.getCameraPosition(); triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () { transitTo(STATE_TYPE.HOLDING); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; // By methods call __proto.onChange = function (e, context) { var triggerEvent = context.triggerEvent, transitTo = context.transitTo; triggerEvent(EVENTS.MOVE_START, e, false).onSuccess(function () { // Trigger AnimatingState's onChange, to trigger "move" event immediately transitTo(STATE_TYPE.ANIMATING).onChange(e, context); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; return IdleState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var HoldingState = /*#__PURE__*/ function (_super) { __extends(HoldingState, _super); function HoldingState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.HOLDING; _this.holding = true; _this.playing = true; _this.releaseEvent = null; return _this; } var __proto = HoldingState.prototype; __proto.onChange = function (e, context) { var flicking = context.flicking, triggerEvent = context.triggerEvent, transitTo = context.transitTo; var offset = flicking.options.horizontal ? e.inputEvent.offsetX : e.inputEvent.offsetY; this.direction = offset < 0 ? DIRECTION.NEXT : DIRECTION.PREV; triggerEvent(EVENTS.MOVE_START, e, true).onSuccess(function () { // Trigger DraggingState's onChange, to trigger "move" event immediately transitTo(STATE_TYPE.DRAGGING).onChange(e, context); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onRelease = function (e, context) { var viewport = context.viewport, triggerEvent = context.triggerEvent, transitTo = context.transitTo; triggerEvent(EVENTS.HOLD_END, e, true); if (e.delta.flick !== 0) { // Sometimes "release" event on axes triggered before "change" event // Especially if user flicked panel fast in really short amount of time // if delta is not zero, that means above case happened. // Event flow should be HOLD_START -> MOVE_START -> MOVE -> HOLD_END // At least one move event should be included between holdStart and holdEnd e.setTo({ flick: viewport.getCameraPosition() }, 0); transitTo(STATE_TYPE.IDLE); return; } // Can't handle select event here, // As "finish" axes event happens this.releaseEvent = e; }; __proto.onFinish = function (e, _a) { var viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; // Should transite to IDLE state before select event // As user expects hold is already finished transitTo(STATE_TYPE.IDLE); if (!this.releaseEvent) { return; } // Handle release event here // To prevent finish event called twice var releaseEvent = this.releaseEvent; // Static click var srcEvent = releaseEvent.inputEvent.srcEvent; var clickedElement; if (srcEvent.type === "touchend") { var touchEvent = srcEvent; var touch = touchEvent.changedTouches[0]; clickedElement = document.elementFromPoint(touch.clientX, touch.clientY); } else { clickedElement = srcEvent.target; } var clickedPanel = viewport.panelManager.findPanelOf(clickedElement); var cameraPosition = viewport.getCameraPosition(); if (clickedPanel) { var clickedPanelPosition = clickedPanel.getPosition(); var direction = clickedPanelPosition > cameraPosition ? DIRECTION.NEXT : clickedPanelPosition < cameraPosition ? DIRECTION.PREV : null; // Don't provide axes event, to use axes instance instead triggerEvent(EVENTS.SELECT, releaseEvent, true, { direction: direction, index: clickedPanel.getIndex(), panel: clickedPanel, element: clickedElement }); } }; return HoldingState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var DraggingState = /*#__PURE__*/ function (_super) { __extends(DraggingState, _super); function DraggingState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.DRAGGING; _this.holding = true; _this.playing = true; return _this; } var __proto = DraggingState.prototype; __proto.onChange = function (e, _a) { var moveCamera = _a.moveCamera, transitTo = _a.transitTo; if (!e.delta.flick) { return; } moveCamera(e).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onRelease = function (e, context) { var flicking = context.flicking, viewport = context.viewport, triggerEvent = context.triggerEvent, transitTo = context.transitTo, stopCamera = context.stopCamera; var delta = this.delta; var absDelta = Math.abs(delta); var options = flicking.options; var horizontal = options.horizontal; var moveType = viewport.moveType; var inputEvent = e.inputEvent; var velocity = horizontal ? inputEvent.velocityX : inputEvent.velocityY; var inputDelta = horizontal ? inputEvent.deltaX : inputEvent.deltaY; var isNextDirection = Math.abs(velocity) > 1 ? velocity < 0 : absDelta > 0 ? delta > 0 : inputDelta < 0; var swipeDistance = viewport.options.bound ? Math.max(absDelta, Math.abs(inputDelta)) : absDelta; var swipeAngle = inputEvent.deltaX ? Math.abs(180 * Math.atan(inputEvent.deltaY / inputEvent.deltaX) / Math.PI) : 90; var belowAngleThreshold = horizontal ? swipeAngle <= options.thresholdAngle : swipeAngle > options.thresholdAngle; var overThreshold = swipeDistance >= options.threshold && belowAngleThreshold; var moveTypeContext = { viewport: viewport, axesEvent: e, state: this, swipeDistance: swipeDistance, isNextDirection: isNextDirection }; // Update last position to cope with Axes's animating behavior // Axes uses start position when animation start triggerEvent(EVENTS.HOLD_END, e, true); var targetPanel = this.targetPanel; if (!overThreshold && targetPanel) { // Interrupted while animating var interruptDestInfo = moveType.findPanelWhenInterrupted(moveTypeContext); viewport.moveTo(interruptDestInfo.panel, interruptDestInfo.destPos, interruptDestInfo.eventType, e, interruptDestInfo.duration); transitTo(STATE_TYPE.ANIMATING); return; } var currentPanel = viewport.getCurrentPanel(); var nearestPanel = viewport.getNearestPanel(); if (!currentPanel || !nearestPanel) { // There're no panels e.stop(); transitTo(STATE_TYPE.IDLE); return; } var destInfo = overThreshold ? moveType.findTargetPanel(moveTypeContext) : moveType.findRestorePanel(moveTypeContext); viewport.moveTo(destInfo.panel, destInfo.destPos, destInfo.eventType, e, destInfo.duration).onSuccess(function () { transitTo(STATE_TYPE.ANIMATING); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); stopCamera(e); }); }; return DraggingState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var AnimatingState = /*#__PURE__*/ function (_super) { __extends(AnimatingState, _super); function AnimatingState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.ANIMATING; _this.holding = false; _this.playing = true; return _this; } var __proto = AnimatingState.prototype; __proto.onHold = function (e, _a) { var viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; var options = viewport.options; var scrollArea = viewport.getScrollArea(); var scrollAreaSize = viewport.getScrollAreaSize(); var loopCount = Math.floor((this.lastPosition + this.delta - scrollArea.prev) / scrollAreaSize); var targetPanel = this.targetPanel; if (options.circular && loopCount !== 0 && targetPanel) { var cloneCount = viewport.panelManager.getCloneCount(); var originalTargetPosition = targetPanel.getPosition(); // cloneIndex is from -1 to cloneCount - 1 var newCloneIndex = circulate(targetPanel.getCloneIndex() - loopCount, -1, cloneCount - 1, true); var newTargetPosition = originalTargetPosition - loopCount * scrollAreaSize; var newTargetPanel = targetPanel.getIdenticalPanels()[newCloneIndex + 1].clone(newCloneIndex, true); // Set new target panel considering looped count newTargetPanel.setPosition(newTargetPosition); this.targetPanel = newTargetPanel; } // Reset last position and delta this.delta = 0; this.lastPosition = viewport.getCameraPosition(); // Update current panel as current nearest panel viewport.setCurrentPanel(viewport.getNearestPanel()); triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () { transitTo(STATE_TYPE.DRAGGING); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onChange = function (e, _a) { var moveCamera = _a.moveCamera, transitTo = _a.transitTo; if (!e.delta.flick) { return; } moveCamera(e).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onFinish = function (e, _a) { var flicking = _a.flicking, viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; var isTrusted = e && e.isTrusted; viewport.options.bound ? viewport.setCurrentPanel(this.targetPanel) : viewport.setCurrentPanel(viewport.getNearestPanel()); if (flicking.options.adaptive) { viewport.updateAdaptiveSize(); } transitTo(STATE_TYPE.IDLE); viewport.updateCameraPosition(); triggerEvent(EVENTS.MOVE_END, e, isTrusted, { direction: this.direction }); }; return AnimatingState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var DisabledState = /*#__PURE__*/ function (_super) { __extends(DisabledState, _super); function DisabledState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.DISABLED; _this.holding = false; _this.playing = true; return _this; } var __proto = DisabledState.prototype; __proto.onAnimationEnd = function (e, _a) { var transitTo = _a.transitTo; transitTo(STATE_TYPE.IDLE); }; __proto.onChange = function (e, _a) { var viewport = _a.viewport, transitTo = _a.transitTo; // Can stop Axes's change event e.stop(); // Should update axes position as it's already changed at this moment viewport.updateAxesPosition(viewport.getCameraPosition()); transitTo(STATE_TYPE.IDLE); }; __proto.onRelease = function (e, _a) { var transitTo = _a.transitTo; // This is needed when stopped hold start event if (e.delta.flick === 0) { transitTo(STATE_TYPE.IDLE); } }; return DisabledState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var StateMachine = /*#__PURE__*/ function () { function StateMachine() { var _this = this; this.state = new IdleState(); this.transitTo = function (nextStateType) { var currentState = _this.state; if (currentState.type !== nextStateType) { var nextState = void 0; switch (nextStateType) { case STATE_TYPE.IDLE: nextState = new IdleState(); break; case STATE_TYPE.HOLDING: nextState = new HoldingState(); break; case STATE_TYPE.DRAGGING: nextState = new DraggingState(); break; case STATE_TYPE.ANIMATING: nextState = new AnimatingState(); break; case STATE_TYPE.DISABLED: nextState = new DisabledState(); break; } currentState.onExit(nextState); nextState.onEnter(currentState); _this.state = nextState; } return _this.state; }; } var __proto = StateMachine.prototype; __proto.fire = function (eventType, e, context) { var currentState = this.state; switch (eventType) { case AXES_EVENTS.HOLD: currentState.onHold(e, context); break; case AXES_EVENTS.CHANGE: currentState.onChange(e, context); break; case AXES_EVENTS.RELEASE: currentState.onRelease(e, context); break; case AXES_EVENTS.ANIMATION_END: currentState.onAnimationEnd(e, context); break; case AXES_EVENTS.FINISH: currentState.onFinish(e, context); break; } }; __proto.getState = function () { return this.state; }; return StateMachine; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var MoveType = /*#__PURE__*/ function () { function MoveType() {} var __proto = MoveType.prototype; __proto.is = function (type) { return type === this.type; }; __proto.findRestorePanel = function (ctx) { var viewport = ctx.viewport; var options = viewport.options; var panel = options.circular ? this.findRestorePanelInCircularMode(ctx) : viewport.getCurrentPanel(); return { panel: panel, destPos: viewport.findEstimatedPosition(panel), duration: options.duration, eventType: EVENTS.RESTORE }; }; __proto.findPanelWhenInterrupted = function (ctx) { var state = ctx.state, viewport = ctx.viewport; var targetPanel = state.targetPanel; return { panel: targetPanel, destPos: viewport.findEstimatedPosition(targetPanel), duration: viewport.options.duration, eventType: "" }; }; // Calculate minimum distance to "change" panel __proto.calcBrinkOfChange = function (ctx) { var viewport = ctx.viewport, isNextDirection = ctx.isNextDirection; var options = viewport.options; var currentPanel = viewport.getCurrentPanel(); var halfGap = options.gap / 2; var relativeAnchorPosition = currentPanel.getRelativeAnchorPosition(); // Minimum distance needed to decide prev/next panel as nearest /* * | Prev | Next | * |--------|--------------| * [][ |<-Anchor ][] <- Panel + Half-Gap */ var minimumDistanceToChange = isNextDirection ? currentPanel.getSize() - relativeAnchorPosition + halfGap : relativeAnchorPosition + halfGap; minimumDistanceToChange = Math.max(minimumDistanceToChange, options.threshold); return minimumDistanceToChange; }; __proto.findRestorePanelInCircularMode = function (ctx) { var viewport = ctx.viewport; var originalPanel = viewport.getCurrentPanel().getOriginalPanel(); var hangerPosition = viewport.getHangerPosition(); var firstClonedPanel = originalPanel.getIdenticalPanels()[1]; var lapped = Math.abs(originalPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition); return !ctx.isNextDirection && lapped ? firstClonedPanel : originalPanel; }; return MoveType; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var Snap = /*#__PURE__*/ function (_super) { __extends(Snap, _super); function Snap(count) { var _this = _super.call(this) || this; _this.type = MOVE_TYPE.SNAP; _this.count = count; return _this; } var __proto = Snap.prototype; __proto.findTargetPanel = function (ctx) { var viewport = ctx.viewport, axesEvent = ctx.axesEvent, swipeDistance = ctx.swipeDistance; var snapCount = this.count; var eventDelta = Math.abs(axesEvent.delta.flick); var currentPanel = viewport.getCurrentPanel(); var nearestPanel = viewport.getNearestPanel(); var minimumDistanceToChange = this.calcBrinkOfChange(ctx); var nearestIsCurrent = nearestPanel.getIndex() === currentPanel.getIndex(); // This can happen when bounce is 0 var shouldMoveWhenBounceIs0 = viewport.canSetBoundMode() && nearestIsCurrent; var shouldMoveToAdjacent = !viewport.isOutOfBound() && (swipeDistance <= minimumDistanceToChange || shouldMoveWhenBounceIs0); if (snapCount > 1 && eventDelta > minimumDistanceToChange) { return this.findSnappedPanel(ctx); } else if (shouldMoveToAdjacent) { return this.findAdjacentPanel(ctx); } else { return { panel: nearestPanel, duration: viewport.options.duration, destPos: viewport.findEstimatedPosition(nearestPanel), // As swipeDistance holds mouse/touch position change regardless of bounce option value // swipDistance > minimumDistanceToChange can happen in bounce area // Second condition is for handling that. eventType: swipeDistance <= minimumDistanceToChange || viewport.isOutOfBound() && nearestIsCurrent ? EVENTS.RESTORE : EVENTS.CHANGE }; } }; __proto.findSnappedPanel = function (ctx) { var axesEvent = ctx.axesEvent, viewport = ctx.viewport, state = ctx.state, isNextDirection = ctx.isNextDirection; var eventDelta = Math.abs(axesEvent.delta.flick); var minimumDistanceToChange = this.calcBrinkOfChange(ctx); var snapCount = this.count; var options = viewport.options; var scrollAreaSize = viewport.getScrollAreaSize(); var halfGap = options.gap / 2; var estimatedHangerPos = axesEvent.destPos.flick + viewport.getRelativeHangerPosition(); var panelToMove = viewport.getNearestPanel(); var cycleIndex = panelToMove.getCloneIndex() + 1; // 0(original) or 1(clone) var passedPanelCount = 0; while (passedPanelCount < snapCount) { // Since panelToMove holds also cloned panels, we should use original panel's position var originalPanel = panelToMove.getOriginalPanel(); var panelPosition = originalPanel.getPosition() + cycleIndex * scrollAreaSize; var panelSize = originalPanel.getSize(); var panelNextPosition = panelPosition + panelSize + halfGap; var panelPrevPosition = panelPosition - halfGap; // Current panelToMove contains destPos if (isNextDirection && panelNextPosition > estimatedHangerPos || !isNextDirection && panelPrevPosition < estimatedHangerPos) { break; } var siblingPanel = isNextDirection ? panelToMove.nextSibling : panelToMove.prevSibling; if (!siblingPanel) { break; } var panelIndex = panelToMove.getIndex(); var siblingIndex = siblingPanel.getIndex(); if (isNextDirection && siblingIndex <= panelIndex || !isNextDirection && siblingIndex >= panelIndex) { cycleIndex = isNextDirection ? cycleIndex + 1 : cycleIndex - 1; } panelToMove = siblingPanel; passedPanelCount += 1; } var originalPosition = panelToMove.getOriginalPanel().getPosition(); if (cycleIndex !== 0) { panelToMove = panelToMove.clone(panelToMove.getCloneIndex(), true); panelToMove.setPosition(originalPosition + cycleIndex * scrollAreaSize); } var defaultDuration = viewport.options.duration; var duration = clamp(axesEvent.duration, defaultDuration, defaultDuration * passedPanelCount); return { panel: panelToMove, destPos: viewport.findEstimatedPosition(panelToMove), duration: duration, eventType: Math.max(eventDelta, state.delta) > minimumDistanceToChange ? EVENTS.CHANGE : EVENTS.RESTORE }; }; __proto.findAdjacentPanel = function (ctx) { var viewport = ctx.viewport, isNextDirection = ctx.isNextDirection; var options = viewport.options; var currentIndex = viewport.getCurrentIndex(); var currentPanel = viewport.panelManager.get(currentIndex); var hangerPosition = viewport.getHangerPosition(); var scrollArea = viewport.getScrollArea(); var firstClonedPanel = currentPanel.getIdenticalPanels()[1]; var lapped = options.circular && Math.abs(currentPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition); // If lapped in circular mode, use first cloned panel as base panel var basePanel = lapped ? firstClonedPanel : currentPanel; var basePosition = basePanel.getPosition(); var adjacentPanel = isNextDirection ? basePanel.nextSibling : basePanel.prevSibling; var eventType = adjacentPanel ? EVENTS.CHANGE : EVENTS.RESTORE; var panelToMove = adjacentPanel ? adjacentPanel : basePanel; var targetRelativeAnchorPosition = panelToMove.getRelativeAnchorPosition(); var estimatedPanelPosition = options.circular ? isNextDirection ? basePosition + basePanel.getSize() + targetRelativeAnchorPosition + options.gap : basePosition - (panelToMove.getSize() - targetRelativeAnchorPosition) - options.gap : panelToMove.getAnchorPosition(); var estimatedPosition = estimatedPanelPosition - viewport.getRelativeHangerPosition(); var destPos = viewport.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition; return { panel: panelToMove, destPos: destPos, duration: options.duration, eventType: eventType }; }; return Snap; }(MoveType); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var FreeScroll = /*#__PURE__*/ function (_super) { __extends(FreeScroll, _super); function FreeScroll() { var _this = // Set snap count to Infinity _super.call(this, Infinity) || this; _this.type = MOVE_TYPE.FREE_SCROLL; return _this; } var __proto = FreeScroll.prototype; __proto.findTargetPanel = function (ctx) { var axesEvent = ctx.axesEvent, state = ctx.state, viewport = ctx.viewport; var destPos = axesEvent.destPos.flick; var minimumDistanceToChange = this.calcBrinkOfChange(ctx); var scrollArea = viewport.getScrollArea(); var currentPanel = viewport.getCurrentPanel(); var options = viewport.options; var delta = Math.abs(axesEvent.delta.flick + state.delta); if (delta > minimumDistanceToChange) { var destInfo = _super.prototype.findSnappedPanel.call(this, ctx); destInfo.duration = axesEvent.duration; destInfo.destPos = destPos; destInfo.eventType = !options.circular && destInfo.panel === currentPanel ? "" : EVENTS.CHANGE; return destInfo; } else { var estimatedPosition = options.circular ? circulate(destPos, scrollArea.prev, scrollArea.next, false) : destPos; estimatedPosition = clamp(estimatedPosition, scrollArea.prev, scrollArea.next); estimatedPosition += viewport.getRelativeHangerPosition(); var estimatedPanel = viewport.findNearestPanelAt(estimatedPosition); return { panel: estimatedPanel, destPos: destPos, duration: axesEvent.duration, eventType: "" }; } }; __proto.findRestorePanel = function (ctx) { return this.findTargetPanel(ctx); }; __proto.findPanelWhenInterrupted = function (ctx) { var viewport = ctx.viewport; return { panel: viewport.getNearestPanel(), destPos: viewport.getCameraPosition(), duration: 0, eventType: "" }; }; __proto.calcBrinkOfChange = function (ctx) { var viewport = ctx.viewport, isNextDirection = ctx.isNextDirection; var options = viewport.options; var currentPanel = viewport.getCurrentPanel(); var halfGap = options.gap / 2; var lastPosition = viewport.stateMachine.getState().lastPosition; var currentPanelPosition = currentPanel.getPosition(); // As camera can stop anywhere in free scroll mode, // minimumDistanceToChange should be calculated differently. // Ref #191(https://github.com/naver/egjs-flicking/issues/191) var lastHangerPosition = lastPosition + viewport.getRelativeHangerPosition(); var scrollAreaSize = viewport.getScrollAreaSize(); var minimumDistanceToChange = isNextDirection ? currentPanelPosition + currentPanel.getSize() - lastHangerPosition + halfGap : lastHangerPosition - currentPanelPosition + halfGap; minimumDistanceToChange = Math.abs(minimumDistanceToChange % scrollAreaSize); return Math.min(minimumDistanceToChange, scrollAreaSize - minimumDistanceToChange); }; return FreeScroll; }(Snap); var Viewport = /*#__PURE__*/ function () { function Viewport(flicking, options, triggerEvent) { var _this = this; this.plugins = []; this.stopCamera = function (axesEvent) { if (axesEvent && axesEvent.setTo) { axesEvent.setTo({ flick: _this.state.position }, 0); } _this.stateMachine.transitTo(STATE_TYPE.IDLE); }; this.flicking = flicking; this.triggerEvent = triggerEvent; this.state = { size: 0, position: 0, panelMaintainRatio: 0, relativeHangerPosition: 0, positionOffset: 0, scrollArea: { prev: 0, next: 0 }, translate: TRANSFORM, infiniteThreshold: 0, checkedIndexes: [], isAdaptiveCached: false, isViewportGiven: false, isCameraGiven: false, originalViewportStyle: { className: null, style: null }, originalCameraStyle: { className: null, style: null }, cachedBbox: null }; this.options = options; this.stateMachine = new StateMachine(); this.visiblePanels = []; this.panelBboxes = {}; this.build(); } var __proto = Viewport.prototype; __proto.moveTo = function (panel, destPos, eventType, axesEvent, duration) { var _this = this; if (duration === void 0) { duration = this.options.duration; } var state = this.state; var currentState = this.stateMachine.getState(); var currentPosition = state.position; var isTrusted = axesEvent ? axesEvent.isTrusted : false; var direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV; var eventResult; if (eventType === EVENTS.CHANGE) { eventResult = this.triggerEvent(EVENTS.CHANGE, axesEvent, isTrusted, { index: panel.getIndex(), panel: panel, direction: direction }); } else if (eventType === EVENTS.RESTORE) { eventResult = this.triggerEvent(EVENTS.RESTORE, axesEvent, isTrusted); } else { eventResult = { onSuccess: function (callback) { callback(); return this; }, onStopped: function () { return this; } }; } eventResult.onSuccess(function () { currentState.delta = 0; currentState.lastPosition = _this.getCameraPosition(); currentState.targetPanel = panel; currentState.direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV; if (destPos === currentPosition) { // no move _this.nearestPanel = panel; _this.currentPanel = panel; } if (axesEvent && axesEvent.setTo) { // freeScroll only occurs in release events axesEvent.setTo({ flick: destPos }, duration); } else { _this.axes.setTo({ flick: destPos }, duration); } }); return eventResult; }; __proto.moveCamera = function (pos, axesEvent) { var state = this.state; var options = this.options; var transform = state.translate.name; var scrollArea = state.scrollArea; // Update position & nearestPanel if (options.circular && !isBetween(pos, scrollArea.prev, scrollArea.next)) { pos = circulate(pos, scrollArea.prev, scrollArea.next, false); } state.position = pos; this.nearestPanel = this.findNearestPanel(); var nearestPanel = this.nearestPanel; var originalNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0; // From 0(panel position) to 1(panel position + panel size) // When it's on gap area value will be (val > 1 || val < 0) if (nearestPanel) { var hangerPosition = this.getHangerPosition(); var panelPosition = nearestPanel.getPosition(); var panelSize = nearestPanel.getSize(); var halfGap = options.gap / 2; // As panel's range is from panel position - half gap ~ panel pos + panel size + half gap state.panelMaintainRatio = (hangerPosition - panelPosition + halfGap) / (panelSize + 2 * halfGap); } else { state.panelMaintainRatio = 0; } this.checkNeedPanel(axesEvent); // Possibly modified after need panel, if it's looped var modifiedNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0; pos += modifiedNearestPosition - originalNearestPosition; state.position = pos; this.updateVisiblePanels(); // Offset is needed to fix camera layer size in visible-only rendering mode var posOffset = options.renderOnlyVisible ? state.positionOffset : 0; var moveVector = options.horizontal ? [-(pos - posOffset), 0] : [0, -(pos - posOffset)]; var moveCoord = moveVector.map(function (coord) { return Math.round(coord) + "px"; }).join(", "); this.cameraElement.style[transform] = state.translate.has3d ? "translate3d(" + moveCoord + ", 0px)" : "translate(" + moveCoord + ")"; }; __proto.unCacheBbox = function () { var state = this.state; var options = this.options; state.cachedBbox = null; this.visiblePanels = []; var viewportElement = this.viewportElement; if (!options.horizontal) { // Don't preserve previous width for adaptive resizing viewportElement.style.width = ""; } else { viewportElement.style.height = ""; } state.isAdaptiveCached = false; this.panelBboxes = {}; }; __proto.resize = function () { this.updateSize(); this.updateOriginalPanelPositions(); this.updateAdaptiveSize(); this.updateScrollArea(); this.updateClonePanels(); this.updateVisiblePanelPositions(); this.updateCameraPosition(); this.updatePlugins(); }; // Find nearest anchor from current hanger position __proto.findNearestPanel = function () { var state = this.state; var panelManager = this.panelManager; var hangerPosition = this.getHangerPosition(); if (this.isOutOfBound()) { var position = state.position; return position <= state.scrollArea.prev ? panelManager.firstPanel() : panelManager.lastPanel(); } return this.findNearestPanelAt(hangerPosition); }; __proto.findNearestPanelAt = function (position) { var panelManager = this.panelManager; var allPanels = panelManager.allPanels(); var minimumDistance = Infinity; var nearestPanel; for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) { var panel = allPanels_1[_i]; if (!panel) { continue; } var prevPosition = panel.getPosition(); var nextPosition = prevPosition + panel.getSize(); // Use shortest distance from panel's range var distance = isBetween(position, prevPosition, nextPosition) ? 0 : Math.min(Math.abs(prevPosition - position), Math.abs(nextPosition - position)); if (distance > minimumDistance) { break; } else if (distance === minimumDistance) { var minimumAnchorDistance = Math.abs(position - nearestPanel.getAnchorPosition()); var anchorDistance = Math.abs(position - panel.getAnchorPosition()); if (anchorDistance > minimumAnchorDistance) { break; } } minimumDistance = distance; nearestPanel = panel; } return nearestPanel; }; __proto.findNearestIdenticalPanel = function (panel) { var nearest = panel; var shortestDistance = Infinity; var hangerPosition = this.getHangerPosition(); var identicals = panel.getIdenticalPanels(); identicals.forEach(function (identical) { var anchorPosition = identical.getAnchorPosition(); var distance = Math.abs(anchorPosition - hangerPosition); if (distance < shortestDistance) { nearest = identical; shortestDistance = distance; } }); return nearest; }; // Find shortest camera position that distance is minimum __proto.findShortestPositionToPanel = function (panel) { var state = this.state; var options = this.options; var anchorPosition = panel.getAnchorPosition(); var hangerPosition = this.getHangerPosition(); var distance = Math.abs(hangerPosition - anchorPosition); var scrollAreaSize = state.scrollArea.next - state.scrollArea.prev; if (!options.circular) { var position = anchorPosition - state.relativeHangerPosition; return this.canSetBoundMode() ? clamp(position, state.scrollArea.prev, state.scrollArea.next) : position; } else { // If going out of viewport border is more efficient way of moving, choose that position return distance <= scrollAreaSize - distance ? anchorPosition - state.relativeHangerPosition : anchorPosition > hangerPosition // PREV TO NEXT ? anchorPosition - state.relativeHangerPosition - scrollAreaSize // NEXT TO PREV : anchorPosition - state.relativeHangerPosition + scrollAreaSize; } }; __proto.findEstimatedPosition = function (panel) { var scrollArea = this.getScrollArea(); var estimatedPosition = panel.getAnchorPosition() - this.getRelativeHangerPosition(); estimatedPosition = this.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition; return estimatedPosition; }; __proto.addVisiblePanel = function (panel) { if (this.getVisibleIndexOf(panel) < 0) { this.visiblePanels.push(panel); } }; __proto.enable = function () { if (!this.panInput) { this.createPanInput(); } }; __proto.disable = function () { if (this.panInput) { this.panInput.destroy(); this.panInput = null; this.stateMachine.transitTo(STATE_TYPE.IDLE); } }; __proto.insert = function (index, element) { var _this = this; var lastIndex = this.panelManager.getLastIndex(); // Index should not below 0 if (index < 0 || index > lastIndex) { return []; } var state = this.state; var options = this.options; var parsedElements = parseElement(element); var panels = parsedElements.map(function (el, idx) { return new Panel(el, index + idx, _this); }).slice(0, lastIndex - index + 1); if (panels.length <= 0) { return []; } var pushedIndex = this.panelManager.insert(index, panels); // ...then calc bbox for all panels this.resizePanels(panels); if (!this.currentPanel) { this.currentPanel = panels[0]; this.nearestPanel = panels[0]; var newCenterPanel = panels[0]; var newPanelPosition = this.findEstimatedPosition(newCenterPanel); state.position = newPanelPosition; this.updateAxesPosition(newPanelPosition); state.panelMaintainRatio = (newCenterPanel.getRelativeAnchorPosition() + options.gap / 2) / (newCenterPanel.getSize() + options.gap); } // Update checked indexes in infinite mode this.updateCheckedIndexes({ min: index, max: index }); state.checkedIndexes.forEach(function (indexes, idx) { var min = indexes[0], max = indexes[1]; if (index < min) { // Push checked index state.checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]); } }); this.resize(); return panels; }; __proto.replace = function (index, element) { var _this = this; var state = this.state; var options = this.options; var panelManager = this.panelManager; var lastIndex = panelManager.getLastIndex(); // Index should not below 0 if (index < 0 || index > lastIndex) { return []; } var parsedElements = parseElement(element); var panels = parsedElements.map(function (el, idx) { return new Panel(el, index + idx, _this); }).slice(0, lastIndex - index + 1); if (panels.length <= 0) { return []; } var replacedPanels = panelManager.replace(index, panels); replacedPanels.forEach(function (panel) { var visibleIndex = _this.getVisibleIndexOf(panel); if (visibleIndex > -1) { _this.visiblePanels.splice(visibleIndex, 1); } }); // ...then calc bbox for all panels this.resizePanels(panels); var currentPanel = this.currentPanel; var wasEmpty = !currentPanel; if (wasEmpty) { this.currentPanel = panels[0]; this.nearestPanel = panels[0]; var newCenterPanel = panels[0]; var newPanelPosition = this.findEstimatedPosition(newCenterPanel); state.position = newPanelPosition; this.updateAxesPosition(newPanelPosition); state.panelMaintainRatio = (newCenterPanel.getRelativeAnchorPosition() + options.gap / 2) / (newCenterPanel.getSize() + options.gap); } else if (isBetween(currentPanel.getIndex(), index, index + panels.length - 1)) { // Current panel is replaced this.currentPanel = panelManager.get(currentPanel.getIndex()); } // Update checked indexes in infinite mode this.updateCheckedIndexes({ min: index, max: index + panels.length - 1 }); this.resize(); return panels; }; __proto.remove = function (index, deleteCount) { if (deleteCount === void 0) { deleteCount = 1; } var state = this.state; // Index should not below 0 index = Math.max(index, 0); var panelManager = this.panelManager; var currentIndex = this.getCurrentIndex(); var removedPanels = panelManager.remove(index, deleteCount); if (isBetween(currentIndex, index, index + deleteCount - 1)) { // Current panel is removed // Use panel at removing index - 1 as new current panel if it exists var newCurrentIndex = Math.max(index - 1, panelManager.getRange().min); this.currentPanel = panelManager.get(newCurrentIndex); } // Update checked indexes in infinite mode if (deleteCount > 0) { // Check whether removing index will affect checked indexes // Suppose index 0 is empty and removed index 1, then checked index 0 should be deleted and vice versa. this.updateCheckedIndexes({ min: index - 1, max: index + deleteCount }); // Uncache visible panels to refresh panels this.visiblePanels = []; } if (panelManager.getPanelCount() <= 0) { this.currentPanel = undefined; this.nearestPanel = undefined; } this.resize(); var scrollArea = state.scrollArea; if (state.position < scrollArea.prev || state.position > scrollArea.next) { var newPosition = circulate(state.position, scrollArea.prev, scrollArea.next, false); this.moveCamera(newPosition); this.updateAxesPosition(newPosition); } return removedPanels; }; __proto.updateAdaptiveSize = function () { var state = this.state; var options = this.options; var horizontal = options.horizontal; var currentPanel = this.getCurrentPanel(); if (!currentPanel) { return; } var shouldApplyAdaptive = options.adaptive || !state.isAdaptiveCached; var viewportStyle = this.viewportElement.style; if (shouldApplyAdaptive) { var sizeToApply = void 0; if (options.adaptive) { var panelBbox = currentPanel.getBbox(); sizeToApply = horizontal ? panelBbox.height : panelBbox.width; } else { // Find minimum height of panels to maximum panel size var maximumPanelSize = this.panelManager.originalPanels().reduce(function (maximum, panel) { var panelBbox = panel.getBbox(); return Math.max(maximum, horizontal ? panelBbox.height : panelBbox.width); }, 0); sizeToApply = maximumPanelSize; } if (!state.isAdaptiveCached) { var viewportBbox = this.updateBbox(); sizeToApply = Math.max(sizeToApply, horizontal ? viewportBbox.height : viewportBbox.width); state.isAdaptiveCached = true; } var viewportSize = sizeToApply + "px"; if (horizontal) { viewportStyle.height = viewportSize; state.cachedBbox.height = sizeToApply; } else { viewportStyle.width = viewportSize; state.cachedBbox.width = sizeToApply; } } }; // Update camera position after resizing __proto.updateCameraPosition = function () { var state = this.state; var currentPanel = this.getCurrentPanel(); var cameraPosition = this.getCameraPosition(); var currentState = this.stateMachine.getState(); var isFreeScroll = this.moveType.is(MOVE_TYPE.FREE_SCROLL); var relativeHangerPosition = this.getRelativeHangerPosition(); var halfGap = this.options.gap / 2; if (currentState.holding || currentState.playing) { this.updateVisiblePanels(); return; } var newPosition; if (isFreeScroll) { var positionBounded = this.canSetBoundMode() && (cameraPosition === state.scrollArea.prev || cameraPosition === state.scrollArea.next); var nearestPanel = this.getNearestPanel(); // Preserve camera position if it is bound to scroll area limit newPosition = positionBounded || !nearestPanel ? cameraPosition : nearestPanel.getPosition() - halfGap + (nearestPanel.getSize() + 2 * halfGap) * state.panelMaintainRatio - relativeHangerPosition; } else { newPosition = currentPanel ? currentPanel.getAnchorPosition() - relativeHangerPosition : cameraPosition; } if (this.canSetBoundMode()) { newPosition = clamp(newPosition, state.scrollArea.prev, state.scrollArea.next); } // Pause & resume axes to prevent axes's "change" event triggered // This should be done before moveCamera, as moveCamera can trigger needPanel this.updateAxesPosition(newPosition); this.moveCamera(newPosition); }; __proto.updateBbox = function () { var state = this.state; var options = this.options; var viewportElement = this.viewportElement; if (!state.cachedBbox) { state.cachedBbox = getBbox(viewportElement, options.useOffset); } return state.cachedBbox; }; __proto.updatePlugins = function () { var _this = this; // update for resize this.plugins.forEach(function (plugin) { plugin.update && plugin.update(_this.flicking); }); }; __proto.destroy = function (option) { var _a; var state = this.state; var wrapper = this.flicking.getElement(); var viewportElement = this.viewportElement; var cameraElement = this.cameraElement; var originalPanels = this.panelManager.originalPanels(); this.removePlugins(this.plugins); if (!option.preserveUI) { restoreStyle(viewportElement, state.originalViewportStyle); restoreStyle(cameraElement, state.originalCameraStyle); if (!state.isCameraGiven && !this.options.renderExternal) { var topmostElement_1 = state.isViewportGiven ? viewportElement : wrapper; var deletingElement = state.isViewportGiven ? cameraElement : viewportElement; originalPanels.forEach(function (panel) { topmostElement_1.appendChild(panel.getElement()); }); topmostElement_1.removeChild(deletingElement); } } this.axes.destroy(); (_a = this.panInput) === null || _a === void 0 ? void 0 : _a.destroy(); originalPanels.forEach(function (panel) { panel.destroy(option); }); // release resources for (var x in this) { this[x] = null; } }; __proto.restore = function (status) { var panels = status.panels; var defaultIndex = this.options.defaultIndex; var cameraElement = this.cameraElement; var panelManager = this.panelManager; // Restore index cameraElement.innerHTML = panels.map(function (panel) { return panel.html; }).join(""); // Create panels first this.refreshPanels(); var createdPanels = panelManager.originalPanels(); // ...then order it by its index var orderedPanels = []; panels.forEach(function (panel, idx) { var createdPanel = createdPanels[idx]; createdPanel.setIndex(panel.index); createdPanel.setPosition(panel.position); orderedPanels[panel.index] = createdPanel; }); panelManager.replacePanels(orderedPanels, []); panelManager.setCloneCount(0); // No clones at this point var panelCount = panelManager.getPanelCount(); if (panelCount > 0) { this.currentPanel = panelManager.get(status.index) || panelManager.get(defaultIndex) || panelManager.firstPanel(); } else { this.currentPanel = undefined; } this.visiblePanels = orderedPanels.filter(function (panel) { return Boolean(panel); }); this.resize(); this.axes.setTo({ flick: status.position }, 0); this.moveCamera(status.position); }; __proto.calcVisiblePanels = function () { var allPanels = this.panelManager.allPanels(); if (this.options.renderOnlyVisible) { var cameraPos_1 = this.getCameraPosition(); var viewportSize_1 = this.getSize(); var basePanel = this.nearestPanel; var getNextPanel = function (panel) { var nextPanel = panel.nextSibling; if (nextPanel && nextPanel.getPosition() >= panel.getPosition()) { return nextPanel; } else { return null; } }; var getPrevPanel = function (panel) { var prevPanel = panel.prevSibling; if (prevPanel && prevPanel.getPosition() <= panel.getPosition()) { return prevPanel; } else { return null; } }; var isOutOfBoundNext = function (panel) { return panel.getPosition() >= cameraPos_1 + viewportSize_1; }; var isOutOfBoundPrev = function (panel) { return panel.getPosition() + panel.getSize() <= cameraPos_1; }; var getVisiblePanels = function (panel, getNext, isOutOfViewport) { var visiblePanels = []; var lastPanel = panel; while (true) { var nextPanel = getNext(lastPanel); if (!nextPanel || isOutOfViewport(nextPanel)) { break; } visiblePanels.push(nextPanel); lastPanel = nextPanel; } return visiblePanels; }; var panelCount_1 = this.panelManager.getPanelCount(); var getAbsIndex_1 = function (panel) { return panel.getIndex() + (panel.getCloneIndex() + 1) * panelCount_1; }; var nextPanels = getVisiblePanels(basePanel, getNextPanel, isOutOfBoundNext); var prevPanels = getVisiblePanels(basePanel, getPrevPanel, isOutOfBoundPrev); return __spreadArrays([basePanel], nextPanels, prevPanels).sort(function (panel1, panel2) { return getAbsIndex_1(panel1) - getAbsIndex_1(panel2); }); } else { return allPanels.filter(function (panel) { var outsetProgress = panel.getOutsetProgress(); return outsetProgress > -1 && outsetProgress < 1; }); } }; __proto.getCurrentPanel = function () { return this.currentPanel; }; __proto.getCurrentIndex = function () { var currentPanel = this.currentPanel; return currentPanel ? currentPanel.getIndex() : -1; }; __proto.getNearestPanel = function () { return this.nearestPanel; }; // Get progress from nearest panel __proto.getCurrentProgress = function () { var currentState = this.stateMachine.getState(); var nearestPanel = currentState.playing || currentState.holding ? this.nearestPanel : this.currentPanel; var panelManager = this.panelManager; if (!nearestPanel) { // There're no panels return NaN; } var _a = this.getScrollArea(), prevRange = _a.prev, nextRange = _a.next; var cameraPosition = this.getCameraPosition(); var isOutOfBound = this.isOutOfBound(); var prevPanel = nearestPanel.prevSibling; var nextPanel = nearestPanel.nextSibling; var hangerPosition = this.getHangerPosition(); var nearestAnchorPos = nearestPanel.getAnchorPosition(); if (isOutOfBound && prevPanel && nextPanel && cameraPosition < nextRange // On the basis of anchor, prevPanel is nearestPanel. && hangerPosition - prevPanel.getAnchorPosition() < nearestAnchorPos - hangerPosition) { nearestPanel = prevPanel; nextPanel = nearestPanel.nextSibling; prevPanel = nearestPanel.prevSibling; nearestAnchorPos = nearestPanel.getAnchorPosition(); } var nearestIndex = nearestPanel.getIndex() + (nearestPanel.getCloneIndex() + 1) * panelManager.getPanelCount(); var nearestSize = nearestPanel.getSize(); if (isOutOfBound) { var relativeHangerPosition = this.getRelativeHangerPosition(); if (nearestAnchorPos > nextRange + relativeHangerPosition) { // next bounce area: hangerPosition - relativeHangerPosition - nextRange hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - nextRange; } else if (nearestAnchorPos < prevRange + relativeHangerPosition) { // prev bounce area: hangerPosition - relativeHangerPosition - prevRange hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - prevRange; } } var hangerIsNextToNearestPanel = hangerPosition >= nearestAnchorPos; var gap = this.options.gap; var basePosition = nearestAnchorPos; var targetPosition = nearestAnchorPos; if (hangerIsNextToNearestPanel) { targetPosition = nextPanel ? nextPanel.getAnchorPosition() : nearestAnchorPos + nearestSize + gap; } else { basePosition = prevPanel ? prevPanel.getAnchorPosition() : nearestAnchorPos - nearestSize - gap; } var progressBetween = (hangerPosition - basePosition) / (targetPosition - basePosition); var startIndex = hangerIsNextToNearestPanel ? nearestIndex : prevPanel ? prevPanel.getIndex() : nearestIndex - 1; return startIndex + progressBetween; }; // Update axes flick position without triggering event __proto.updateAxesPosition = function (position) { var axes = this.axes; axes.off(); axes.setTo({ flick: position }, 0); axes.on(this.axesHandlers); }; __proto.getSize = function () { return this.state.size; }; __proto.getScrollArea = function () { return this.state.scrollArea; }; __proto.isOutOfBound = function () { var state = this.state; var options = this.options; var scrollArea = state.scrollArea; return !options.circular && options.bound && (state.position <= scrollArea.prev || state.position >= scrollArea.next); }; __proto.canSetBoundMode = function () { var options = this.options; return options.bound && !options.circular; }; __proto.getViewportElement = function () { return this.viewportElement; }; __proto.getCameraElement = function () { return this.cameraElement; }; __proto.getScrollAreaSize = function () { var scrollArea = this.state.scrollArea; return scrollArea.next - scrollArea.prev; }; __proto.getRelativeHangerPosition = function () { return this.state.relativeHangerPosition; }; __proto.getHangerPosition = function () { return this.state.position + this.state.relativeHangerPosition; }; __proto.getCameraPosition = function () { return this.state.position; }; __proto.getPositionOffset = function () { return this.state.positionOffset; }; __proto.getCheckedIndexes = function () { return this.state.checkedIndexes; }; __proto.getVisiblePanels = function () { return this.visiblePanels; }; __proto.setCurrentPanel = function (panel) { this.currentPanel = panel; }; __proto.setLastIndex = function (index) { var currentPanel = this.currentPanel; var panelManager = this.panelManager; panelManager.setLastIndex(index); if (currentPanel && currentPanel.getIndex() > index) { this.currentPanel = panelManager.lastPanel(); } this.resize(); }; __proto.setVisiblePanels = function (panels) { this.visiblePanels = panels; }; __proto.connectAxesHandler = function (handlers) { var axes = this.axes; this.axesHandlers = handlers; axes.on(handlers); }; __proto.addPlugins = function (plugins) { var _this = this; var newPlugins = [].concat(plugins); newPlugins.forEach(function (plugin) { plugin.init(_this.flicking); }); this.plugins = this.plugins.concat(newPlugins); return this; }; __proto.removePlugins = function (plugins) { var _this = this; var currentPlugins = this.plugins; var removedPlugins = [].concat(plugins); removedPlugins.forEach(function (plugin) { var index = currentPlugins.indexOf(plugin); if (index > -1) { currentPlugins.splice(index, 1); } plugin.destroy(_this.flicking); }); return this; }; __proto.updateCheckedIndexes = function (changedRange) { var state = this.state; var removed = 0; state.checkedIndexes.concat().forEach(function (indexes, idx) { var min = indexes[0], max = indexes[1]; // Can fill part of indexes in range if (changedRange.min <= max && changedRange.max >= min) { // Remove checked index from list state.checkedIndexes.splice(idx - removed, 1); removed++; } }); }; __proto.appendUncachedPanelElements = function (panels) { var _this = this; var options = this.options; var fragment = document.createDocumentFragment(); if (options.isEqualSize) { var prevVisiblePanels = this.visiblePanels; var equalSizeClasses_1 = options.isEqualSize; // for readability var cached_1 = {}; this.visiblePanels = []; Object.keys(this.panelBboxes).forEach(function (className) { cached_1[className] = true; }); panels.forEach(function (panel) { var overlappedClass = panel.getOverlappedClass(equalSizeClasses_1); if (overlappedClass && !cached_1[overlappedClass]) { if (!options.renderExternal) { fragment.appendChild(panel.getElement()); } _this.visiblePanels.push(panel); cached_1[overlappedClass] = true; } else if (!overlappedClass) { if (!options.renderExternal) { fragment.appendChild(panel.getElement()); } _this.visiblePanels.push(panel); } }); prevVisiblePanels.forEach(function (panel) { _this.addVisiblePanel(panel); }); } else { if (!options.renderExternal) { panels.forEach(function (panel) { return fragment.appendChild(panel.getElement()); }); } this.visiblePanels = panels.filter(function (panel) { return Boolean(panel); }); } if (!options.renderExternal) { this.cameraElement.appendChild(fragment); } }; __proto.updateClonePanels = function () { var panelManager = this.panelManager; // Clone panels in circular mode if (this.options.circular && panelManager.getPanelCount() > 0) { this.clonePanels(); this.updateClonedPanelPositions(); } panelManager.chainAllPanels(); }; __proto.getVisibleIndexOf = function (panel) { return findIndex(this.visiblePanels, function (visiblePanel) { return visiblePanel === panel; }); }; __proto.build = function () { this.setElements(); this.applyCSSValue(); this.setMoveType(); this.setAxesInstance(); this.refreshPanels(); this.setDefaultPanel(); this.resize(); this.moveToDefaultPanel(); }; __proto.setElements = function () { var state = this.state; var options = this.options; var wrapper = this.flicking.getElement(); var classPrefix = options.classPrefix; var viewportCandidate = wrapper.children[0]; var hasViewportElement = viewportCandidate && hasClass(viewportCandidate, classPrefix + "-viewport"); var viewportElement = hasViewportElement ? viewportCandidate : document.createElement("div"); var cameraCandidate = hasViewportElement ? viewportElement.children[0] : wrapper.children[0]; var hasCameraElement = cameraCandidate && hasClass(cameraCandidate, classPrefix + "-camera"); var cameraElement = hasCameraElement ? cameraCandidate : document.createElement("div"); if (!hasCameraElement) { cameraElement.className = classPrefix + "-camera"; var panelElements = hasViewportElement ? viewportElement.children : wrapper.children; // Make all panels to be a child of camera element // wrapper <- viewport <- camera <- panels[1...n] toArray(panelElements).forEach(function (child) { cameraElement.appendChild(child); }); } else { state.originalCameraStyle = { className: cameraElement.getAttribute("class"), style: cameraElement.getAttribute("style") }; } if (!hasViewportElement) { viewportElement.className = classPrefix + "-viewport"; // Add viewport element to wrapper wrapper.appendChild(viewportElement); } else { state.originalViewportStyle = { className: viewportElement.getAttribute("class"), style: viewportElement.getAttribute("style") }; } if (!hasCameraElement || !hasViewportElement) { viewportElement.appendChild(cameraElement); } this.viewportElement = viewportElement; this.cameraElement = cameraElement; state.isViewportGiven = hasViewportElement; state.isCameraGiven = hasCameraElement; }; __proto.applyCSSValue = function () { var options = this.options; var viewportElement = this.viewportElement; var cameraElement = this.cameraElement; var viewportStyle = this.viewportElement.style; // Set default css values for each element applyCSS(viewportElement, DEFAULT_VIEWPORT_CSS); applyCSS(cameraElement, DEFAULT_CAMERA_CSS); viewportElement.style.zIndex = "" + options.zIndex; if (options.horizontal) { viewportStyle.minHeight = "100%"; viewportStyle.width = "100%"; } else { viewportStyle.minWidth = "100%"; viewportStyle.height = "100%"; } if (options.overflow) { viewportStyle.overflow = "visible"; } this.panelManager = new PanelManager(this.cameraElement, options); }; __proto.setMoveType = function () { var moveType = this.options.moveType; switch (moveType.type) { case MOVE_TYPE.SNAP: this.moveType = new Snap(moveType.count); break; case MOVE_TYPE.FREE_SCROLL: this.moveType = new FreeScroll(); break; default: throw new Error("moveType is not correct!"); } }; __proto.setAxesInstance = function () { var state = this.state; var options = this.options; var scrollArea = state.scrollArea; this.axes = new Axes({ flick: { range: [scrollArea.prev, scrollArea.next], circular: options.circular, bounce: [0, 0] } }, { easing: options.panelEffect, deceleration: options.deceleration, interruptable: true }); this.createPanInput(); }; __proto.refreshPanels = function () { var _this = this; var panelManager = this.panelManager; // Panel elements were attached to camera element by Flicking class var panelElements = this.cameraElement.children; // Initialize panels var panels = toArray(panelElements).map(function (el, idx) { return new Panel(el, idx, _this); }); panelManager.replacePanels(panels, []); this.visiblePanels = panels.filter(function (panel) { return Boolean(panel); }); }; __proto.setDefaultPanel = function () { var options = this.options; var panelManager = this.panelManager; var indexRange = this.panelManager.getRange(); var index = clamp(options.defaultIndex, indexRange.min, indexRange.max); this.currentPanel = panelManager.get(index); }; __proto.clonePanels = function () { var state = this.state; var options = this.options; var panelManager = this.panelManager; var gap = options.gap; var viewportSize = state.size; var firstPanel = panelManager.firstPanel(); var lastPanel = panelManager.lastPanel(); // There're no panels exist if (!firstPanel) { return; } // For each panels, clone itself while last panel's position + size is below viewport size var panels = panelManager.originalPanels(); var reversedPanels = panels.concat().reverse(); var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + gap; var relativeAnchorPosition = firstPanel.getRelativeAnchorPosition(); var relativeHangerPosition = this.getRelativeHangerPosition(); var areaPrev = (relativeHangerPosition - relativeAnchorPosition) % sumOriginalPanelSize; var sizeSum = 0; var panelAtLeftBoundary; for (var _i = 0, reversedPanels_1 = reversedPanels; _i < reversedPanels_1.length; _i++) { var panel = reversedPanels_1[_i]; if (!panel) { continue; } sizeSum += panel.getSize() + gap; if (sizeSum >= areaPrev) { panelAtLeftBoundary = panel; break; } } var areaNext = (viewportSize - relativeHangerPosition + relativeAnchorPosition) % sumOriginalPanelSize; sizeSum = 0; var panelAtRightBoundary; for (var _a = 0, panels_1 = panels; _a < panels_1.length; _a++) { var panel = panels_1[_a]; if (!panel) { continue; } sizeSum += panel.getSize() + gap; if (sizeSum >= areaNext) { panelAtRightBoundary = panel; break; } } // Need one more set of clones on prev area of original panel 0 var needCloneOnPrev = panelAtLeftBoundary.getIndex() !== 0 && panelAtLeftBoundary.getIndex() <= panelAtRightBoundary.getIndex(); // Visible count of panel 0 on first screen var panel0OnFirstscreen = Math.ceil((relativeHangerPosition + firstPanel.getSize() - relativeAnchorPosition) / sumOriginalPanelSize) + Math.ceil((viewportSize - relativeHangerPosition + relativeAnchorPosition) / sumOriginalPanelSize) - 1; // duplication var cloneCount = panel0OnFirstscreen + (needCloneOnPrev ? 1 : 0); var prevCloneCount = panelManager.getCloneCount(); panelManager.setCloneCount(cloneCount); if (options.renderExternal) { return; } if (cloneCount > prevCloneCount) { var _loop_1 = function (cloneIndex) { var _a; var clones = panels.map(function (origPanel) { return origPanel.clone(cloneIndex); }); var fragment = document.createDocumentFragment(); clones.forEach(function (panel) { return fragment.appendChild(panel.getElement()); }); this_1.cameraElement.appendChild(fragment); (_a = this_1.visiblePanels).push.apply(_a, clones.filter(function (clone) { return Boolean(clone); })); panelManager.insertClones(cloneIndex, 0, clones); }; var this_1 = this; // should clone more for (var cloneIndex = prevCloneCount; cloneIndex < cloneCount; cloneIndex++) { _loop_1(cloneIndex); } } else if (cloneCount < prevCloneCount) { // should remove some panelManager.removeClonesAfter(cloneCount); } }; __proto.moveToDefaultPanel = function () { var state = this.state; var panelManager = this.panelManager; var options = this.options; var indexRange = this.panelManager.getRange(); var defaultIndex = clamp(options.defaultIndex, indexRange.min, indexRange.max); var defaultPanel = panelManager.get(defaultIndex); var defaultPosition = 0; if (defaultPanel) { defaultPosition = defaultPanel.getAnchorPosition() - state.relativeHangerPosition; defaultPosition = this.canSetBoundMode() ? clamp(defaultPosition, state.scrollArea.prev, state.scrollArea.next) : defaultPosition; } this.moveCamera(defaultPosition); this.axes.setTo({ flick: defaultPosition }, 0); }; __proto.updateSize = function () { var state = this.state; var options = this.options; var panels = this.panelManager.originalPanels().filter(function (panel) { return Boolean(panel); }); var bbox = this.updateBbox(); var prevSize = state.size; // Update size & hanger position state.size = options.horizontal ? bbox.width : bbox.height; if (prevSize !== state.size) { state.relativeHangerPosition = parseArithmeticExpression(options.hanger, state.size); state.infiniteThreshold = parseArithmeticExpression(options.infiniteThreshold, state.size); } if (panels.length <= 0) { return; } this.resizePanels(panels); }; __proto.updateOriginalPanelPositions = function () { var gap = this.options.gap; var panelManager = this.panelManager; var firstPanel = panelManager.firstPanel(); var panels = panelManager.originalPanels(); if (!firstPanel) { return; } var currentPanel = this.currentPanel; var nearestPanel = this.nearestPanel; var currentState = this.stateMachine.getState(); var scrollArea = this.state.scrollArea; // Update panel position && fit to wrapper var nextPanelPos = firstPanel.getPosition(); var maintainingPanel = firstPanel; if (nearestPanel) { // We should maintain nearestPanel's position var looped = !isBetween(currentState.lastPosition + currentState.delta, scrollArea.prev, scrollArea.next); maintainingPanel = looped ? currentPanel : nearestPanel; } else if (firstPanel.getIndex() > 0) { maintainingPanel = currentPanel; } var panelsBeforeMaintainPanel = panels.slice(0, maintainingPanel.getIndex() + (maintainingPanel.getCloneIndex() + 1) * panels.length); var accumulatedSize = panelsBeforeMaintainPanel.reduce(function (total, panel) { return total + panel.getSize() + gap; }, 0); nextPanelPos = maintainingPanel.getPosition() - accumulatedSize; panels.forEach(function (panel) { var newPosition = nextPanelPos; var panelSize = panel.getSize(); panel.setPosition(newPosition); nextPanelPos += panelSize + gap; }); if (!this.options.renderOnlyVisible) { panels.forEach(function (panel) { return panel.setPositionCSS(); }); } }; __proto.updateClonedPanelPositions = function () { var state = this.state; var options = this.options; var panelManager = this.panelManager; var clonedPanels = panelManager.clonedPanels().reduce(function (allClones, clones) { return __spreadArrays(allClones, clones); }, []).filter(function (panel) { return Boolean(panel); }); var scrollArea = state.scrollArea; var firstPanel = panelManager.firstPanel(); var lastPanel = panelManager.lastPanel(); if (!firstPanel) { return; } var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Locate all cloned panels linearly first for (var _i = 0, clonedPanels_1 = clonedPanels; _i < clonedPanels_1.length; _i++) { var panel = clonedPanels_1[_i]; var origPanel = panel.getOriginalPanel(); var cloneIndex = panel.getCloneIndex(); var cloneBasePos = sumOriginalPanelSize * (cloneIndex + 1); var clonedPanelPos = cloneBasePos + origPanel.getPosition(); panel.setPosition(clonedPanelPos); } var lastReplacePosition = firstPanel.getPosition(); // reverse() pollutes original array, so copy it with concat() for (var _a = 0, _b = clonedPanels.concat().reverse(); _a < _b.length; _a++) { var panel = _b[_a]; var panelSize = panel.getSize(); var replacePosition = lastReplacePosition - panelSize - options.gap; if (replacePosition + panelSize <= scrollArea.prev) { // Replace is not meaningful, as it won't be seen in current scroll area break; } panel.setPosition(replacePosition); lastReplacePosition = replacePosition; } if (!this.options.renderOnlyVisible) { clonedPanels.forEach(function (panel) { panel.setPositionCSS(); }); } }; __proto.updateVisiblePanelPositions = function () { var _this = this; if (this.options.renderOnlyVisible) { this.visiblePanels.forEach(function (panel) { panel.setPositionCSS(_this.state.positionOffset); }); } }; __proto.updateScrollArea = function () { var state = this.state; var panelManager = this.panelManager; var options = this.options; var axes = this.axes; // Set viewport scrollable area var firstPanel = panelManager.firstPanel(); var lastPanel = panelManager.lastPanel(); var relativeHangerPosition = state.relativeHangerPosition; if (!firstPanel) { state.scrollArea = { prev: 0, next: 0 }; } else if (this.canSetBoundMode()) { var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition(); if (sumOriginalPanelSize >= state.size) { state.scrollArea = { prev: firstPanel.getPosition(), next: lastPanel.getPosition() + lastPanel.getSize() - state.size }; } else { // Find anchor position of set of the combined panels var relAnchorPosOfCombined = parseArithmeticExpression(options.anchor, sumOriginalPanelSize); var anchorPos = firstPanel.getPosition() + clamp(relAnchorPosOfCombined, sumOriginalPanelSize - (state.size - relativeHangerPosition), relativeHangerPosition); state.scrollArea = { prev: anchorPos - relativeHangerPosition, next: anchorPos - relativeHangerPosition }; } } else if (options.circular) { var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Maximum scroll extends to first clone sequence's first panel state.scrollArea = { prev: firstPanel.getAnchorPosition() - relativeHangerPosition, next: sumOriginalPanelSize + firstPanel.getAnchorPosition() - relativeHangerPosition }; } else { state.scrollArea = { prev: firstPanel.getAnchorPosition() - relativeHangerPosition, next: lastPanel.getAnchorPosition() - relativeHangerPosition }; } var viewportSize = state.size; var bounce = options.bounce; var parsedBounce; if (isArray(bounce)) { parsedBounce = bounce.map(function (val) { return parseArithmeticExpression(val, viewportSize, DEFAULT_OPTIONS.bounce); }); } else { var parsedVal = parseArithmeticExpression(bounce, viewportSize, DEFAULT_OPTIONS.bounce); parsedBounce = [parsedVal, parsedVal]; } // Update axes range and bounce var flick = axes.axis.flick; flick.range = [state.scrollArea.prev, state.scrollArea.next]; flick.bounce = parsedBounce; }; __proto.checkNeedPanel = function (axesEvent) { var state = this.state; var options = this.options; var panelManager = this.panelManager; var currentPanel = this.currentPanel; var nearestPanel = this.nearestPanel; var currentState = this.stateMachine.getState(); if (!options.infinite) { return; } var gap = options.gap; var infiniteThreshold = state.infiniteThreshold; var maxLastIndex = panelManager.getLastIndex(); if (maxLastIndex < 0) { return; } if (!currentPanel || !nearestPanel) { // There're no panels this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: null, direction: null, indexRange: { min: 0, max: maxLastIndex, length: maxLastIndex + 1 } }); return; } var originalNearestPosition = nearestPanel.getPosition(); // Check next direction var checkingPanel = !currentState.holding && !currentState.playing ? currentPanel : nearestPanel; while (checkingPanel) { var currentIndex = checkingPanel.getIndex(); var nextSibling = checkingPanel.nextSibling; var lastPanel = panelManager.lastPanel(); var atLastPanel = currentIndex === lastPanel.getIndex(); var nextIndex = !atLastPanel && nextSibling ? nextSibling.getIndex() : maxLastIndex + 1; var currentNearestPosition = nearestPanel.getPosition(); var panelRight = checkingPanel.getPosition() + checkingPanel.getSize() - (currentNearestPosition - originalNearestPosition); var cameraNext = state.position + state.size; // There're empty panels between var emptyPanelExistsBetween = nextIndex - currentIndex > 1; // Expected prev panel's left position is smaller than camera position var overThreshold = panelRight + gap - infiniteThreshold <= cameraNext; if (emptyPanelExistsBetween && overThreshold) { this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.NEXT, indexRange: { min: currentIndex + 1, max: nextIndex - 1, length: nextIndex - currentIndex - 1 } }); } // Trigger needPanel in circular & at max panel index if (options.circular && currentIndex === maxLastIndex && overThreshold) { var firstPanel = panelManager.firstPanel(); var firstIndex = firstPanel ? firstPanel.getIndex() : -1; if (firstIndex > 0) { this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.NEXT, indexRange: { min: 0, max: firstIndex - 1, length: firstIndex } }); } } // Check whether panels are changed var lastPanelAfterNeed = panelManager.lastPanel(); var atLastPanelAfterNeed = lastPanelAfterNeed && currentIndex === lastPanelAfterNeed.getIndex(); if (atLastPanelAfterNeed || !overThreshold) { break; } checkingPanel = checkingPanel.nextSibling; } // Check prev direction checkingPanel = nearestPanel; while (checkingPanel) { var cameraPrev = state.position; var checkingIndex = checkingPanel.getIndex(); var prevSibling = checkingPanel.prevSibling; var firstPanel = panelManager.firstPanel(); var atFirstPanel = checkingIndex === firstPanel.getIndex(); var prevIndex = !atFirstPanel && prevSibling ? prevSibling.getIndex() : -1; var currentNearestPosition = nearestPanel.getPosition(); var panelLeft = checkingPanel.getPosition() - (currentNearestPosition - originalNearestPosition); // There're empty panels between var emptyPanelExistsBetween = checkingIndex - prevIndex > 1; // Expected prev panel's right position is smaller than camera position var overThreshold = panelLeft - gap + infiniteThreshold >= cameraPrev; if (emptyPanelExistsBetween && overThreshold) { this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.PREV, indexRange: { min: prevIndex + 1, max: checkingIndex - 1, length: checkingIndex - prevIndex - 1 } }); } // Trigger needPanel in circular & at panel 0 if (options.circular && checkingIndex === 0 && overThreshold) { var lastPanel = panelManager.lastPanel(); if (lastPanel && lastPanel.getIndex() < maxLastIndex) { var lastIndex = lastPanel.getIndex(); this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.PREV, indexRange: { min: lastIndex + 1, max: maxLastIndex, length: maxLastIndex - lastIndex } }); } } // Check whether panels were changed var firstPanelAfterNeed = panelManager.firstPanel(); var atFirstPanelAfterNeed = firstPanelAfterNeed && checkingIndex === firstPanelAfterNeed.getIndex(); // Looped in circular mode if (atFirstPanelAfterNeed || !overThreshold) { break; } checkingPanel = checkingPanel.prevSibling; } }; __proto.triggerNeedPanel = function (params) { var _this = this; var axesEvent = params.axesEvent, siblingPanel = params.siblingPanel, direction = params.direction, indexRange = params.indexRange; var options = this.options; var checkedIndexes = this.state.checkedIndexes; var alreadyTriggered = checkedIndexes.some(function (_a) { var min = _a[0], max = _a[1]; return min === indexRange.min || max === indexRange.max; }); var hasHandler = this.flicking.hasOn(EVENTS.NEED_PANEL); if (alreadyTriggered || !hasHandler) { return; } // Should done before triggering event, as we can directly add panels by event callback checkedIndexes.push([indexRange.min, indexRange.max]); var index = siblingPanel ? siblingPanel.getIndex() : 0; var isTrusted = axesEvent ? axesEvent.isTrusted : false; this.triggerEvent(EVENTS.NEED_PANEL, axesEvent, isTrusted, { index: index, panel: siblingPanel, direction: direction, range: indexRange, fill: function (element) { var panelManager = _this.panelManager; if (!siblingPanel) { return _this.insert(panelManager.getRange().max + 1, element); } var parsedElements = parseElement(element); // Slice elements to fit size equal to empty spaces var elements = direction === DIRECTION.NEXT ? parsedElements.slice(0, indexRange.length) : parsedElements.slice(-indexRange.length); if (direction === DIRECTION.NEXT) { if (options.circular && index === panelManager.getLastIndex()) { // needPanel event is triggered on last index, insert at index 0 return _this.insert(0, elements); } else { return siblingPanel.insertAfter(elements); } } else if (direction === DIRECTION.PREV) { if (options.circular && index === 0) { // needPanel event is triggered on first index(0), insert at the last index return _this.insert(indexRange.max - elements.length + 1, elements); } else { return siblingPanel.insertBefore(elements); } } else { // direction is null when there're no panels exist return _this.insert(0, elements); } } }); }; __proto.updateVisiblePanels = function () { var state = this.state; var options = this.options; var panelManager = this.panelManager; var currentState = this.stateMachine.getState(); var cameraElement = this.cameraElement; var renderExternal = options.renderExternal, renderOnlyVisible = options.renderOnlyVisible; if (!renderOnlyVisible) { return; } if (!this.nearestPanel) { this.visiblePanels = []; while (cameraElement.firstChild) { cameraElement.removeChild(cameraElement.firstChild); } return; } var prevVisiblePanels = this.visiblePanels; var newVisiblePanels = this.calcVisiblePanels(); var _a = this.checkVisiblePanelChange(prevVisiblePanels, newVisiblePanels), addedPanels = _a.addedPanels, removedPanels = _a.removedPanels; if (addedPanels.length <= 0 && removedPanels.length <= 0) { // Visible panels not changed return; } if (currentState.holding) { newVisiblePanels.push.apply(newVisiblePanels, removedPanels); } else { var firstVisiblePanelPos = newVisiblePanels[0].getPosition(); state.positionOffset = firstVisiblePanelPos; } newVisiblePanels.forEach(function (panel) { panel.setPositionCSS(state.positionOffset); }); if (!renderExternal) { if (!currentState.holding) { removedPanels.forEach(function (panel) { var panelElement = panel.getElement(); panelElement.parentNode && cameraElement.removeChild(panelElement); }); } var fragment_1 = document.createDocumentFragment(); addedPanels.forEach(function (panel) { fragment_1.appendChild(panel.getElement()); }); cameraElement.appendChild(fragment_1); } var firstVisiblePanel = newVisiblePanels[0]; var lastVisiblePanel = newVisiblePanels[newVisiblePanels.length - 1]; var getAbsIndex = function (panel) { return panel.getIndex() + (panel.getCloneIndex() + 1) * panelManager.getPanelCount(); }; var newVisibleRange = { min: getAbsIndex(firstVisiblePanel), max: getAbsIndex(lastVisiblePanel) }; this.visiblePanels = newVisiblePanels; this.flicking.trigger(EVENTS.VISIBLE_CHANGE, { type: EVENTS.VISIBLE_CHANGE, range: newVisibleRange }); }; __proto.checkVisiblePanelChange = function (prevVisiblePanels, newVisiblePanels) { var prevRefCount = prevVisiblePanels.map(function () { return 0; }); var newRefCount = newVisiblePanels.map(function () { return 0; }); prevVisiblePanels.forEach(function (prevPanel, prevIndex) { newVisiblePanels.forEach(function (newPanel, newIndex) { if (prevPanel === newPanel) { prevRefCount[prevIndex]++; newRefCount[newIndex]++; } }); }); var removedPanels = prevRefCount.reduce(function (removed, count, index) { return count === 0 ? __spreadArrays(removed, [prevVisiblePanels[index]]) : removed; }, []); var addedPanels = newRefCount.reduce(function (added, count, index) { return count === 0 ? __spreadArrays(added, [newVisiblePanels[index]]) : added; }, []); return { removedPanels: removedPanels, addedPanels: addedPanels }; }; __proto.resizePanels = function (panels) { var options = this.options; var panelBboxes = this.panelBboxes; if (options.isEqualSize === true) { if (!panelBboxes.default) { var defaultPanel = panels[0]; panelBboxes.default = defaultPanel.getBbox(); } var defaultBbox_1 = panelBboxes.default; panels.forEach(function (panel) { panel.resize(defaultBbox_1); }); return; } else if (options.isEqualSize) { var equalSizeClasses_2 = options.isEqualSize; panels.forEach(function (panel) { var overlappedClass = panel.getOverlappedClass(equalSizeClasses_2); if (overlappedClass) { panel.resize(panelBboxes[overlappedClass]); panelBboxes[overlappedClass] = panel.getBbox(); } else { panel.resize(); } }); return; } panels.forEach(function (panel) { panel.resize(); }); }; __proto.createPanInput = function () { var options = this.options; this.panInput = new Axes.PanInput(this.viewportElement, { inputType: options.inputType, thresholdAngle: options.thresholdAngle, iOSEdgeSwipeThreshold: options.iOSEdgeSwipeThreshold, scale: options.horizontal ? [-1, 0] : [0, -1] }); this.axes.connect(options.horizontal ? ["flick", ""] : ["", "flick"], this.panInput); }; return Viewport; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ /** * @memberof eg * @extends eg.Component * @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest" , "edge" : "latest", "ios" : "7+", "an" : "4.X+"} * @requires {@link https://github.com/naver/egjs-component|eg.Component} * @requires {@link https://github.com/naver/egjs-axes|eg.Axes} * @see Easing Functions Cheat Sheet {@link http://easings.net/} <ko>이징 함수 Cheat Sheet {@link http://easings.net/}</ko> */ var Flicking = /*#__PURE__*/ function (_super) { __extends(Flicking, _super); /** * @param element A base element for the eg.Flicking module. When specifying a value as a `string` type, you must specify a css selector string to select the element.<ko>eg.Flicking 모듈을 사용할 기준 요소. `string`타입으로 값 지정시 요소를 선택하기 위한 css 선택자 문자열을 지정해야 한다.</ko> * @param options An option object of the eg.Flicking module<ko>eg.Flicking 모듈의 옵션 객체</ko> * @param {string} [options.classPrefix="eg-flick"] A prefix of class names will be added for the panels, viewport, and camera.<ko>패널들과 뷰포트, 카메라에 추가될 클래스 이름의 접두사.</ko> * @param {number} [options.deceleration=0.0075] Deceleration value for panel movement animation for animation triggered by manual user input. A higher value means a shorter running time.<ko>사용자의 동작으로 가속도가 적용된 패널 이동 애니메이션의 감속도. 값이 높을수록 애니메이션 실행 시간이 짧아진다.</ko> * @param {boolean} [options.horizontal=true] The direction of panel movement. (true: horizontal, false: vertical)<ko>패널 이동 방향. (true: 가로방향, false: 세로방향)</ko> * @param {boolean} [options.circular=false] Enables circular mode, which connects first/last panel for continuous scrolling.<ko>순환 모드를 활성화한다. 순환 모드에서는 양 끝의 패널이 서로 연결되어 끊김없는 스크롤이 가능하다.</ko> * @param {boolean} [options.infinite=false] Enables infinite mode, which can automatically trigger needPanel until reaching the last panel's index reaches the lastIndex.<ko>무한 모드를 활성화한다. 무한 모드에서는 needPanel 이벤트를 자동으로 트리거한다. 해당 동작은 마지막 패널의 인덱스가 lastIndex와 일치할때까지 일어난다.</ko> * @param {number} [options.infiniteThreshold=0] A Threshold from viewport edge before triggering `needPanel` event in infinite mode.<ko>무한 모드에서 `needPanel`이벤트가 발생하기 위한 뷰포트 끝으로부터의 최대 거리.</ko> * @param {number} [options.lastIndex=Infinity] Maximum panel index that Flicking can set. Flicking won't trigger `needPanel` when the event's panel index is greater than it.<br/>Also, if the last panel's index reached a given index, you can't add more panels.<ko>Flicking이 설정 가능한 패널의 최대 인덱스. `needPanel` 이벤트에 지정된 인덱스가 최대 패널의 개수보다 같거나 커야 하는 경우에 이벤트를 트리거하지 않게 한다.<br>또한, 마지막 패널의 인덱스가 주어진 인덱스와 동일할 경우, 새로운 패널을 더 이상 추가할 수 없다.</ko> * @param {number} [options.threshold=40] Movement threshold to change panel(unit: pixel). It should be dragged above the threshold to change the current panel.<ko>패널 변경을 위한 이동 임계값 (단위: 픽셀). 주어진 값 이상으로 스크롤해야만 패널 변경이 가능하다.</ko> * @param {number} [options.duration=100] Duration of the panel movement animation. (unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @param {function} [options.panelEffect=x => 1 - Math.pow(1 - x, 3)] An easing function applied to the panel movement animation. Default value is `easeOutCubic`.<ko>패널 이동 애니메이션에 적용할 easing함수. 기본값은 `easeOutCubic`이다.</ko> * @param {number} [options.defaultIndex=0] Index of the panel to set as default when initializing. A zero-based integer.<ko>초기화시 지정할 디폴트 패널의 인덱스로, 0부터 시작하는 정수.</ko> * @param {string[]} [options.inputType=["touch,"mouse"]] Types of input devices to enable.({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption Reference})<ko>활성화할 입력 장치 종류. ({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption 참고})</ko> * @param {number} [options.thresholdAngle=45] The threshold angle value(0 ~ 90).<br>If the input angle from click/touched position is above or below this value in horizontal and vertical mode each, scrolling won't happen.<ko>스크롤 동작을 막기 위한 임계각(0 ~ 90).<br>클릭/터치한 지점으로부터 계산된 사용자 입력의 각도가 horizontal/vertical 모드에서 각각 크거나 작으면, 스크롤 동작이 이루어지지 않는다.</ko> * @param {number|string|number[]|string[]} [options.bounce=[10,10]] The size value of the bounce area. Only can be enabled when `circular=false`.<br>You can set different bounce value for prev/next direction by using array.<br>`number` for px value, and `string` for px, and % value relative to viewport size.(ex - 0, "10px", "20%")<ko>바운스 영역의 크기값. `circular=false`인 경우에만 사용할 수 있다.<br>배열을 통해 prev/next 방향에 대해 서로 다른 바운스 값을 지정 가능하다.<br>`number`를 통해 px값을, `stirng`을 통해 px 혹은 뷰포트 크기 대비 %값을 사용할 수 있다.(ex - 0, "10px", "20%")</ko> * @param {boolean} [options.autoResize=false] Whether the `resize` method should be called automatically after a window resize event.<ko>window의 `resize` 이벤트 이후 자동으로 resize()메소드를 호출할지의 여부.</ko> * @param {boolean} [options.adaptive=false] Whether the height(horizontal)/width(vertical) of the viewport element reflects the height/width value of the panel after completing the movement.<ko>목적 패널로 이동한 후 그 패널의 높이(horizontal)/너비(vertical)값을 뷰포트 요소의 높이/너비값에 반영할지 여부.</ko> * @param {number|""} [options.zIndex=2000] z-index value for viewport element.<ko>뷰포트 엘리먼트의 z-index 값.</ko> * @param {boolean} [options.bound=false] Prevent the view from going out of the first/last panel. Only can be enabled when `circular=false`.<ko>뷰가 첫번째와 마지막 패널 밖으로 나가는 것을 막아준다. `circular=false`인 경우에만 사용할 수 있다.</ko> * @param {boolean} [options.overflow=false] Disables CSS property `overflow: hidden` in viewport if `true`.<ko>`true`로 설정시 뷰포트에 `overflow: hidden` 속성을 해제한다.</ko> * @param {string} [options.hanger="50%"] The reference position of the hanger in the viewport, which hangs panel anchors should be stopped at.<br>It should be provided in px or % value of viewport size.<br>You can combinate those values with plus/minus sign.<br>ex) "50", "100px", "0%", "25% + 100px"<ko>뷰포트 내부의 행어의 위치. 패널의 앵커들이 뷰포트 내에서 멈추는 지점에 해당한다.<br>px값이나, 뷰포트의 크기 대비 %값을 사용할 수 있고, 이를 + 혹은 - 기호로 연계하여 사용할 수도 있다.<br>예) "50", "100px", "0%", "25% + 100px"</ko> * @param {string} [options.anchor="50%"] The reference position of the anchor in panels, which can be hanged by viewport hanger.<br>It should be provided in px or % value of panel size.<br>You can combinate those values with plus/minus sign.<br>ex) "50", "100px", "0%", "25% + 100px"<ko>패널 내부의 앵커의 위치. 뷰포트의 행어와 연계하여 패널이 화면 내에서 멈추는 지점을 설정할 수 있다.<br>px값이나, 패널의 크기 대비 %값을 사용할 수 있고, 이를 + 혹은 - 기호로 연계하여 사용할 수도 있다.<br>예) "50", "100px", "0%", "25% + 100px"</ko> * @param {number} [options.gap=0] Space value between panels. Should be given in number.(px)<ko>패널간에 부여할 간격의 크기를 나타내는 숫자.(px)</ko> * @param {eg.Flicking.MoveTypeOption} [options.moveType="snap"] Movement style by user input. (ex: snap, freeScroll)<ko>사용자 입력에 의한 이동 방식.(ex: snap, freeScroll)</ko> * @param {boolean} [options.useOffset=false] Whether to use `offsetWidth`/`offsetHeight` instead of `getBoundingClientRect` for panel/viewport size calculation.<br/>You can use this option to calculate the original panel size when CSS transform is applied to viewport or panel.<br/>⚠️ If panel size is not fixed integer value, there can be a 1px gap between panels.<ko>패널과 뷰포트의 크기를 계산할 때 `offsetWidth`/`offsetHeight`를 `getBoundingClientRect` 대신 사용할지 여부.<br/>패널이나 뷰포트에 CSS transform이 설정되어 있을 때 원래 패널 크기를 계산하려면 옵션을 활성화한다.<br/>⚠️ 패널의 크기가 정수로 고정되어있지 않다면 패널 사이에 1px의 공간이 생길 수 있다.</ko> * @param {boolean} [options.renderOnlyVisible=false] Whether to render visible panels only. This can dramatically increase performance when there're many panels.<ko>보이는 패널만 렌더링할지 여부를 설정한다. 패널이 많을 경우에 퍼포먼스를 크게 향상시킬 수 있다.</ko> * @param {boolean|string[]} [options.isEqualSize=false] This option indicates whether all panels have the same size(true) of first panel, or it can hold a list of class names that determines panel size.<br/>Enabling this option can increase performance while recalculating panel size.<ko>모든 패널의 크기가 동일한지(true), 혹은 패널 크기를 결정하는 패널 클래스들의 리스트.<br/>이 옵션을 설정하면 패널 크기 재설정시에 성능을 높일 수 있다.</ko> * @param {boolean} [options.isConstantSize=false] Whether all panels have a constant size that won't be changed after resize. Enabling this option can increase performance while recalculating panel size.<ko>모든 패널의 크기가 불변인지의 여부. 이 옵션을 'true'로 설정하면 패널 크기 재설정시에 성능을 높일 수 있다.</ko> * @param {boolean} [options.renderExternal=false] Whether to use external rendering. It will delegate DOM manipulation and can synchronize the rendered state by calling `sync()` method. You can use this option to use in frameworks like React, Vue, Angular, which has its states and rendering methods.<ko>외부 렌더링을 사용할 지의 여부. 이 옵션을 사용시 렌더링을 외부에 위임할 수 있고, `sync()`를 호출하여 그 상태를 동기화할 수 있다. 이 옵션을 사용하여, React, Vue, Angular 등 자체적인 상태와 렌더링 방법을 갖는 프레임워크에 대응할 수 있다.</ko> * @param {boolean} [options.resizeOnContentsReady=false] Whether to resize the Flicking after the image/video elements inside viewport are ready.<br/>Use this property to prevent wrong Flicking layout caused by dynamic image / video sizes.<ko>Flicking 내부의 이미지 / 비디오 엘리먼트들이 전부 로드되었을 때 Flicking의 크기를 재계산하기 위한 옵션.<br/>이미지 / 비디오 크기가 고정 크기가 아닐 경우 사용하여 레이아웃이 잘못되는 것을 방지할 수 있다.</ko> * @param {boolean} [options.collectStatistics=true] Whether to collect statistics on how you are using `Flicking`. These statistical data do not contain any personal information and are used only as a basis for the development of a user-friendly product.<ko>어떻게 `Flicking`을 사용하고 있는지에 대한 통계 수집 여부를 나타낸다. 이 통계자료는 개인정보를 포함하고 있지 않으며 오직 사용자 친화적인 제품으로 발전시키기 위한 근거자료로서 활용한다.</ko> */ function Flicking(element, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; _this.contentsReadyChecker = null; _this.isPanelChangedAtBeforeSync = false; /** * Update panels to current state. * @ko 패널들을 현재 상태에 맞춰 갱신한다. * @method * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ _this.resize = function () { var viewport = _this.viewport; var options = _this.options; var wrapper = _this.getElement(); var allPanels = viewport.panelManager.allPanels(); if (!options.isConstantSize) { allPanels.forEach(function (panel) { return panel.unCacheBbox(); }); } var shouldResetElements = options.renderOnlyVisible && !options.isConstantSize && options.isEqualSize !== true; // Temporarily set parent's height to prevent scroll (#333) var parent = wrapper.parentElement; var origStyle = parent.style.height; parent.style.height = parent.offsetHeight + "px"; viewport.unCacheBbox(); // This should be done before adding panels, to lower performance issue viewport.updateBbox(); if (shouldResetElements) { viewport.appendUncachedPanelElements(allPanels); } viewport.resize(); parent.style.height = origStyle; return _this; }; _this.triggerEvent = function (eventName, // visibleChange event has no common event definition from other events axesEvent, isTrusted, params) { if (params === void 0) { params = {}; } var viewport = _this.viewport; var canceled = true; // Ignore events before viewport is initialized if (viewport) { var state = viewport.stateMachine.getState(); var _a = viewport.getScrollArea(), prev = _a.prev, next = _a.next; var pos = viewport.getCameraPosition(); var progress = getProgress(pos, [prev, prev, next]); if (_this.options.circular) { progress %= 1; } canceled = !_super.prototype.trigger.call(_this, eventName, merge({ type: eventName, index: _this.getIndex(), panel: _this.getCurrentPanel(), direction: state.direction, holding: state.holding, progress: progress, axesEvent: axesEvent, isTrusted: isTrusted }, params)); } return { onSuccess: function (callback) { if (!canceled) { callback(); } return this; }, onStopped: function (callback) { if (canceled) { callback(); } return this; } }; }; // Return result of "move" event triggered _this.moveCamera = function (axesEvent) { var viewport = _this.viewport; var state = viewport.stateMachine.getState(); var options = _this.options; var pos = axesEvent.pos.flick; var previousPosition = viewport.getCameraPosition(); if (axesEvent.isTrusted && state.holding) { var inputOffset = options.horizontal ? axesEvent.inputEvent.offsetX : axesEvent.inputEvent.offsetY; var isNextDirection = inputOffset < 0; var cameraChange = pos - previousPosition; var looped = isNextDirection === pos < previousPosition; if (options.circular && looped) { // Reached at max/min range of axes var scrollAreaSize = viewport.getScrollAreaSize(); cameraChange = (cameraChange > 0 ? -1 : 1) * (scrollAreaSize - Math.abs(cameraChange)); } var currentDirection = cameraChange === 0 ? state.direction : cameraChange > 0 ? DIRECTION.NEXT : DIRECTION.PREV; state.direction = currentDirection; } state.delta += axesEvent.delta.flick; viewport.moveCamera(pos, axesEvent); return _this.triggerEvent(EVENTS.MOVE, axesEvent, axesEvent.isTrusted).onStopped(function () { // Undo camera movement viewport.moveCamera(previousPosition, axesEvent); }); }; // Set flicking wrapper user provided var wrapper; if (isString(element)) { wrapper = document.querySelector(element); if (!wrapper) { throw new Error("Base element doesn't exist."); } } else if (element.nodeName && element.nodeType === 1) { wrapper = element; } else { throw new Error("Element should be provided in string or HTMLElement."); } _this.wrapper = wrapper; // Override default options _this.options = merge({}, DEFAULT_OPTIONS, options); // Override moveType option var currentOptions = _this.options; var moveType = currentOptions.moveType; if (moveType in DEFAULT_MOVE_TYPE_OPTIONS) { currentOptions.moveType = DEFAULT_MOVE_TYPE_OPTIONS[moveType]; } // Make viewport instance with panel container element _this.viewport = new Viewport(_this, _this.options, _this.triggerEvent); _this.listenInput(); _this.listenResize(); return _this; // if (this.options.collectStatistics) { // sendEvent( // "usage", // "options", // options, // ); // } } /** * Move to the previous panel if it exists. * @ko 이전 패널이 존재시 해당 패널로 이동한다. * @param [duration=options.duration] Duration of the panel movement animation.(unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ var __proto = Flicking.prototype; __proto.prev = function (duration) { var currentPanel = this.getCurrentPanel(); var currentState = this.viewport.stateMachine.getState(); if (currentPanel && currentState.type === STATE_TYPE.IDLE) { var prevPanel = currentPanel.prev(); if (prevPanel) { prevPanel.focus(duration); } } return this; }; /** * Move to the next panel if it exists. * @ko 다음 패널이 존재시 해당 패널로 이동한다. * @param [duration=options.duration] Duration of the panel movement animation(unit: ms).<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.next = function (duration) { var currentPanel = this.getCurrentPanel(); var currentState = this.viewport.stateMachine.getState(); if (currentPanel && currentState.type === STATE_TYPE.IDLE) { var nextPanel = currentPanel.next(); if (nextPanel) { nextPanel.focus(duration); } } return this; }; /** * Move to the panel of given index. * @ko 주어진 인덱스에 해당하는 패널로 이동한다. * @param index The index number of the panel to move.<ko>이동할 패널의 인덱스 번호.</ko> * @param duration [duration=options.duration] Duration of the panel movement.(unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.moveTo = function (index, duration) { var viewport = this.viewport; var panel = viewport.panelManager.get(index); var state = viewport.stateMachine.getState(); if (!panel || state.type !== STATE_TYPE.IDLE) { return this; } var anchorPosition = panel.getAnchorPosition(); var hangerPosition = viewport.getHangerPosition(); var targetPanel = panel; if (this.options.circular) { var scrollAreaSize = viewport.getScrollAreaSize(); // Check all three possible locations, find the nearest position among them. var possiblePositions = [anchorPosition - scrollAreaSize, anchorPosition, anchorPosition + scrollAreaSize]; var nearestPosition = possiblePositions.reduce(function (nearest, current) { return Math.abs(current - hangerPosition) < Math.abs(nearest - hangerPosition) ? current : nearest; }, Infinity) - panel.getRelativeAnchorPosition(); var identicals = panel.getIdenticalPanels(); var offset = nearestPosition - anchorPosition; if (offset > 0) { // First cloned panel is nearest targetPanel = identicals[1]; } else if (offset < 0) { // Last cloned panel is nearest targetPanel = identicals[identicals.length - 1]; } targetPanel = targetPanel.clone(targetPanel.getCloneIndex(), true); targetPanel.setPosition(nearestPosition); } var currentIndex = this.getIndex(); if (hangerPosition === targetPanel.getAnchorPosition() && currentIndex === index) { return this; } var eventType = panel.getIndex() === viewport.getCurrentIndex() ? "" : EVENTS.CHANGE; viewport.moveTo(targetPanel, viewport.findEstimatedPosition(targetPanel), eventType, null, duration); return this; }; /** * Return index of the current panel. `-1` if no panel exists. * @ko 현재 패널의 인덱스 번호를 반환한다. 패널이 하나도 없을 경우 `-1`을 반환한다. * @return Current panel's index, zero-based integer.<ko>현재 패널의 인덱스 번호. 0부터 시작하는 정수.</ko> */ __proto.getIndex = function () { return this.viewport.getCurrentIndex(); }; /** * Return the wrapper element user provided in constructor. * @ko 사용자가 생성자에서 제공한 래퍼 엘리먼트를 반환한다. * @return Wrapper element user provided.<ko>사용자가 제공한 래퍼 엘리먼트.</ko> */ __proto.getElement = function () { return this.wrapper; }; /** * Return the viewport element's size. * @ko 뷰포트 엘리먼트의 크기를 반환한다. * @return Width if horizontal: true, height if horizontal: false */ __proto.getSize = function () { return this.viewport.getSize(); }; /** * Return current panel. `null` if no panel exists. * @ko 현재 패널을 반환한다. 패널이 하나도 없을 경우 `null`을 반환한다. * @return Current panel.<ko>현재 패널.</ko> */ __proto.getCurrentPanel = function () { var viewport = this.viewport; var panel = viewport.getCurrentPanel(); return panel ? panel : null; }; /** * Return the panel of given index. `null` if it doesn't exists. * @ko 주어진 인덱스에 해당하는 패널을 반환한다. 해당 패널이 존재하지 않을 시 `null`이다. * @return Panel of given index.<ko>주어진 인덱스에 해당하는 패널.</ko> */ __proto.getPanel = function (index) { var viewport = this.viewport; var panel = viewport.panelManager.get(index); return panel ? panel : null; }; /** * Return all panels. * @ko 모든 패널들을 반환한다. * @param - Should include cloned panels or not.<ko>복사된 패널들을 포함할지의 여부.</ko> * @return All panels.<ko>모든 패널들.</ko> */ __proto.getAllPanels = function (includeClone) { var viewport = this.viewport; var panelManager = viewport.panelManager; var panels = includeClone ? panelManager.allPanels() : panelManager.originalPanels(); return panels.filter(function (panel) { return !!panel; }); }; /** * Return the panels currently shown in viewport area. * @ko 현재 뷰포트 영역에서 보여지고 있는 패널들을 반환한다. * @return Panels currently shown in viewport area.<ko>현재 뷰포트 영역에 보여지는 패널들</ko> */ __proto.getVisiblePanels = function () { return this.viewport.calcVisiblePanels(); }; /** * Return length of original panels. * @ko 원본 패널의 개수를 반환한다. * @return Length of original panels.<ko>원본 패널의 개수</ko> */ __proto.getPanelCount = function () { return this.viewport.panelManager.getPanelCount(); }; /** * Return how many groups of clones are created. * @ko 몇 개의 클론 그룹이 생성되었는지를 반환한다. * @return Length of cloned panel groups.<ko>클론된 패널 그룹의 개수</ko> */ __proto.getCloneCount = function () { return this.viewport.panelManager.getCloneCount(); }; /** * Get maximum panel index for `infinite` mode. * @ko `infinite` 모드에서 적용되는 추가 가능한 패널의 최대 인덱스 값을 반환한다. * @see {@link eg.Flicking.FlickingOptions} * @return Maximum index of panel that can be added.<ko>최대 추가 가능한 패널의 인덱스.</ko> */ __proto.getLastIndex = function () { return this.viewport.panelManager.getLastIndex(); }; /** * Set maximum panel index for `infinite' mode.<br>[needPanel]{@link eg.Flicking#events:needPanel} won't be triggered anymore when last panel's index reaches it.<br>Also, you can't add more panels after it. * @ko `infinite` 모드에서 적용되는 패널의 최대 인덱스를 설정한다.<br>마지막 패널의 인덱스가 설정한 값에 도달할 경우 더 이상 [needPanel]{@link eg.Flicking#events:needPanel} 이벤트가 발생되지 않는다.<br>또한, 설정한 인덱스 이후로 새로운 패널을 추가할 수 없다. * @param - Maximum panel index. * @see {@link eg.Flicking.FlickingOptions} * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.setLastIndex = function (index) { this.viewport.setLastIndex(index); return this; }; /** * Return panel movement animation. * @ko 현재 패널 이동 애니메이션이 진행 중인지를 반환한다. * @return Is animating or not.<ko>애니메이션 진행 여부.</ko> */ __proto.isPlaying = function () { return this.viewport.stateMachine.getState().playing; }; /** * Unblock input devices. * @ko 막았던 입력 장치로부터의 입력을 푼다. * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.enableInput = function () { this.viewport.enable(); return this; }; /** * Block input devices. * @ko 입력 장치로부터의 입력을 막는다. * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.disableInput = function () { this.viewport.disable(); return this; }; /** * Get current flicking status. You can restore current state by giving returned value to [setStatus()]{@link eg.Flicking#setStatus}. * @ko 현재 상태 값을 반환한다. 반환받은 값을 [setStatus()]{@link eg.Flicking#setStatus} 메소드의 인자로 지정하면 현재 상태를 복원할 수 있다. * @return An object with current status value information.<ko>현재 상태값 정보를 가진 객체.</ko> */ __proto.getStatus = function () { var viewport = this.viewport; var panels = viewport.panelManager.originalPanels().filter(function (panel) { return !!panel; }).map(function (panel) { return { html: panel.getElement().outerHTML, index: panel.getIndex(), position: panel.getPosition() }; }); return { index: viewport.getCurrentIndex(), panels: panels, position: viewport.getCameraPosition() }; }; /** * Restore to the state of the `status`. * @ko `status`의 상태로 복원한다. * @param status Status value to be restored. You can specify the return value of the [getStatus()]{@link eg.Flicking#getStatus} method.<ko>복원할 상태 값. [getStatus()]{@link eg.Flicking#getStatus}메서드의 반환값을 지정하면 된다.</ko> */ __proto.setStatus = function (status) { this.viewport.restore(status); }; /** * Add plugins that can have different effects on Flicking. * @ko 플리킹에 다양한 효과를 부여할 수 있는 플러그인을 추가한다. * @param - The plugin(s) to add.<ko>추가할 플러그인(들).</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.addPlugins = function (plugins) { this.viewport.addPlugins(plugins); return this; }; /** * Remove plugins from Flicking. * @ko 플리킹으로부터 플러그인들을 제거한다. * @param - The plugin(s) to remove.<ko>제거 플러그인(들).</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.removePlugins = function (plugins) { this.viewport.removePlugins(plugins); return this; }; /** * Return the reference element and all its children to the state they were in before the instance was created. Remove all attached event handlers. Specify `null` for all attributes of the instance (including inherited attributes). * @ko 기준 요소와 그 하위 패널들을 인스턴스 생성전의 상태로 되돌린다. 부착된 모든 이벤트 핸들러를 탈거한다. 인스턴스의 모든 속성(상속받은 속성포함)에 `null`을 지정한다. * @example * const flick = new eg.Flicking("#flick"); * flick.destroy(); * console.log(flick.moveTo); // null */ __proto.destroy = function (option) { var _a; if (option === void 0) { option = {}; } this.off(); if (this.options.autoResize) { window.removeEventListener("resize", this.resize); } this.viewport.destroy(option); (_a = this.contentsReadyChecker) === null || _a === void 0 ? void 0 : _a.destroy(); // release resources for (var x in this) { this[x] = null; } }; /** * Add new panels at the beginning of panels. * @ko 제일 앞에 새로운 패널을 추가한다. * @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko> * @return Array of appended panels.<ko>추가된 패널들의 배열</ko> * @example * // Suppose there were no panels at initialization * const flicking = new eg.Flicking("#flick"); * flicking.replace(3, document.createElement("div")); // Add new panel at index 3 * flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 2 * flicking.prepend(["\<div\>Panel\</div\>", document.createElement("div")]); // Prepended at index 0, 1 * flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 0, pushing every panels behind it. */ __proto.prepend = function (element) { var viewport = this.viewport; var parsedElements = parseElement(element); var insertingIndex = Math.max(viewport.panelManager.getRange().min - parsedElements.length, 0); var prependedPanels = viewport.insert(insertingIndex, parsedElements); this.checkContentsReady(prependedPanels); return prependedPanels; }; /** * Add new panels at the end of panels. * @ko 제일 끝에 새로운 패널을 추가한다. * @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko> * @return Array of appended panels.<ko>추가된 패널들의 배열</ko> * @example * // Suppose there were no panels at initialization * const flicking = new eg.Flicking("#flick"); * flicking.append(document.createElement("div")); // Appended at index 0 * flicking.append("\<div\>Panel\</div\>"); // Appended at index 1 * flicking.append(["\<div\>Panel\</div\>", document.createElement("div")]); // Appended at index 2, 3 * // Even this is possible * flicking.append("\<div\>Panel 1\</div\>\<div\>Panel 2\</div\>"); // Appended at index 4, 5 */ __proto.append = function (element) { var viewport = this.viewport; var appendedPanels = viewport.insert(viewport.panelManager.getRange().max + 1, element); this.checkContentsReady(appendedPanels); return appendedPanels; }; /** * Replace existing panels with new panels from given index. If target index is empty, add new panel at target index. * @ko 주어진 인덱스로부터의 패널들을 새로운 패널들로 교체한다. 인덱스에 해당하는 자리가 비어있다면, 새로운 패널을 해당 자리에 집어넣는다. * @param index - Start index to replace new panels.<ko>새로운 패널들로 교체할 시작 인덱스</ko> * @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko> * @return Array of created panels by replace.<ko>교체되어 새롭게 추가된 패널들의 배열</ko> * @example * // Suppose there were no panels at initialization * const flicking = new eg.Flicking("#flick"); * * // This will add new panel at index 3, * // Index 0, 1, 2 is empty at this moment. * // [empty, empty, empty, PANEL] * flicking.replace(3, document.createElement("div")); * * // As index 2 was empty, this will also add new panel at index 2. * // [empty, empty, PANEL, PANEL] * flicking.replace(2, "\<div\>Panel\</div\>"); * * // Index 3 was not empty, so it will replace previous one. * // It will also add new panels at index 4 and 5. * // before - [empty, empty, PANEL, PANEL] * // after - [empty, empty, PANEL, NEW_PANEL, NEW_PANEL, NEW_PANEL] * flicking.replace(3, ["\<div\>Panel\</div\>", "\<div\>Panel\</div\>", "\<div\>Panel\</div\>"]) */ __proto.replace = function (index, element) { var replacedPanels = this.viewport.replace(index, element); this.checkContentsReady(replacedPanels); return replacedPanels; }; /** * Remove panel at target index. This will decrease index of panels behind it. * @ko `index`에 해당하는 자리의 패널을 제거한다. 수행시 `index` 이후의 패널들의 인덱스가 감소된다. * @param index - Index of panel to remove.<ko>제거할 패널의 인덱스</ko> * @param {number} [deleteCount=1] - Number of panels to remove from index.<ko>`index` 이후로 제거할 패널의 개수.</ko> * @return Array of removed panels<ko>제거된 패널들의 배열</ko> */ __proto.remove = function (index, deleteCount) { if (deleteCount === void 0) { deleteCount = 1; } return this.viewport.remove(index, deleteCount); }; /** * Get indexes to render. Should be used with `renderOnlyVisible` option. * `beforeSync` should be called before this method for a correct result. * @private * @ko 렌더링이 필요한 인덱스들을 반환한다. `renderOnlyVisible` 옵션과 함께 사용해야 한다. 정확한 결과를 위해선 `beforeSync`를 이전에 호출해야만 합니다. * @param - Info object of how panel infos are changed.<ko>패널 정보들의 변경 정보를 담는 오브젝트.</ko> * @return Array of indexes to render.<ko>렌더링할 인덱스의 배열</ko> */ __proto.getRenderingIndexes = function (diffResult) { var viewport = this.viewport; var visiblePanels = viewport.getVisiblePanels(); var maintained = diffResult.maintained.reduce(function (values, _a) { var before = _a[0], after = _a[1]; values[after] = before; return values; }, {}); var panelCount = diffResult.list.length; var added = diffResult.added; var getPanelAbsIndex = function (panel) { return panel.getIndex() + (panel.getCloneIndex() + 1) * panelCount; }; var visibleIndexes = visiblePanels.map(function (panel) { return getPanelAbsIndex(panel); }).filter(function (val) { return maintained[val % panelCount] != null; }); var renderingPanels = __spreadArrays(visibleIndexes, added); var allPanels = viewport.panelManager.allPanels(); viewport.setVisiblePanels(renderingPanels.map(function (index) { return allPanels[index]; })); return renderingPanels; }; /** * Synchronize info of panels instance with info given by external rendering. * @ko 외부 렌더링 방식에 의해 입력받은 패널의 정보와 현재 플리킹이 갖는 패널 정보를 동기화한다. * @private * @param - Info object of how panel infos are changed.<ko>패널 정보들의 변경 정보를 담는 오브젝트.</ko> * @param - Whether called from sync method <ko> sync 메소드로부터 호출됐는지 여부 </ko> */ __proto.beforeSync = function (diffInfo) { var _this = this; var maintained = diffInfo.maintained, added = diffInfo.added, changed = diffInfo.changed, removed = diffInfo.removed; var viewport = this.viewport; var panelManager = viewport.panelManager; var isCircular = this.options.circular; var cloneCount = panelManager.getCloneCount(); var prevClonedPanels = panelManager.clonedPanels(); // Update visible panels var newVisiblePanels = viewport.getVisiblePanels().filter(function (panel) { return findIndex(removed, function (index) { return index === panel.getIndex(); }) < 0; }); viewport.setVisiblePanels(newVisiblePanels); // Did not changed at all if (added.length <= 0 && removed.length <= 0 && changed.length <= 0 && cloneCount === prevClonedPanels.length) { return this; } var prevOriginalPanels = panelManager.originalPanels(); var newPanels = []; var newClones = counter(cloneCount).map(function () { return []; }); maintained.forEach(function (_a) { var beforeIdx = _a[0], afterIdx = _a[1]; newPanels[afterIdx] = prevOriginalPanels[beforeIdx]; newPanels[afterIdx].setIndex(afterIdx); }); added.forEach(function (addIndex) { newPanels[addIndex] = new Panel(null, addIndex, _this.viewport); }); if (isCircular) { counter(cloneCount).forEach(function (groupIndex) { var prevCloneGroup = prevClonedPanels[groupIndex]; var newCloneGroup = newClones[groupIndex]; maintained.forEach(function (_a) { var beforeIdx = _a[0], afterIdx = _a[1]; newCloneGroup[afterIdx] = prevCloneGroup ? prevCloneGroup[beforeIdx] : newPanels[afterIdx].clone(groupIndex, false); newCloneGroup[afterIdx].setIndex(afterIdx); }); added.forEach(function (addIndex) { var newPanel = newPanels[addIndex]; newCloneGroup[addIndex] = newPanel.clone(groupIndex, false); }); }); } added.forEach(function (index) { viewport.updateCheckedIndexes({ min: index, max: index }); }); removed.forEach(function (index) { viewport.updateCheckedIndexes({ min: index - 1, max: index + 1 }); }); var checkedIndexes = viewport.getCheckedIndexes(); checkedIndexes.forEach(function (_a, idx) { var min = _a[0], max = _a[1]; // Push checked indexes backward var pushedIndex = added.filter(function (index) { return index < min && panelManager.has(index); }).length - removed.filter(function (index) { return index < min; }).length; checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]); }); // Only effective only when there are least one panel which have changed its index if (changed.length > 0) { // Removed checked index by changed ones after pushing maintained.forEach(function (_a) { var next = _a[1]; viewport.updateCheckedIndexes({ min: next, max: next }); }); } panelManager.replacePanels(newPanels, newClones); this.isPanelChangedAtBeforeSync = true; }; /** * Synchronize info of panels with DOM info given by external rendering. * @ko 외부 렌더링 방식에 의해 입력받은 DOM의 정보와 현재 플리킹이 갖는 패널 정보를 동기화 한다. * @private * @param - Info object of how panel elements are changed.<ko>패널의 DOM 요소들의 변경 정보를 담는 오브젝트.</ko> */ __proto.sync = function (diffInfo) { var list = diffInfo.list, maintained = diffInfo.maintained, added = diffInfo.added, changed = diffInfo.changed, removed = diffInfo.removed; // Did not changed at all if (added.length <= 0 && removed.length <= 0 && changed.length <= 0) { return this; } var viewport = this.viewport; var _a = this.options, renderOnlyVisible = _a.renderOnlyVisible, circular = _a.circular; var panelManager = viewport.panelManager; if (!renderOnlyVisible) { var indexRange = panelManager.getRange(); var beforeDiffInfo = diffInfo; if (circular) { var prevOriginalPanelCount_1 = indexRange.max; var originalPanelCount_1 = list.length / (panelManager.getCloneCount() + 1) >> 0; var originalAdded = added.filter(function (index) { return index < originalPanelCount_1; }); var originalRemoved = removed.filter(function (index) { return index <= prevOriginalPanelCount_1; }); var originalMaintained = maintained.filter(function (_a) { var beforeIdx = _a[0]; return beforeIdx <= prevOriginalPanelCount_1; }); var originalChanged = changed.filter(function (_a) { var beforeIdx = _a[0]; return beforeIdx <= prevOriginalPanelCount_1; }); beforeDiffInfo = { added: originalAdded, maintained: originalMaintained, removed: originalRemoved, changed: originalChanged }; } this.beforeSync(beforeDiffInfo); } var visiblePanels = renderOnlyVisible ? viewport.getVisiblePanels() : this.getAllPanels(true); added.forEach(function (addedIndex) { var addedElement = list[addedIndex]; var beforePanel = visiblePanels[addedIndex]; beforePanel.setElement(addedElement); // As it can be 0 beforePanel.unCacheBbox(); }); if (this.isPanelChangedAtBeforeSync) { // Reset visible panels viewport.setVisiblePanels([]); this.isPanelChangedAtBeforeSync = false; } viewport.resize(); return this; }; __proto.listenInput = function () { var flicking = this; var viewport = flicking.viewport; var stateMachine = viewport.stateMachine; // Set event context flicking.eventContext = { flicking: flicking, viewport: flicking.viewport, transitTo: stateMachine.transitTo, triggerEvent: flicking.triggerEvent, moveCamera: flicking.moveCamera, stopCamera: viewport.stopCamera }; var handlers = {}; var _loop_1 = function (key) { var eventType = AXES_EVENTS[key]; handlers[eventType] = function (e) { return stateMachine.fire(eventType, e, flicking.eventContext); }; }; for (var key in AXES_EVENTS) { _loop_1(key); } // Connect Axes instance with PanInput flicking.viewport.connectAxesHandler(handlers); }; __proto.listenResize = function () { var _this = this; var options = this.options; if (options.autoResize) { window.addEventListener("resize", this.resize); } if (options.resizeOnContentsReady) { var contentsReadyChecker = new ImReady(); contentsReadyChecker.on("preReady", function () { _this.resize(); }); contentsReadyChecker.on("readyElement", function (e) { if (e.hasLoading && e.isPreReadyOver) { _this.resize(); } }); contentsReadyChecker.on("error", function (e) { _this.trigger(EVENTS.CONTENT_ERROR, { type: EVENTS.CONTENT_ERROR, element: e.element }); }); contentsReadyChecker.check([this.wrapper]); this.contentsReadyChecker = contentsReadyChecker; } }; __proto.checkContentsReady = function (panels) { var _a; (_a = this.contentsReadyChecker) === null || _a === void 0 ? void 0 : _a.check(panels.map(function (panel) { return panel.getElement(); })); }; /** * Version info string * @ko 버전정보 문자열 * @example * eg.Flicking.VERSION; // ex) 3.0.0 * @memberof eg.Flicking */ Flicking.VERSION = "3.8.0"; /** * Direction constant - "PREV" or "NEXT" * @ko 방향 상수 - "PREV" 또는 "NEXT" * @type {object} * @property {"PREV"} PREV - Prev direction from current hanger position.<br/>It's `left(←️)` direction when `horizontal: true`.<br/>Or, `up(↑️)` direction when `horizontal: false`.<ko>현재 행어를 기준으로 이전 방향.<br/>`horizontal: true`일 경우 `왼쪽(←️)` 방향.<br/>`horizontal: false`일 경우 `위쪽(↑️)`방향이다.</ko> * @property {"NEXT"} NEXT - Next direction from current hanger position.<br/>It's `right(→)` direction when `horizontal: true`.<br/>Or, `down(↓️)` direction when `horizontal: false`.<ko>현재 행어를 기준으로 다음 방향.<br/>`horizontal: true`일 경우 `오른쪽(→)` 방향.<br/>`horizontal: false`일 경우 `아래쪽(↓️)`방향이다.</ko> * @example * eg.Flicking.DIRECTION.PREV; // "PREV" * eg.Flicking.DIRECTION.NEXT; // "NEXT" */ Flicking.DIRECTION = DIRECTION; /** * Event type object with event name strings. * @ko 이벤트 이름 문자열들을 담은 객체 * @type {object} * @property {"holdStart"} HOLD_START - holdStart event<ko>holdStart 이벤트</ko> * @property {"holdEnd"} HOLD_END - holdEnd event<ko>holdEnd 이벤트</ko> * @property {"moveStart"} MOVE_START - moveStart event<ko>moveStart 이벤트</ko> * @property {"move"} MOVE - move event<ko>move 이벤트</ko> * @property {"moveEnd"} MOVE_END - moveEnd event<ko>moveEnd 이벤트</ko> * @property {"change"} CHANGE - change event<ko>change 이벤트</ko> * @property {"restore"} RESTORE - restore event<ko>restore 이벤트</ko> * @property {"select"} SELECT - select event<ko>select 이벤트</ko> * @property {"needPanel"} NEED_PANEL - needPanel event<ko>needPanel 이벤트</ko> * @example * eg.Flicking.EVENTS.MOVE_START; // "MOVE_START" */ Flicking.EVENTS = EVENTS; return Flicking; }(Component); Flicking.withFlickingMethods = withFlickingMethods; Flicking.DEFAULT_OPTIONS = DEFAULT_OPTIONS; Flicking.MOVE_TYPE = MOVE_TYPE; return Flicking; }))); //# sourceMappingURL=flicking.js.map
{ "content_hash": "e4661d0ae19972714932866389532da2", "timestamp": "", "source": "github", "line_count": 5062, "max_line_length": 586, "avg_line_length": 36.06775977874358, "alnum_prop": 0.5939750787347665, "repo_name": "cdnjs/cdnjs", "id": "804d6867f8363e046d559d527dd72de9440e37bc", "size": "188593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/egjs-flicking/3.8.0/flicking.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import datetime import os from decimal import Decimal from unittest import mock, skipUnless from django import forms from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.core.files.uploadedfile import SimpleUploadedFile from django.db import connection, models from django.db.models.query import EmptyQuerySet from django.forms.models import ( ModelFormMetaclass, construct_instance, fields_for_model, model_to_dict, modelform_factory, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import ( Article, ArticleStatus, Author, Author1, Award, BetterWriter, BigInt, Book, Category, Character, Colour, ColourfulItem, CustomErrorMessage, CustomFF, CustomFieldForExclusionModel, DateTimePost, DerivedBook, DerivedPost, Document, ExplicitPK, FilePathModel, FlexibleDatePost, Homepage, ImprovedArticle, ImprovedArticleWithParentLink, Inventory, NullableUniqueCharFieldModel, Person, Photo, Post, Price, Product, Publication, PublicationDefaults, StrictAssignmentAll, StrictAssignmentFieldSpecific, Student, StumpJoke, TextFile, Triple, Writer, WriterProfile, test_images, ) if test_images: from .models import ImageFile, OptionalImageFile, NoExtensionImageFile class ImageFileForm(forms.ModelForm): class Meta: model = ImageFile fields = '__all__' class OptionalImageFileForm(forms.ModelForm): class Meta: model = OptionalImageFile fields = '__all__' class NoExtensionImageFileForm(forms.ModelForm): class Meta: model = NoExtensionImageFile fields = '__all__' class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' class PriceForm(forms.ModelForm): class Meta: model = Price fields = '__all__' class BookForm(forms.ModelForm): class Meta: model = Book fields = '__all__' class DerivedBookForm(forms.ModelForm): class Meta: model = DerivedBook fields = '__all__' class ExplicitPKForm(forms.ModelForm): class Meta: model = ExplicitPK fields = ('key', 'desc',) class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' class DerivedPostForm(forms.ModelForm): class Meta: model = DerivedPost fields = '__all__' class CustomWriterForm(forms.ModelForm): name = forms.CharField(required=False) class Meta: model = Writer fields = '__all__' class BaseCategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' class ArticleForm(forms.ModelForm): class Meta: model = Article fields = '__all__' class RoykoForm(forms.ModelForm): class Meta: model = Writer fields = '__all__' class ArticleStatusForm(forms.ModelForm): class Meta: model = ArticleStatus fields = '__all__' class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = '__all__' class SelectInventoryForm(forms.Form): items = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') class CustomFieldForExclusionForm(forms.ModelForm): class Meta: model = CustomFieldForExclusionModel fields = ['name', 'markup'] class TextFileForm(forms.ModelForm): class Meta: model = TextFile fields = '__all__' class BigIntForm(forms.ModelForm): class Meta: model = BigInt fields = '__all__' class ModelFormWithMedia(forms.ModelForm): class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } class Meta: model = TextFile fields = '__all__' class CustomErrorMessageForm(forms.ModelForm): name1 = forms.CharField(error_messages={'invalid': 'Form custom error message.'}) class Meta: fields = '__all__' model = CustomErrorMessage class ModelFormBaseTest(TestCase): def test_base_form(self): self.assertEqual(list(BaseCategoryForm.base_fields), ['name', 'slug', 'url']) def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass with self.assertRaisesMessage(ValueError, 'ModelForm has no model class specified.'): NoModelModelForm() def test_empty_fields_to_fields_for_model(self): """ An argument of fields=() to fields_for_model should return an empty dictionary """ field_dict = fields_for_model(Person, fields=()) self.assertEqual(len(field_dict), 0) def test_empty_fields_on_modelform(self): """ No fields on a ModelForm should actually result in no fields. """ class EmptyPersonForm(forms.ModelForm): class Meta: model = Person fields = () form = EmptyPersonForm() self.assertEqual(len(form.fields), 0) def test_empty_fields_to_construct_instance(self): """ No fields should be set on a model instance if construct_instance receives fields=(). """ form = modelform_factory(Person, fields="__all__")({'name': 'John Doe'}) self.assertTrue(form.is_valid()) instance = construct_instance(form, Person(), fields=()) self.assertEqual(instance.name, '') def test_blank_with_null_foreign_key_field(self): """ #13776 -- ModelForm's with models having a FK set to null=False and required=False should be valid. """ class FormForTestingIsValid(forms.ModelForm): class Meta: model = Student fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['character'].required = False char = Character.objects.create(username='user', last_action=datetime.datetime.today()) data = {'study': 'Engineering'} data2 = {'study': 'Engineering', 'character': char.pk} # form is valid because required=False for field 'character' f1 = FormForTestingIsValid(data) self.assertTrue(f1.is_valid()) f2 = FormForTestingIsValid(data2) self.assertTrue(f2.is_valid()) obj = f2.save() self.assertEqual(obj.character, char) def test_blank_false_with_null_true_foreign_key_field(self): """ A ModelForm with a model having ForeignKey(blank=False, null=True) and the form field set to required=False should allow the field to be unset. """ class AwardForm(forms.ModelForm): class Meta: model = Award fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['character'].required = False character = Character.objects.create(username='user', last_action=datetime.datetime.today()) award = Award.objects.create(name='Best sprinter', character=character) data = {'name': 'Best tester', 'character': ''} # remove character form = AwardForm(data=data, instance=award) self.assertTrue(form.is_valid()) award = form.save() self.assertIsNone(award.character) def test_blank_foreign_key_with_radio(self): class BookForm(forms.ModelForm): class Meta: model = Book fields = ['author'] widgets = {'author': forms.RadioSelect()} writer = Writer.objects.create(name='Joe Doe') form = BookForm() self.assertEqual(list(form.fields['author'].choices), [ ('', '---------'), (writer.pk, 'Joe Doe'), ]) def test_non_blank_foreign_key_with_radio(self): class AwardForm(forms.ModelForm): class Meta: model = Award fields = ['character'] widgets = {'character': forms.RadioSelect()} character = Character.objects.create( username='user', last_action=datetime.datetime.today(), ) form = AwardForm() self.assertEqual( list(form.fields['character'].choices), [(character.pk, 'user')], ) def test_save_blank_false_with_required_false(self): """ A ModelForm with a model with a field set to blank=False and the form field set to required=False should allow the field to be unset. """ obj = Writer.objects.create(name='test') form = CustomWriterForm(data={'name': ''}, instance=obj) self.assertTrue(form.is_valid()) obj = form.save() self.assertEqual(obj.name, '') def test_save_blank_null_unique_charfield_saves_null(self): form_class = modelform_factory(model=NullableUniqueCharFieldModel, fields=['codename']) empty_value = '' if connection.features.interprets_empty_strings_as_nulls else None form = form_class(data={'codename': ''}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) # Save a second form to verify there isn't a unique constraint violation. form = form_class(data={'codename': ''}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) def test_missing_fields_attribute(self): message = ( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form " "MissingFieldsForm needs updating." ) with self.assertRaisesMessage(ImproperlyConfigured, message): class MissingFieldsForm(forms.ModelForm): class Meta: model = Category def test_extra_fields(self): class ExtraFields(BaseCategoryForm): some_extra_field = forms.BooleanField() self.assertEqual(list(ExtraFields.base_fields), ['name', 'slug', 'url', 'some_extra_field']) def test_extra_field_model_form(self): with self.assertRaisesMessage(FieldError, 'no-field'): class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'no-field') def test_extra_declared_field_model_form(self): class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'age') def test_extra_field_modelform_factory(self): with self.assertRaisesMessage(FieldError, 'Unknown field(s) (no-field) specified for Person'): modelform_factory(Person, fields=['no-field', 'name']) def test_replace_field(self): class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = '__all__' self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_2(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = ['url'] self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_3(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = [] # url will still appear, since it is explicit above self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_override_field(self): class WriterForm(forms.ModelForm): book = forms.CharField(required=False) class Meta: model = Writer fields = '__all__' wf = WriterForm({'name': 'Richard Lockridge'}) self.assertTrue(wf.is_valid()) def test_limit_nonexistent_field(self): expected_msg = 'Unknown field(s) (nonexistent) specified for Category' with self.assertRaisesMessage(FieldError, expected_msg): class InvalidCategoryForm(forms.ModelForm): class Meta: model = Category fields = ['nonexistent'] def test_limit_fields_with_string(self): expected_msg = "CategoryForm.Meta.fields cannot be a string. Did you mean to type: ('url',)?" with self.assertRaisesMessage(TypeError, expected_msg): class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ('url') # note the missing comma def test_exclude_fields(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ['url'] self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug']) def test_exclude_nonexistent_field(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ['nonexistent'] self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug', 'url']) def test_exclude_fields_with_string(self): expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?" with self.assertRaisesMessage(TypeError, expected_msg): class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = ('url') # note the missing comma def test_exclude_and_validation(self): # This Price instance generated by this form is not valid because the quantity # field is required, but the form is valid because the field is excluded from # the form. This is for backwards compatibility. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price exclude = ('quantity',) form = PriceFormWithoutQuantity({'price': '6.00'}) self.assertTrue(form.is_valid()) price = form.save(commit=False) msg = "{'quantity': ['This field cannot be null.']}" with self.assertRaisesMessage(ValidationError, msg): price.full_clean() # The form should not validate fields that it doesn't contain even if they are # specified using 'fields', not 'exclude'. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price fields = ('price',) form = PriceFormWithoutQuantity({'price': '6.00'}) self.assertTrue(form.is_valid()) # The form should still have an instance of a model that is not complete and # not saved into a DB yet. self.assertEqual(form.instance.price, Decimal('6.00')) self.assertIsNone(form.instance.quantity) self.assertIsNone(form.instance.pk) def test_confused_form(self): class ConfusedForm(forms.ModelForm): """ Using 'fields' *and* 'exclude'. Not sure why you'd want to do this, but uh, "be liberal in what you accept" and all. """ class Meta: model = Category fields = ['name', 'url'] exclude = ['url'] self.assertEqual(list(ConfusedForm.base_fields), ['name']) def test_mixmodel_form(self): class MixModelForm(BaseCategoryForm): """ Don't allow more than one 'model' definition in the inheritance hierarchy. Technically, it would generate a valid form, but the fact that the resulting save method won't deal with multiple objects is likely to trip up people not familiar with the mechanics. """ class Meta: model = Article fields = '__all__' # MixModelForm is now an Article-related thing, because MixModelForm.Meta # overrides BaseCategoryForm.Meta. self.assertEqual( list(MixModelForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_article_form(self): self.assertEqual( list(ArticleForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_bad_form(self): # First class with a Meta class wins... class BadForm(ArticleForm, BaseCategoryForm): pass self.assertEqual( list(BadForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_invalid_meta_model(self): class InvalidModelForm(forms.ModelForm): class Meta: pass # no model # Can't create new form msg = 'ModelForm has no model class specified.' with self.assertRaisesMessage(ValueError, msg): InvalidModelForm() # Even if you provide a model instance with self.assertRaisesMessage(ValueError, msg): InvalidModelForm(instance=Category) def test_subcategory_form(self): class SubCategoryForm(BaseCategoryForm): """ Subclassing without specifying a Meta on the class will use the parent's Meta (or the first parent in the MRO if there are multiple parent classes). """ pass self.assertEqual(list(SubCategoryForm.base_fields), ['name', 'slug', 'url']) def test_subclassmeta_form(self): class SomeCategoryForm(forms.ModelForm): checkbox = forms.BooleanField() class Meta: model = Category fields = '__all__' class SubclassMeta(SomeCategoryForm): """ We can also subclass the Meta inner class to change the fields list. """ class Meta(SomeCategoryForm.Meta): exclude = ['url'] self.assertHTMLEqual( str(SubclassMeta()), """<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr> <tr><th><label for="id_slug">Slug:</label></th> <td><input id="id_slug" type="text" name="slug" maxlength="20" required></td></tr> <tr><th><label for="id_checkbox">Checkbox:</label></th> <td><input type="checkbox" name="checkbox" id="id_checkbox" required></td></tr>""" ) def test_orderfields_form(self): class OrderFields(forms.ModelForm): class Meta: model = Category fields = ['url', 'name'] self.assertEqual(list(OrderFields.base_fields), ['url', 'name']) self.assertHTMLEqual( str(OrderFields()), """<tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr> <tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr>""" ) def test_orderfields2_form(self): class OrderFields2(forms.ModelForm): class Meta: model = Category fields = ['slug', 'url', 'name'] exclude = ['url'] self.assertEqual(list(OrderFields2.base_fields), ['slug', 'name']) def test_default_populated_on_optional_field(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data uses the model field default. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, 'di') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') # Blank data doesn't use the model field default. mf2 = PubForm({'mode': ''}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.mode, '') def test_default_not_populated_on_non_empty_value_in_cleaned_data(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) mocked_mode = None def clean(self): self.cleaned_data['mode'] = self.mocked_mode return self.cleaned_data class Meta: model = PublicationDefaults fields = ('mode',) pub_form = PubForm({}) pub_form.mocked_mode = 'de' pub = pub_form.save(commit=False) self.assertEqual(pub.mode, 'de') # Default should be populated on an empty value in cleaned_data. default_mode = 'di' for empty_value in pub_form.fields['mode'].empty_values: with self.subTest(empty_value=empty_value): pub_form = PubForm({}) pub_form.mocked_mode = empty_value pub = pub_form.save(commit=False) self.assertEqual(pub.mode, default_mode) def test_default_not_populated_on_optional_checkbox_input(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('active',) # Empty data doesn't use the model default because CheckboxInput # doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertIs(m1.active, False) self.assertIsInstance(mf1.fields['active'].widget, forms.CheckboxInput) self.assertIs(m1._meta.get_field('active').get_default(), True) def test_default_not_populated_on_checkboxselectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data doesn't use the model default because an unchecked # CheckboxSelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, '') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') def test_default_not_populated_on_selectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.SelectMultiple) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data doesn't use the model default because an unselected # SelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, '') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') def test_prefixed_form_with_default_field(self): class PubForm(forms.ModelForm): prefix = 'form-prefix' class Meta: model = PublicationDefaults fields = ('mode',) mode = 'de' self.assertNotEqual(mode, PublicationDefaults._meta.get_field('mode').get_default()) mf1 = PubForm({'form-prefix-mode': mode}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, mode) def test_renderer_kwarg(self): custom = object() self.assertIs(ProductForm(renderer=custom).renderer, custom) def test_default_splitdatetime_field(self): class PubForm(forms.ModelForm): datetime_published = forms.SplitDateTimeField(required=False) class Meta: model = PublicationDefaults fields = ('datetime_published',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.datetime_published, datetime.datetime(2000, 1, 1)) mf2 = PubForm({'datetime_published_0': '2010-01-01', 'datetime_published_1': '0:00:00'}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.datetime_published, datetime.datetime(2010, 1, 1)) def test_default_filefield(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('file',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.file.name, 'default.txt') mf2 = PubForm({}, {'file': SimpleUploadedFile('name', b'foo')}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.file.name, 'name') def test_default_selectdatewidget(self): class PubForm(forms.ModelForm): date_published = forms.DateField(required=False, widget=forms.SelectDateWidget) class Meta: model = PublicationDefaults fields = ('date_published',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.date_published, datetime.date.today()) mf2 = PubForm({'date_published_year': '2010', 'date_published_month': '1', 'date_published_day': '1'}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.date_published, datetime.date(2010, 1, 1)) class FieldOverridesByFormMetaForm(forms.ModelForm): class Meta: model = Category fields = ['name', 'url', 'slug'] widgets = { 'name': forms.Textarea, 'url': forms.TextInput(attrs={'class': 'url'}) } labels = { 'name': 'Title', } help_texts = { 'slug': 'Watch out! Letters, numbers, underscores and hyphens only.', } error_messages = { 'slug': { 'invalid': ( "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!" ) } } field_classes = { 'url': forms.URLField, } class TestFieldOverridesByFormMeta(SimpleTestCase): def test_widget_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form['name']), '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" required></textarea>', ) self.assertHTMLEqual( str(form['url']), '<input id="id_url" type="text" class="url" name="url" maxlength="40" required>', ) self.assertHTMLEqual( str(form['slug']), '<input id="id_slug" type="text" name="slug" maxlength="20" required>', ) def test_label_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form['name'].label_tag()), '<label for="id_name">Title:</label>', ) self.assertHTMLEqual( str(form['url'].label_tag()), '<label for="id_url">The URL:</label>', ) self.assertHTMLEqual( str(form['slug'].label_tag()), '<label for="id_slug">Slug:</label>', ) def test_help_text_overrides(self): form = FieldOverridesByFormMetaForm() self.assertEqual( form['slug'].help_text, 'Watch out! Letters, numbers, underscores and hyphens only.', ) def test_error_messages_overrides(self): form = FieldOverridesByFormMetaForm(data={ 'name': 'Category', 'url': 'http://www.example.com/category/', 'slug': '!%#*@', }) form.full_clean() error = [ "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!", ] self.assertEqual(form.errors, {'slug': error}) def test_field_type_overrides(self): form = FieldOverridesByFormMetaForm() self.assertIs(Category._meta.get_field('url').__class__, models.CharField) self.assertIsInstance(form.fields['url'], forms.URLField) class IncompleteCategoryFormWithFields(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: fields = ('name', 'slug') model = Category class IncompleteCategoryFormWithExclude(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: exclude = ['url'] model = Category class ValidationTest(SimpleTestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields(data={'name': 'some name', 'slug': 'some-slug'}) self.assertIs(form.is_valid(), True) def test_validates_with_replaced_field_excluded(self): form = IncompleteCategoryFormWithExclude(data={'name': 'some name', 'slug': 'some-slug'}) self.assertIs(form.is_valid(), True) def test_notrequired_overrides_notblank(self): form = CustomWriterForm({}) self.assertIs(form.is_valid(), True) class UniqueTest(TestCase): """ unique/unique_together validation. """ @classmethod def setUpTestData(cls): cls.writer = Writer.objects.create(name='Mike Royko') def test_simple_unique(self): form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertTrue(form.is_valid()) obj = form.save() form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Product with this Slug already exists.']) form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj) self.assertTrue(form.is_valid()) def test_unique_together(self): """ModelForm test of unique_together constraint""" form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertTrue(form.is_valid()) form.save() form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Price with this Price and Quantity already exists.']) def test_unique_together_exclusion(self): """ Forms don't validate unique_together constraints when only part of the constraint is included in the form's fields. This allows using form.save(commit=False) and then assigning the missing field(s) to the model instance. """ class BookForm(forms.ModelForm): class Meta: model = DerivedBook fields = ('isbn', 'suffix1') # The unique_together is on suffix1/suffix2 but only suffix1 is part # of the form. The fields must have defaults, otherwise they'll be # skipped by other logic. self.assertEqual(DerivedBook._meta.unique_together, (('suffix1', 'suffix2'),)) for name in ('suffix1', 'suffix2'): with self.subTest(name=name): field = DerivedBook._meta.get_field(name) self.assertEqual(field.default, 0) # The form fails validation with "Derived book with this Suffix1 and # Suffix2 already exists." if the unique_together validation isn't # skipped. DerivedBook.objects.create(isbn='12345') form = BookForm({'isbn': '56789', 'suffix1': '0'}) self.assertTrue(form.is_valid(), form.errors) def test_multiple_field_unique_together(self): """ When the same field is involved in multiple unique_together constraints, we need to make sure we don't remove the data for it before doing all the validation checking (not just failing after the first one). """ class TripleForm(forms.ModelForm): class Meta: model = Triple fields = '__all__' Triple.objects.create(left=1, middle=2, right=3) form = TripleForm({'left': '1', 'middle': '2', 'right': '3'}) self.assertFalse(form.is_valid()) form = TripleForm({'left': '1', 'middle': '3', 'right': '1'}) self.assertTrue(form.is_valid()) @skipUnlessDBFeature('supports_nullable_unique_constraints') def test_unique_null(self): title = 'I May Be Wrong But I Doubt It' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title, 'author': self.writer.pk}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) form = BookForm({'title': title}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title}) self.assertTrue(form.is_valid()) def test_inherited_unique(self): title = 'Boss' Book.objects.create(title=title, author=self.writer, special_id=1) form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': '1', 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['special_id'], ['Book with this Special id already exists.']) def test_inherited_unique_together(self): title = 'Boss' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = DerivedBookForm({'title': title, 'author': self.writer.pk, 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) def test_abstract_inherited_unique(self): title = 'Boss' isbn = '12345' DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({ 'title': 'Other', 'author': self.writer.pk, 'isbn': isbn, 'suffix1': '1', 'suffix2': '2', }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['isbn'], ['Derived book with this Isbn already exists.']) def test_abstract_inherited_unique_together(self): title = 'Boss' isbn = '12345' DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({ 'title': 'Other', 'author': self.writer.pk, 'isbn': '9876', 'suffix1': '0', 'suffix2': '0' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors['__all__'], ['Derived book with this Suffix1 and Suffix2 already exists.'], ) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" form = ExplicitPKForm({'key': '', 'desc': ''}) self.assertFalse(form.is_valid()) def test_explicitpk_unique(self): """Ensure keys and blank character strings are tested for uniqueness.""" form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertTrue(form.is_valid()) form.save() form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertFalse(form.is_valid()) if connection.features.interprets_empty_strings_as_nulls: self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) else: self.assertEqual(len(form.errors), 3) self.assertEqual(form.errors['__all__'], ['Explicit pk with this Key and Desc already exists.']) self.assertEqual(form.errors['desc'], ['Explicit pk with this Desc already exists.']) self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) def test_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = PostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = PostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} form = PostForm(data, instance=p) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['posted'], ['This field is required.']) def test_unique_for_date_in_exclude(self): """ If the date for unique_for_* constraints is excluded from the ModelForm (in this case 'posted' has editable=False, then the constraint should be ignored. """ class DateTimePostForm(forms.ModelForm): class Meta: model = DateTimePost fields = '__all__' DateTimePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.datetime(2008, 9, 3, 10, 10, 1), ) # 'title' has unique_for_date='posted' form = DateTimePostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) # 'slug' has unique_for_year='posted' form = DateTimePostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertTrue(form.is_valid()) # 'subtitle' has unique_for_month='posted' form = DateTimePostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertTrue(form.is_valid()) def test_inherited_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = DerivedPostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} form = DerivedPostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_unique_for_date_with_nullable_date(self): class FlexDatePostForm(forms.ModelForm): class Meta: model = FlexibleDatePost fields = '__all__' p = FlexibleDatePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = FlexDatePostForm({'title': "Django 1.0 is released"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'slug': "Django 1.0"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'subtitle': "Finally"}) self.assertTrue(form.is_valid()) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0"} form = FlexDatePostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_override_unique_message(self): class CustomProductForm(ProductForm): class Meta(ProductForm.Meta): error_messages = { 'slug': { 'unique': "%(model_name)s's %(field_label)s not unique.", } } Product.objects.create(slug='teddy-bear-blue') form = CustomProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ["Product's Slug not unique."]) def test_override_unique_together_message(self): class CustomPriceForm(PriceForm): class Meta(PriceForm.Meta): error_messages = { NON_FIELD_ERRORS: { 'unique_together': "%(model_name)s's %(field_labels)s not unique.", } } Price.objects.create(price=6.00, quantity=1) form = CustomPriceForm({'price': '6.00', 'quantity': '1'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."]) def test_override_unique_for_date_message(self): class CustomPostForm(PostForm): class Meta(PostForm.Meta): error_messages = { 'title': { 'unique_for_date': ( "%(model_name)s's %(field_label)s not unique " "for %(date_field_label)s date." ), } } Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = CustomPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ["Post's Title not unique for Posted date."]) class ModelFormBasicTests(TestCase): def create_basic_data(self): self.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') self.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') self.c3 = Category.objects.create(name='Third test', slug='third-test', url='third') self.w_royko = Writer.objects.create(name='Mike Royko') self.w_woodward = Writer.objects.create(name='Bob Woodward') def test_base_form(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm() self.assertHTMLEqual( str(f), """<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr> <tr><th><label for="id_slug">Slug:</label></th> <td><input id="id_slug" type="text" name="slug" maxlength="20" required></td></tr> <tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr>""" ) self.assertHTMLEqual( str(f.as_ul()), """<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" required></li> <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" required></li> <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" required></li>""" ) self.assertHTMLEqual( str(f["name"]), """<input id="id_name" type="text" name="name" maxlength="20" required>""") def test_auto_id(self): f = BaseCategoryForm(auto_id=False) self.assertHTMLEqual( str(f.as_ul()), """<li>Name: <input type="text" name="name" maxlength="20" required></li> <li>Slug: <input type="text" name="slug" maxlength="20" required></li> <li>The URL: <input type="text" name="url" maxlength="40" required></li>""" ) def test_initial_values(self): self.create_basic_data() # Initial values can be provided for model forms f = ArticleForm( auto_id=False, initial={ 'headline': 'Your headline here', 'categories': [str(self.c1.id), str(self.c2.id)] }) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s" selected>It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) # When the ModelForm is passed an instance, that instance's current values are # inserted as 'initial' data in each Field. f = RoykoForm(auto_id=False, instance=self.w_royko) self.assertHTMLEqual( str(f), '''<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" required><br> <span class="helptext">Use both first and last names.</span></td></tr>''' ) art = Article.objects.create( headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=self.w_royko, article='Hello.' ) art_id_1 = art.id f = ArticleForm(auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) f = ArticleForm({ 'headline': 'Test headline', 'slug': 'test-headline', 'pub_date': '1984-02-06', 'writer': str(self.w_royko.pk), 'article': 'Hello.' }, instance=art) self.assertEqual(f.errors, {}) self.assertTrue(f.is_valid()) test_art = f.save() self.assertEqual(test_art.id, art_id_1) test_art = Article.objects.get(id=art_id_1) self.assertEqual(test_art.headline, 'Test headline') def test_m2m_initial_callable(self): """ Regression for #10349: A callable can be provided as the initial value for an m2m field """ self.maxDiff = 1200 self.create_basic_data() # Set up a callable initial value def formfield_for_dbfield(db_field, **kwargs): if db_field.name == 'categories': kwargs['initial'] = lambda: Category.objects.all().order_by('name')[:2] return db_field.formfield(**kwargs) # Create a ModelForm, instantiate it, and check that the output is as expected ModelForm = modelform_factory( Article, fields=['headline', 'categories'], formfield_callback=formfield_for_dbfield, ) form = ModelForm() self.assertHTMLEqual( form.as_ul(), """<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="50" required></li> <li><label for="id_categories">Categories:</label> <select multiple name="categories" id="id_categories"> <option value="%d" selected>Entertainment</option> <option value="%d" selected>It&#x27;s a test</option> <option value="%d">Third test</option> </select></li>""" % (self.c1.pk, self.c2.pk, self.c3.pk)) def test_basic_creation(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm({ 'name': 'Entertainment', 'slug': 'entertainment', 'url': 'entertainment', }) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['name'], 'Entertainment') self.assertEqual(f.cleaned_data['slug'], 'entertainment') self.assertEqual(f.cleaned_data['url'], 'entertainment') c1 = f.save() # Testing whether the same object is returned from the # ORM... not the fastest way... self.assertEqual(Category.objects.count(), 1) self.assertEqual(c1, Category.objects.all()[0]) self.assertEqual(c1.name, "Entertainment") def test_save_commit_false(self): # If you call save() with commit=False, then it will return an object that # hasn't yet been saved to the database. In this case, it's up to you to call # save() on the resulting model instance. f = BaseCategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'}) self.assertTrue(f.is_valid()) c1 = f.save(commit=False) self.assertEqual(c1.name, "Third test") self.assertEqual(Category.objects.count(), 0) c1.save() self.assertEqual(Category.objects.count(), 1) def test_save_with_data_errors(self): # If you call save() with invalid data, you'll get a ValueError. f = BaseCategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'}) self.assertEqual(f.errors['name'], ['This field is required.']) self.assertEqual( f.errors['slug'], ['Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.'] ) self.assertEqual(f.cleaned_data, {'url': 'foo'}) msg = "The Category could not be created because the data didn't validate." with self.assertRaisesMessage(ValueError, msg): f.save() f = BaseCategoryForm({'name': '', 'slug': '', 'url': 'foo'}) with self.assertRaisesMessage(ValueError, msg): f.save() def test_multi_fields(self): self.create_basic_data() self.maxDiff = None # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any # fields with the 'choices' attribute are represented by a ChoiceField. f = ArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr> <tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" required></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr> <tr><th>Writer:</th><td><select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></td></tr> <tr><th>Article:</th><td><textarea rows="10" cols="40" name="article" required></textarea></td></tr> <tr><th>Categories:</th><td><select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></td></tr> <tr><th>Status:</th><td><select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></td></tr>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) # Add some categories and test the many-to-many form output. new_art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=self.w_royko) new_art.categories.add(Category.objects.get(name='Entertainment')) self.assertQuerysetEqual(new_art.categories.all(), ["Entertainment"]) f = ArticleForm(auto_id=False, instance=new_art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) def test_subset_fields(self): # You can restrict a form to a subset of the complete list of fields # by providing a 'fields' argument. If you try to save a # model created with such a form, you need to ensure that the fields # that are _not_ on the form have default values, or are allowed to have # a value of None. If a field isn't specified on a form, the object created # from the form can't provide a value for that field! class PartialArticleForm(forms.ModelForm): class Meta: model = Article fields = ('headline', 'pub_date') f = PartialArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr>''') class PartialArticleFormWithSlug(forms.ModelForm): class Meta: model = Article fields = ('headline', 'slug', 'pub_date') w_royko = Writer.objects.create(name='Mike Royko') art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=w_royko) f = PartialArticleFormWithSlug({ 'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04' }, auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>''' ) self.assertTrue(f.is_valid()) new_art = f.save() self.assertEqual(new_art.id, art.id) new_art = Article.objects.get(id=art.id) self.assertEqual(new_art.headline, 'New headline') def test_m2m_editing(self): self.create_basic_data() form_data = { 'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04', 'writer': str(self.w_royko.pk), 'article': 'Hello.', 'categories': [str(self.c1.id), str(self.c2.id)] } # Create a new article, with categories, via the form. f = ArticleForm(form_data) new_art = f.save() new_art = Article.objects.get(id=new_art.id) art_id_1 = new_art.id self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) # Now, submit form data with no categories. This deletes the existing categories. form_data['categories'] = [] f = ArticleForm(form_data, instance=new_art) new_art = f.save() self.assertEqual(new_art.id, art_id_1) new_art = Article.objects.get(id=art_id_1) self.assertQuerysetEqual(new_art.categories.all(), []) # Create a new article, with no categories, via the form. f = ArticleForm(form_data) new_art = f.save() art_id_2 = new_art.id self.assertNotIn(art_id_2, (None, art_id_1)) new_art = Article.objects.get(id=art_id_2) self.assertQuerysetEqual(new_art.categories.all(), []) # Create a new article, with categories, via the form, but use commit=False. # The m2m data won't be saved until save_m2m() is invoked on the form. form_data['categories'] = [str(self.c1.id), str(self.c2.id)] f = ArticleForm(form_data) new_art = f.save(commit=False) # Manually save the instance new_art.save() art_id_3 = new_art.id self.assertNotIn(art_id_3, (None, art_id_1, art_id_2)) # The instance doesn't have m2m data yet new_art = Article.objects.get(id=art_id_3) self.assertQuerysetEqual(new_art.categories.all(), []) # Save the m2m data on the form f.save_m2m() self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) def test_custom_form_fields(self): # Here, we define a custom ModelForm. Because it happens to have the same fields as # the Category model, we can just call the form's save() to apply its changes to an # existing Category instance. class ShortCategory(forms.ModelForm): name = forms.CharField(max_length=5) slug = forms.CharField(max_length=5) url = forms.CharField(max_length=3) class Meta: model = Category fields = '__all__' cat = Category.objects.create(name='Third test') form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat) self.assertEqual(form.save().name, 'Third') self.assertEqual(Category.objects.get(id=cat.id).name, 'Third') def test_runtime_choicefield_populated(self): self.maxDiff = None # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined # at runtime, based on the data in the database when the form is displayed, not # the data in the database when the form is instantiated. self.create_basic_data() f = ArticleForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select> </li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) c4 = Category.objects.create(name='Fourth', url='4th') w_bernstein = Writer.objects.create(name='Carl Bernstein') self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Carl Bernstein</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> <option value="%s">Fourth</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, w_bernstein.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk, c4.pk)) def test_recleaning_model_form_instance(self): """ Re-cleaning an instance that was added via a ModelForm shouldn't raise a pk uniqueness error. """ class AuthorForm(forms.ModelForm): class Meta: model = Author fields = '__all__' form = AuthorForm({'full_name': 'Bob'}) self.assertTrue(form.is_valid()) obj = form.save() obj.name = 'Alice' obj.full_clean() class ModelMultipleChoiceFieldTests(TestCase): @classmethod def setUpTestData(cls): cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') cls.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') cls.c3 = Category.objects.create(name='Third', slug='third-test', url='third') def test_model_multiple_choice_field(self): f = forms.ModelMultipleChoiceField(Category.objects.all()) self.assertEqual(list(f.choices), [ (self.c1.pk, 'Entertainment'), (self.c2.pk, "It's a test"), (self.c3.pk, 'Third')]) with self.assertRaises(ValidationError): f.clean(None) with self.assertRaises(ValidationError): f.clean([]) self.assertQuerysetEqual(f.clean([self.c1.id]), ["Entertainment"]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) self.assertQuerysetEqual(f.clean([str(self.c1.id)]), ["Entertainment"]) self.assertQuerysetEqual( f.clean([str(self.c1.id), str(self.c2.id)]), ["Entertainment", "It's a test"], ordered=False ) self.assertQuerysetEqual( f.clean([self.c1.id, str(self.c2.id)]), ["Entertainment", "It's a test"], ordered=False ) self.assertQuerysetEqual( f.clean((self.c1.id, str(self.c2.id))), ["Entertainment", "It's a test"], ordered=False ) with self.assertRaises(ValidationError): f.clean(['100']) with self.assertRaises(ValidationError): f.clean('hello') with self.assertRaises(ValidationError): f.clean(['fail']) # Invalid types that require TypeError to be caught (#22808). with self.assertRaises(ValidationError): f.clean([['fail']]) with self.assertRaises(ValidationError): f.clean([{'foo': 'bar'}]) # Add a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. # Note, we are using an id of 1006 here since tests that run before # this may create categories with primary keys up to 6. Use # a number that will not conflict. c6 = Category.objects.create(id=1006, name='Sixth', url='6th') self.assertQuerysetEqual(f.clean([c6.id]), ["Sixth"]) # Delete a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. Category.objects.get(url='6th').delete() with self.assertRaises(ValidationError): f.clean([c6.id]) def test_model_multiple_choice_required_false(self): f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False) self.assertIsInstance(f.clean([]), EmptyQuerySet) self.assertIsInstance(f.clean(()), EmptyQuerySet) with self.assertRaises(ValidationError): f.clean(['0']) with self.assertRaises(ValidationError): f.clean([str(self.c3.id), '0']) with self.assertRaises(ValidationError): f.clean([str(self.c1.id), '0']) # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name='Third') self.assertEqual(list(f.choices), [ (self.c1.pk, 'Entertainment'), (self.c2.pk, "It's a test")]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) with self.assertRaises(ValidationError): f.clean([self.c3.id]) with self.assertRaises(ValidationError): f.clean([str(self.c2.id), str(self.c3.id)]) f.queryset = Category.objects.all() f.label_from_instance = lambda obj: "multicategory " + str(obj) self.assertEqual(list(f.choices), [ (self.c1.pk, 'multicategory Entertainment'), (self.c2.pk, "multicategory It's a test"), (self.c3.pk, 'multicategory Third')]) def test_model_multiple_choice_number_of_queries(self): """ ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]]) def test_model_multiple_choice_run_validators(self): """ ModelMultipleChoiceField run given validators (#14144). """ for i in range(30): Writer.objects.create(name="Person %s" % i) self._validator_run = False def my_validator(value): self._validator_run = True f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all(), validators=[my_validator]) f.clean([p.pk for p in Writer.objects.all()[8:9]]) self.assertTrue(self._validator_run) def test_model_multiple_choice_show_hidden_initial(self): """ Test support of show_hidden_initial by ModelMultipleChoiceField. """ class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(show_hidden_initial=True, queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") person2 = Writer.objects.create(name="Person 2") form = WriterForm( initial={'persons': [person1, person2]}, data={ 'initial-persons': [str(person1.pk), str(person2.pk)], 'persons': [str(person1.pk), str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertFalse(form.has_changed()) form = WriterForm( initial={'persons': [person1, person2]}, data={ 'initial-persons': [str(person1.pk), str(person2.pk)], 'persons': [str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertTrue(form.has_changed()) def test_model_multiple_choice_field_22745(self): """ #22745 -- Make sure that ModelMultipleChoiceField with CheckboxSelectMultiple widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelMultipleChoiceForm(forms.Form): categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple) form = ModelMultipleChoiceForm() field = form['categories'] # BoundField template = Template('{{ field.name }}{{ field }}{{ field.help_text }}') with self.assertNumQueries(1): template.render(Context({'field': field})) def test_show_hidden_initial_changed_queries_efficiently(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all()) writers = (Writer.objects.create(name=str(x)) for x in range(0, 50)) writer_pks = tuple(x.pk for x in writers) form = WriterForm(data={'initial-persons': writer_pks}) with self.assertNumQueries(1): self.assertTrue(form.has_changed()) def test_clean_does_deduplicate_values(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") form = WriterForm(data={}) queryset = form.fields['persons'].clean([str(person1.pk)] * 50) sql, params = queryset.query.sql_with_params() self.assertEqual(len(params), 1) def test_to_field_name_with_initial_data(self): class ArticleCategoriesForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField(Category.objects.all(), to_field_name='slug') class Meta: model = Article fields = ['categories'] article = Article.objects.create( headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=Writer.objects.create(name='Test writer'), article='Hello.', ) article.categories.add(self.c2, self.c3) form = ArticleCategoriesForm(instance=article) self.assertCountEqual(form['categories'].value(), [self.c2.slug, self.c3.slug]) class ModelOneToOneFieldTests(TestCase): def test_modelform_onetoonefield(self): class ImprovedArticleForm(forms.ModelForm): class Meta: model = ImprovedArticle fields = '__all__' class ImprovedArticleWithParentLinkForm(forms.ModelForm): class Meta: model = ImprovedArticleWithParentLink fields = '__all__' self.assertEqual(list(ImprovedArticleForm.base_fields), ['article']) self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), []) def test_modelform_subclassed_model(self): class BetterWriterForm(forms.ModelForm): class Meta: # BetterWriter model is a subclass of Writer with an additional `score` field model = BetterWriter fields = '__all__' bw = BetterWriter.objects.create(name='Joe Better', score=10) self.assertEqual(sorted(model_to_dict(bw)), ['id', 'name', 'score', 'writer_ptr']) self.assertEqual(sorted(model_to_dict(bw, fields=[])), []) self.assertEqual(sorted(model_to_dict(bw, fields=['id', 'name'])), ['id', 'name']) self.assertEqual(sorted(model_to_dict(bw, exclude=[])), ['id', 'name', 'score', 'writer_ptr']) self.assertEqual(sorted(model_to_dict(bw, exclude=['id', 'name'])), ['score', 'writer_ptr']) form = BetterWriterForm({'name': 'Some Name', 'score': 12}) self.assertTrue(form.is_valid()) bw2 = form.save() self.assertEqual(bw2.score, 12) def test_onetoonefield(self): class WriterProfileForm(forms.ModelForm): class Meta: # WriterProfile has a OneToOneField to Writer model = WriterProfile fields = '__all__' self.w_royko = Writer.objects.create(name='Mike Royko') self.w_woodward = Writer.objects.create(name='Bob Woodward') form = WriterProfileForm() self.assertHTMLEqual( form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" required></p>''' % ( self.w_woodward.pk, self.w_royko.pk, ) ) data = { 'writer': str(self.w_woodward.pk), 'age': '65', } form = WriterProfileForm(data) instance = form.save() self.assertEqual(str(instance), 'Bob Woodward is 65') form = WriterProfileForm(instance=instance) self.assertHTMLEqual( form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="">---------</option> <option value="%s" selected>Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" value="65" id="id_age" min="0" required></p>''' % ( self.w_woodward.pk, self.w_royko.pk, ) ) def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertTrue(form.is_valid()) self.assertIsNone(form.cleaned_data['publication']) author = form.save() # author object returned from form still retains original publication object # that's why we need to retrieve it from database again new_author = Author.objects.get(pk=author.pk) self.assertIsNone(new_author.publication) def test_assignment_of_none_null_false(self): class AuthorForm(forms.ModelForm): class Meta: model = Author1 fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author1.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertFalse(form.is_valid()) class FileAndImageFieldTests(TestCase): def test_clean_false(self): """ If the ``clean`` method on a non-required FileField receives False as the data (meaning clear the field value), it returns False, regardless of the value of ``initial``. """ f = forms.FileField(required=False) self.assertIs(f.clean(False), False) self.assertIs(f.clean(False, 'initial'), False) def test_clean_false_required(self): """ If the ``clean`` method on a required FileField receives False as the data, it has the same effect as None: initial is returned if non-empty, otherwise the validation catches the lack of a required value. """ f = forms.FileField(required=True) self.assertEqual(f.clean(False, 'initial'), 'initial') with self.assertRaises(ValidationError): f.clean(False) def test_full_clear(self): """ Integration happy-path test that a model FileField can actually be set and cleared via a ModelForm. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' form = DocumentForm() self.assertIn('name="myfile"', str(form)) self.assertNotIn('myfile-clear', str(form)) form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) self.assertEqual(doc.myfile.name, 'something.txt') form = DocumentForm(instance=doc) self.assertIn('myfile-clear', str(form)) form = DocumentForm(instance=doc, data={'myfile-clear': 'true'}) doc = form.save(commit=False) self.assertFalse(doc.myfile) def test_clear_and_file_contradiction(self): """ If the user submits a new file upload AND checks the clear checkbox, they get a validation error, and the bound redisplay of the form still includes the current file and the clear checkbox. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) form = DocumentForm( instance=doc, files={'myfile': SimpleUploadedFile('something.txt', b'content')}, data={'myfile-clear': 'true'}, ) self.assertTrue(not form.is_valid()) self.assertEqual(form.errors['myfile'], ['Please either submit a file or check the clear checkbox, not both.']) rendered = str(form) self.assertIn('something.txt', rendered) self.assertIn('myfile-clear', rendered) def test_render_empty_file_field(self): class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' doc = Document.objects.create() form = DocumentForm(instance=doc) self.assertHTMLEqual( str(form['myfile']), '<input id="id_myfile" name="myfile" type="file">' ) def test_file_field_data(self): # Test conditions when files is either not given or empty. f = TextFileForm(data={'description': 'Assistance'}) self.assertFalse(f.is_valid()) f = TextFileForm(data={'description': 'Assistance'}, files={}) self.assertFalse(f.is_valid()) # Upload a file and ensure it all works as expected. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') instance.file.delete() # If the previous file has been deleted, the file name can be reused f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') # Check if the max_length attribute has been inherited from the model. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')}, ) self.assertFalse(f.is_valid()) # Edit an instance that already has the file defined in the model. This will not # save the file again, but leave it exactly as it is. f = TextFileForm({'description': 'Assistance'}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['file'].name, 'tests/test1.txt') instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') # Delete the current file since this is not done by Django. instance.file.delete() # Override the file by uploading a new one. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test2.txt') # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_filefield_required_false(self): # Test the non-required FileField f = TextFileForm(data={'description': 'Assistance'}) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, '') f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test3.txt') # Instance can be edited w/out re-uploading the file and existing file should be preserved. f = TextFileForm({'description': 'New Description'}, instance=instance) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.file.name, 'tests/test3.txt') # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_custom_file_field_save(self): """ Regression for #11149: save_form_data should be called only once """ class CFFForm(forms.ModelForm): class Meta: model = CustomFF fields = '__all__' # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. form = CFFForm(data={'f': None}) form.save() def test_file_field_multiple_save(self): """ Simulate a file upload and check how many times Model.save() gets called. Test for bug #639. """ class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = '__all__' # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), 'test.png') with open(filename, "rb") as fp: img = fp.read() # Fake a POST QueryDict and FILES MultiValueDict. data = {'title': 'Testing'} files = {"image": SimpleUploadedFile('test.png', img, 'image/png')} form = PhotoForm(data=data, files=files) p = form.save() try: # Check the savecount stored on the object (see the model). self.assertEqual(p._savecount, 1) finally: # Delete the "uploaded" file to avoid clogging /tmp. p = Photo.objects.get() p.image.delete(save=False) def test_file_path_field_blank(self): """FilePathField(blank=True) includes the empty option.""" class FPForm(forms.ModelForm): class Meta: model = FilePathModel fields = '__all__' form = FPForm() self.assertEqual([name for _, name in form['path'].field.choices], ['---------', 'models.py']) @skipUnless(test_images, "Pillow not installed") def test_image_field(self): # ImageField and FileField are nearly identical, but they differ slightly when # it comes to validation. This specifically tests that #6302 is fixed for # both file fields and image fields. with open(os.path.join(os.path.dirname(__file__), 'test.png'), 'rb') as fp: image_data = fp.read() with open(os.path.join(os.path.dirname(__file__), 'test2.png'), 'rb') as fp: image_data2 = fp.read() f = ImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) f = ImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Edit an instance that already has the (required) image defined in the model. This will not # save the image again, but leave it exactly as it is. f = ImageFileForm(data={'description': 'Look, it changed'}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['image'].name, 'tests/test.png') instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.height, 16) self.assertEqual(instance.width, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) # Override the file by uploading a new one. f = ImageFileForm( data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() f = ImageFileForm( data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() # Test the non-required ImageField # Note: In Oracle, we expect a null ImageField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_imagefield_repr = '' else: expected_null_imagefield_repr = None f = OptionalImageFileForm(data={'description': 'Test'}) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, expected_null_imagefield_repr) self.assertIsNone(instance.width) self.assertIsNone(instance.height) f = OptionalImageFileForm( data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test3.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Editing the instance without re-uploading the image should not affect # the image or its width/height properties. f = OptionalImageFileForm({'description': 'New Description'}, instance=instance) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.image.name, 'tests/test3.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django. instance.image.delete() instance.delete() f = OptionalImageFileForm( data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test4.png', image_data2)} ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test4.png') self.assertEqual(instance.width, 48) self.assertEqual(instance.height, 32) instance.delete() # Test callable upload_to behavior that's dependent on the value of another field in the model f = ImageFileForm( data={'description': 'And a final one', 'path': 'foo'}, files={'image': SimpleUploadedFile('test4.png', image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'foo/test4.png') instance.delete() # Editing an instance that has an image without an extension shouldn't # fail validation. First create: f = NoExtensionImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/no_extension') # Then edit: f = NoExtensionImageFileForm(data={'description': 'Edited image'}, instance=instance) self.assertTrue(f.is_valid()) class ModelOtherFieldTests(SimpleTestCase): def test_big_integer_field(self): bif = BigIntForm({'biggie': '-9223372036854775808'}) self.assertTrue(bif.is_valid()) bif = BigIntForm({'biggie': '-9223372036854775809'}) self.assertFalse(bif.is_valid()) self.assertEqual( bif.errors, {'biggie': ['Ensure this value is greater than or equal to -9223372036854775808.']} ) bif = BigIntForm({'biggie': '9223372036854775807'}) self.assertTrue(bif.is_valid()) bif = BigIntForm({'biggie': '9223372036854775808'}) self.assertFalse(bif.is_valid()) self.assertEqual(bif.errors, {'biggie': ['Ensure this value is less than or equal to 9223372036854775807.']}) def test_url_on_modelform(self): "Check basic URL field validation on model forms" class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = '__all__' self.assertFalse(HomepageForm({'url': 'foo'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://com.'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://localhost'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com/foo/bar'}).is_valid()) def test_modelform_non_editable_field(self): """ When explicitly including a non-editable field in a ModelForm, the error message should be explicit. """ # 'created', non-editable, is excluded by default self.assertNotIn('created', ArticleForm().fields) msg = "'created' cannot be specified for Article model form as it is a non-editable field" with self.assertRaisesMessage(FieldError, msg): class InvalidArticleForm(forms.ModelForm): class Meta: model = Article fields = ('headline', 'created') def test_http_prefixing(self): """ If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613) """ class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = '__all__' form = HomepageForm({'url': 'example.com'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['url'], 'http://example.com') form = HomepageForm({'url': 'example.com/test'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['url'], 'http://example.com/test') class OtherModelFormTests(TestCase): def test_media_on_modelform(self): # Similar to a regular Form class you can define custom media to be used on # the ModelForm. f = ModelFormWithMedia() self.assertHTMLEqual( str(f.media), '''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet"> <script src="/some/form/javascript"></script>''' ) def test_choices_type(self): # Choices on CharField and IntegerField f = ArticleForm() with self.assertRaises(ValidationError): f.fields['status'].clean('42') f = ArticleStatusForm() with self.assertRaises(ValidationError): f.fields['status'].clean('z') def test_prefetch_related_queryset(self): """ ModelChoiceField should respect a prefetch_related() on its queryset. """ blue = Colour.objects.create(name='blue') red = Colour.objects.create(name='red') multicolor_item = ColourfulItem.objects.create() multicolor_item.colours.add(blue, red) red_item = ColourfulItem.objects.create() red_item.colours.add(red) class ColorModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return ', '.join(c.name for c in obj.colours.all()) field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related('colours')) with self.assertNumQueries(3): # would be 4 if prefetch is ignored self.assertEqual(tuple(field.choices), ( ('', '---------'), (multicolor_item.pk, 'blue, red'), (red_item.pk, 'red'), )) def test_foreignkeys_which_use_to_field(self): apple = Inventory.objects.create(barcode=86, name='Apple') Inventory.objects.create(barcode=22, name='Pear') core = Inventory.objects.create(barcode=87, name='Core', parent=apple) field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode') self.assertEqual(tuple(field.choices), ( ('', '---------'), (86, 'Apple'), (87, 'Core'), (22, 'Pear'))) form = InventoryForm(instance=core) self.assertHTMLEqual(str(form['parent']), '''<select name="parent" id="id_parent"> <option value="">---------</option> <option value="86" selected>Apple</option> <option value="87">Core</option> <option value="22">Pear</option> </select>''') data = model_to_dict(core) data['parent'] = '22' form = InventoryForm(data=data, instance=core) core = form.save() self.assertEqual(core.parent.name, 'Pear') class CategoryForm(forms.ModelForm): description = forms.CharField() class Meta: model = Category fields = ['description', 'url'] self.assertEqual(list(CategoryForm.base_fields), ['description', 'url']) self.assertHTMLEqual( str(CategoryForm()), '''<tr><th><label for="id_description">Description:</label></th> <td><input type="text" name="description" id="id_description" required></td></tr> <tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr>''' ) # to_field_name should also work on ModelMultipleChoiceField ################## field = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') self.assertEqual(tuple(field.choices), ((86, 'Apple'), (87, 'Core'), (22, 'Pear'))) self.assertQuerysetEqual(field.clean([86]), ['Apple']) form = SelectInventoryForm({'items': [87, 22]}) self.assertTrue(form.is_valid()) self.assertEqual(len(form.cleaned_data), 1) self.assertQuerysetEqual(form.cleaned_data['items'], ['Core', 'Pear']) def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self): self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ['name']) self.assertHTMLEqual( str(CustomFieldForExclusionForm()), '''<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="10" required></td></tr>''' ) def test_iterable_model_m2m(self): class ColourfulItemForm(forms.ModelForm): class Meta: model = ColourfulItem fields = '__all__' colour = Colour.objects.create(name='Blue') form = ColourfulItemForm() self.maxDiff = 1024 self.assertHTMLEqual( form.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" required></p> <p><label for="id_colours">Colours:</label> <select multiple name="colours" id="id_colours" required> <option value="%(blue_pk)s">Blue</option> </select></p>""" % {'blue_pk': colour.pk}) def test_callable_field_default(self): class PublicationDefaultsForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('title', 'date_published', 'mode', 'category') self.maxDiff = 2000 form = PublicationDefaultsForm() today_str = str(datetime.date.today()) self.assertHTMLEqual( form.as_p(), """ <p><label for="id_title">Title:</label> <input id="id_title" maxlength="30" name="title" type="text" required></p> <p><label for="id_date_published">Date published:</label> <input id="id_date_published" name="date_published" type="text" value="{0}" required> <input id="initial-id_date_published" name="initial-date_published" type="hidden" value="{0}"></p> <p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode"> <option value="di" selected>direct</option> <option value="de">delayed</option></select> <input id="initial-id_mode" name="initial-mode" type="hidden" value="di"></p> <p><label for="id_category">Category:</label> <select id="id_category" name="category"> <option value="1">Games</option> <option value="2">Comics</option> <option value="3" selected>Novel</option></select> <input id="initial-id_category" name="initial-category" type="hidden" value="3"> """.format(today_str) ) empty_data = { 'title': '', 'date_published': today_str, 'initial-date_published': today_str, 'mode': 'di', 'initial-mode': 'di', 'category': '3', 'initial-category': '3', } bound_form = PublicationDefaultsForm(empty_data) self.assertFalse(bound_form.has_changed()) class ModelFormCustomErrorTests(SimpleTestCase): def test_custom_error_messages(self): data = {'name1': '@#$!!**@#$', 'name2': '@#$!!**@#$'} errors = CustomErrorMessageForm(data).errors self.assertHTMLEqual( str(errors['name1']), '<ul class="errorlist"><li>Form custom error message.</li></ul>' ) self.assertHTMLEqual( str(errors['name2']), '<ul class="errorlist"><li>Model custom error message.</li></ul>' ) def test_model_clean_error_messages(self): data = {'name1': 'FORBIDDEN_VALUE', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors['name1']), '<ul class="errorlist"><li>Model.clean() error messages.</li></ul>' ) data = {'name1': 'FORBIDDEN_VALUE2', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors['name1']), '<ul class="errorlist"><li>Model.clean() error messages (simpler syntax).</li></ul>' ) data = {'name1': 'GLOBAL_ERROR', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['__all__'], ['Global error message.']) class CustomCleanTests(TestCase): def test_override_clean(self): """ Regression for #12596: Calling super from ModelForm.clean() should be optional. """ class TripleFormWithCleanOverride(forms.ModelForm): class Meta: model = Triple fields = '__all__' def clean(self): if not self.cleaned_data['left'] == self.cleaned_data['right']: raise ValidationError('Left and right should be equal') return self.cleaned_data form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1}) self.assertTrue(form.is_valid()) # form.instance.left will be None if the instance was not constructed # by form.full_clean(). self.assertEqual(form.instance.left, 1) def test_model_form_clean_applies_to_model(self): """ Regression test for #12960. Make sure the cleaned_data returned from ModelForm.clean() is applied to the model instance. """ class CategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' def clean(self): self.cleaned_data['name'] = self.cleaned_data['name'].upper() return self.cleaned_data data = {'name': 'Test', 'slug': 'test', 'url': '/test'} form = CategoryForm(data) category = form.save() self.assertEqual(category.name, 'TEST') class ModelFormInheritanceTests(SimpleTestCase): def test_form_subclass_inheritance(self): class Form(forms.Form): age = forms.IntegerField() class ModelForm(forms.ModelForm, Form): class Meta: model = Writer fields = '__all__' self.assertEqual(list(ModelForm().fields), ['name', 'age']) def test_field_removal(self): class ModelForm(forms.ModelForm): class Meta: model = Writer fields = '__all__' class Mixin: age = None class Form(forms.Form): age = forms.IntegerField() class Form2(forms.Form): foo = forms.IntegerField() self.assertEqual(list(ModelForm().fields), ['name']) self.assertEqual(list(type('NewForm', (Mixin, Form), {})().fields), []) self.assertEqual(list(type('NewForm', (Form2, Mixin, Form), {})().fields), ['foo']) self.assertEqual(list(type('NewForm', (Mixin, ModelForm, Form), {})().fields), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Mixin, Form), {})().fields), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Form, Mixin), {})().fields), ['name', 'age']) self.assertEqual(list(type('NewForm', (ModelForm, Form), {'age': None})().fields), ['name']) def test_field_removal_name_clashes(self): """ Form fields can be removed in subclasses by setting them to None (#22510). """ class MyForm(forms.ModelForm): media = forms.CharField() class Meta: model = Writer fields = '__all__' class SubForm(MyForm): media = None self.assertIn('media', MyForm().fields) self.assertNotIn('media', SubForm().fields) self.assertTrue(hasattr(MyForm, 'media')) self.assertTrue(hasattr(SubForm, 'media')) class StumpJokeForm(forms.ModelForm): class Meta: model = StumpJoke fields = '__all__' class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field): queryset = 42 class StumpJokeWithCustomFieldForm(forms.ModelForm): custom = CustomFieldWithQuerysetButNoLimitChoicesTo() class Meta: model = StumpJoke fields = () class LimitChoicesToTests(TestCase): """ Tests the functionality of ``limit_choices_to``. """ @classmethod def setUpTestData(cls): cls.threepwood = Character.objects.create( username='threepwood', last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) cls.marley = Character.objects.create( username='marley', last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) def test_limit_choices_to_callable_for_fk_rel(self): """ A ForeignKey can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual(stumpjokeform.fields['most_recently_fooled'].queryset, [self.threepwood]) def test_limit_choices_to_callable_for_m2m_rel(self): """ A ManyToManyField can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual(stumpjokeform.fields['most_recently_fooled'].queryset, [self.threepwood]) def test_custom_field_with_queryset_but_no_limit_choices_to(self): """ A custom field with a `queryset` attribute but no `limit_choices_to` works (#23795). """ f = StumpJokeWithCustomFieldForm() self.assertEqual(f.fields['custom'].queryset, 42) def test_fields_for_model_applies_limit_choices_to(self): fields = fields_for_model(StumpJoke, ['has_fooled_today']) self.assertSequenceEqual(fields['has_fooled_today'].queryset, [self.threepwood]) def test_callable_called_each_time_form_is_instantiated(self): field = StumpJokeForm.base_fields['most_recently_fooled'] with mock.patch.object(field, 'limit_choices_to') as today_callable_dict: StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 1) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 2) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 3) class FormFieldCallbackTests(SimpleTestCase): def test_baseform_with_widgets_in_meta(self): """Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.""" widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} fields = "__all__" Form = modelform_factory(Person, form=BaseForm) self.assertIsInstance(Form.base_fields['name'].widget, forms.Textarea) def test_factory_with_widget_argument(self): """ Regression for #15315: modelform_factory should accept widgets argument """ widget = forms.Textarea() # Without a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__") self.assertNotEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) # With a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__", widgets={'name': widget}) self.assertEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) def test_modelform_factory_without_fields(self): """ Regression for #19733 """ message = ( "Calling modelform_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelform_factory(Person) def test_modelform_factory_with_all_fields(self): """ Regression for #19733 """ form = modelform_factory(Person, fields="__all__") self.assertEqual(list(form.base_fields), ["name"]) def test_custom_callback(self): """A custom formfield_callback is used if provided""" callback_args = [] def callback(db_field, **kwargs): callback_args.append((db_field, kwargs)) return db_field.formfield(**kwargs) widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} fields = "__all__" modelform_factory(Person, form=BaseForm, formfield_callback=callback) id_field, name_field = Person._meta.fields self.assertEqual(callback_args, [(id_field, {}), (name_field, {'widget': widget})]) def test_bad_callback(self): # A bad callback provided by user still gives an error with self.assertRaises(TypeError): modelform_factory(Person, fields="__all__", formfield_callback='not a function or callable') def test_inherit_after_custom_callback(self): def callback(db_field, **kwargs): if isinstance(db_field, models.CharField): return forms.CharField(widget=forms.Textarea) return db_field.formfield(**kwargs) class BaseForm(forms.ModelForm): class Meta: model = Person fields = '__all__' NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback) class InheritedForm(NewForm): pass for name in NewForm.base_fields: self.assertEqual( type(InheritedForm.base_fields[name].widget), type(NewForm.base_fields[name].widget) ) class LocalizedModelFormTest(TestCase): def test_model_form_applies_localize_to_some_fields(self): class PartiallyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = ('left', 'right',) fields = '__all__' f = PartiallyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields['left'].localize) self.assertFalse(f.fields['middle'].localize) self.assertTrue(f.fields['right'].localize) def test_model_form_applies_localize_to_all_fields(self): class FullyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = '__all__' fields = '__all__' f = FullyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields['left'].localize) self.assertTrue(f.fields['middle'].localize) self.assertTrue(f.fields['right'].localize) def test_model_form_refuses_arbitrary_string(self): msg = ( "BrokenLocalizedTripleForm.Meta.localized_fields " "cannot be a string. Did you mean to type: ('foo',)?" ) with self.assertRaisesMessage(TypeError, msg): class BrokenLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = "foo" class CustomMetaclass(ModelFormMetaclass): def __new__(cls, name, bases, attrs): new = super().__new__(cls, name, bases, attrs) new.base_fields = {} return new class CustomMetaclassForm(forms.ModelForm, metaclass=CustomMetaclass): pass class CustomMetaclassTestCase(SimpleTestCase): def test_modelform_factory_metaclass(self): new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm) self.assertEqual(new_cls.base_fields, {}) class StrictAssignmentTests(SimpleTestCase): """ Should a model do anything special with __setattr__() or descriptors which raise a ValidationError, a model form should catch the error (#24706). """ def test_setattr_raises_validation_error_field_specific(self): """ A model ValidationError using the dict form should put the error message into the correct key of form.errors. """ form_class = modelform_factory(model=StrictAssignmentFieldSpecific, fields=['title']) form = form_class(data={'title': 'testing setattr'}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'title': ['Cannot set attribute', 'This field cannot be blank.'] }) def test_setattr_raises_validation_error_non_field(self): """ A model ValidationError not using the dict form should put the error message into __all__ (i.e. non-field errors) on the form. """ form_class = modelform_factory(model=StrictAssignmentAll, fields=['title']) form = form_class(data={'title': 'testing setattr'}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { '__all__': ['Cannot set attribute'], 'title': ['This field cannot be blank.'] }) class ModelToDictTests(TestCase): def test_many_to_many(self): """Data for a ManyToManyField is a list rather than a lazy QuerySet.""" blue = Colour.objects.create(name='blue') red = Colour.objects.create(name='red') item = ColourfulItem.objects.create() item.colours.set([blue]) data = model_to_dict(item)['colours'] self.assertEqual(data, [blue]) item.colours.set([red]) # If data were a QuerySet, it would be reevaluated here and give "red" # instead of the original value. self.assertEqual(data, [blue])
{ "content_hash": "60ba785a8b27fb6ffa1464bb1ce733bd", "timestamp": "", "source": "github", "line_count": 2974, "max_line_length": 127, "avg_line_length": 40.25924680564896, "alnum_prop": 0.5991096708454786, "repo_name": "theo-l/django", "id": "cb8d7c3f842789ff04f40ed0928c6f5cfde756e2", "size": "119735", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/model_forms/tests.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "54515" }, { "name": "HTML", "bytes": "172728" }, { "name": "JavaScript", "bytes": "247742" }, { "name": "Makefile", "bytes": "125" }, { "name": "Python", "bytes": "11279991" }, { "name": "Shell", "bytes": "809" }, { "name": "Smarty", "bytes": "130" } ], "symlink_target": "" }
package org.elasticsearch.xpack.ml.filestructurefinder; import com.ibm.icu.text.CharsetDetector; import com.ibm.icu.text.CharsetMatch; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.unit.TimeValue; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; /** * Runs the high-level steps needed to create ingest configs for the specified file. In order: * 1. Determine the most likely character set (UTF-8, UTF-16LE, ISO-8859-2, etc.) * 2. Load a sample of the file, consisting of the first 1000 lines of the file * 3. Determine the most likely file structure - one of ND-JSON, XML, delimited or semi-structured text * 4. Create an appropriate structure object and delegate writing configs to it */ public final class FileStructureFinderManager { public static final int MIN_SAMPLE_LINE_COUNT = 2; public static final int DEFAULT_IDEAL_SAMPLE_LINE_COUNT = 1000; static final Set<String> FILEBEAT_SUPPORTED_ENCODINGS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "866", "ansi_x3.4-1968", "arabic", "ascii", "asmo-708", "big5", "big5-hkscs", "chinese", "cn-big5", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "cp819", "cp866", "csbig5", "cseuckr", "cseucpkdfmtjapanese", "csgb2312", "csibm866", "csiso2022jp", "csiso2022kr", "csiso58gb231280", "csiso88596e", "csiso88596i", "csiso88598e", "csiso88598i", "csisolatin1", "csisolatin2", "csisolatin3", "csisolatin4", "csisolatin5", "csisolatin6", "csisolatin9", "csisolatinarabic", "csisolatincyrillic", "csisolatingreek", "csisolatinhebrew", "cskoi8r", "csksc56011987", "csmacintosh", "csshiftjis", "cyrillic", "dos-874", "ecma-114", "ecma-118", "elot_928", "euc-jp", "euc-kr", "gb18030", "gb2312", "gb_2312", "gb_2312-80", "gbk", "greek", "greek8", "hebrew", "hz-gb-2312", "ibm819", "ibm866", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-jp", "iso-2022-kr", "iso-8859-1", "iso-8859-10", "iso-8859-11", "iso-8859-13", "iso-8859-14", "iso-8859-15", "iso-8859-16", "iso-8859-2", "iso-8859-3", "iso-8859-4", "iso-8859-5", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-8859-7", "iso-8859-8", "iso-8859-8-e", "iso-8859-8-i", "iso-8859-9", "iso-ir-100", "iso-ir-101", "iso-ir-109", "iso-ir-110", "iso-ir-126", "iso-ir-127", "iso-ir-138", "iso-ir-144", "iso-ir-148", "iso-ir-149", "iso-ir-157", "iso-ir-58", "iso8859-1", "iso8859-10", "iso8859-11", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5", "iso8859-6", "iso8859-6e", "iso8859-6i", "iso8859-7", "iso8859-8", "iso8859-8e", "iso8859-8i", "iso8859-9", "iso88591", "iso885910", "iso885911", "iso885913", "iso885914", "iso885915", "iso88592", "iso88593", "iso88594", "iso88595", "iso88596", "iso88597", "iso88598", "iso88599", "iso_8859-1", "iso_8859-15", "iso_8859-1:1987", "iso_8859-2", "iso_8859-2:1987", "iso_8859-3", "iso_8859-3:1988", "iso_8859-4", "iso_8859-4:1988", "iso_8859-5", "iso_8859-5:1988", "iso_8859-6", "iso_8859-6:1987", "iso_8859-7", "iso_8859-7:1987", "iso_8859-8", "iso_8859-8:1988", "iso_8859-9", "iso_8859-9:1989", "koi", "koi8", "koi8-r", "koi8-ru", "koi8-u", "koi8_r", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "l1", "l2", "l3", "l4", "l5", "l6", "l9", "latin1", "latin2", "latin3", "latin4", "latin5", "latin6", "logical", "mac", "macintosh", "ms932", "ms_kanji", "shift-jis", "shift_jis", "sjis", "sun_eu_greek", "tis-620", "unicode-1-1-utf-8", "us-ascii", "utf-16", "utf-16-bom", "utf-16be", "utf-16be-bom", "utf-16le", "utf-16le-bom", "utf-8", "utf8", "visual", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255", "windows-1256", "windows-1257", "windows-1258", "windows-31j", "windows-874", "windows-949", "x-cp1250", "x-cp1251", "x-cp1252", "x-cp1253", "x-cp1254", "x-cp1255", "x-cp1256", "x-cp1257", "x-cp1258", "x-euc-jp", "x-gbk", "x-mac-cyrillic", "x-mac-roman", "x-mac-ukrainian", "x-sjis", "x-x-big5" ))); /** * These need to be ordered so that the more generic formats come after the more specific ones */ private static final List<FileStructureFinderFactory> ORDERED_STRUCTURE_FACTORIES = Collections.unmodifiableList(Arrays.asList( new JsonFileStructureFinderFactory(), new XmlFileStructureFinderFactory(), // ND-JSON will often also be valid (although utterly weird) CSV, so JSON must come before CSV new DelimitedFileStructureFinderFactory(',', '"', 2, false), new DelimitedFileStructureFinderFactory('\t', '"', 2, false), new DelimitedFileStructureFinderFactory(';', '"', 4, false), new DelimitedFileStructureFinderFactory('|', '"', 5, true), new TextLogFileStructureFinderFactory() )); private static final int BUFFER_SIZE = 8192; private final ScheduledExecutorService scheduler; /** * Create the file structure manager. * @param scheduler Used for checking timeouts. */ public FileStructureFinderManager(ScheduledExecutorService scheduler) { this.scheduler = Objects.requireNonNull(scheduler); } public FileStructureFinder findFileStructure(Integer idealSampleLineCount, InputStream fromFile) throws Exception { return findFileStructure(idealSampleLineCount, fromFile, FileStructureOverrides.EMPTY_OVERRIDES, null); } /** * Given a stream of data from some file, determine its structure. * @param idealSampleLineCount Ideally, how many lines from the stream will be read to determine the structure? * If the stream has fewer lines then an attempt will still be made, providing at * least {@link #MIN_SAMPLE_LINE_COUNT} lines can be read. If <code>null</code> * the value of {@link #DEFAULT_IDEAL_SAMPLE_LINE_COUNT} will be used. * @param fromFile A stream from which the sample will be read. * @param overrides Aspects of the file structure that are known in advance. These take precedence over * values determined by structure analysis. An exception will be thrown if the file structure * is incompatible with an overridden value. * @param timeout The maximum time the analysis is permitted to take. If it takes longer than this an * {@link ElasticsearchTimeoutException} may be thrown (although not necessarily immediately * the timeout is exceeded). * @return A {@link FileStructureFinder} object from which the structure and messages can be queried. * @throws Exception A variety of problems could occur at various stages of the structure finding process. */ public FileStructureFinder findFileStructure(Integer idealSampleLineCount, InputStream fromFile, FileStructureOverrides overrides, TimeValue timeout) throws Exception { return findFileStructure(new ArrayList<>(), (idealSampleLineCount == null) ? DEFAULT_IDEAL_SAMPLE_LINE_COUNT : idealSampleLineCount, fromFile, overrides, timeout); } public FileStructureFinder findFileStructure(List<String> explanation, int idealSampleLineCount, InputStream fromFile) throws Exception { return findFileStructure(explanation, idealSampleLineCount, fromFile, FileStructureOverrides.EMPTY_OVERRIDES, null); } public FileStructureFinder findFileStructure(List<String> explanation, int idealSampleLineCount, InputStream fromFile, FileStructureOverrides overrides, TimeValue timeout) throws Exception { try (TimeoutChecker timeoutChecker = new TimeoutChecker("structure analysis", timeout, scheduler)) { String charsetName = overrides.getCharset(); Reader sampleReader; if (charsetName != null) { // Creating the reader will throw if the specified character set does not exist sampleReader = new InputStreamReader(fromFile, charsetName); explanation.add("Using specified character encoding [" + charsetName + "]"); } else { CharsetMatch charsetMatch = findCharset(explanation, fromFile, timeoutChecker); charsetName = charsetMatch.getName(); sampleReader = charsetMatch.getReader(); } Tuple<String, Boolean> sampleInfo = sampleFile(sampleReader, charsetName, MIN_SAMPLE_LINE_COUNT, Math.max(MIN_SAMPLE_LINE_COUNT, idealSampleLineCount), timeoutChecker); return makeBestStructureFinder(explanation, sampleInfo.v1(), charsetName, sampleInfo.v2(), overrides, timeoutChecker); } } CharsetMatch findCharset(List<String> explanation, InputStream inputStream, TimeoutChecker timeoutChecker) throws Exception { // We need an input stream that supports mark and reset, so wrap the argument // in a BufferedInputStream if it doesn't already support this feature if (inputStream.markSupported() == false) { inputStream = new BufferedInputStream(inputStream, BUFFER_SIZE); } // This is from ICU4J CharsetDetector charsetDetector = new CharsetDetector().setText(inputStream); CharsetMatch[] charsetMatches = charsetDetector.detectAll(); timeoutChecker.check("character set detection"); // Determine some extra characteristics of the input to compensate for some deficiencies of ICU4J boolean pureAscii = true; boolean containsZeroBytes = false; inputStream.mark(BUFFER_SIZE); byte[] workspace = new byte[BUFFER_SIZE]; int remainingLength = BUFFER_SIZE; do { int bytesRead = inputStream.read(workspace, 0, remainingLength); if (bytesRead <= 0) { break; } for (int i = 0; i < bytesRead && containsZeroBytes == false; ++i) { if (workspace[i] == 0) { containsZeroBytes = true; pureAscii = false; } else { pureAscii = pureAscii && workspace[i] > 0 && workspace[i] < 128; } } remainingLength -= bytesRead; } while (containsZeroBytes == false && remainingLength > 0); inputStream.reset(); timeoutChecker.check("character set detection"); if (pureAscii) { // If the input is pure ASCII then many single byte character sets will match. We want to favour // UTF-8 in this case, as it avoids putting a bold declaration of a dubious character set choice // in the config files. Optional<CharsetMatch> utf8CharsetMatch = Arrays.stream(charsetMatches) .filter(charsetMatch -> StandardCharsets.UTF_8.name().equals(charsetMatch.getName())).findFirst(); if (utf8CharsetMatch.isPresent()) { explanation.add("Using character encoding [" + StandardCharsets.UTF_8.name() + "], which matched the input with [" + utf8CharsetMatch.get().getConfidence() + "%] confidence - first [" + (BUFFER_SIZE / 1024) + "kB] of input was pure ASCII"); return utf8CharsetMatch.get(); } } // Input wasn't pure ASCII, so use the best matching character set that's supported by both Java and Go. // Additionally, if the input contains zero bytes then avoid single byte character sets, as ICU4J will // suggest these for binary files but then for (CharsetMatch charsetMatch : charsetMatches) { String name = charsetMatch.getName(); if (Charset.isSupported(name) && FILEBEAT_SUPPORTED_ENCODINGS.contains(name.toLowerCase(Locale.ROOT))) { // This extra test is to avoid trying to read binary files as text. Running the structure // finding algorithms on binary files is very slow as the binary files generally appear to // have very long lines. boolean spaceEncodingContainsZeroByte = false; Charset charset = Charset.forName(name); // Some character sets cannot be encoded. These are extremely rare so it's likely that // they've been chosen based on incorrectly provided binary data. Therefore, err on // the side of rejecting binary data. if (charset.canEncode()) { byte[] spaceBytes = " ".getBytes(charset); for (int i = 0; i < spaceBytes.length && spaceEncodingContainsZeroByte == false; ++i) { spaceEncodingContainsZeroByte = (spaceBytes[i] == 0); } } if (containsZeroBytes && spaceEncodingContainsZeroByte == false) { explanation.add("Character encoding [" + name + "] matched the input with [" + charsetMatch.getConfidence() + "%] confidence but was rejected as the input contains zero bytes and the [" + name + "] encoding does not"); } else { explanation.add("Using character encoding [" + name + "], which matched the input with [" + charsetMatch.getConfidence() + "%] confidence"); return charsetMatch; } } else { explanation.add("Character encoding [" + name + "] matched the input with [" + charsetMatch.getConfidence() + "%] confidence but was rejected as it is not supported by [" + (Charset.isSupported(name) ? "Filebeat" : "the JVM") + "]"); } } throw new IllegalArgumentException("Could not determine a usable character encoding for the input" + (containsZeroBytes ? " - could it be binary data?" : "")); } FileStructureFinder makeBestStructureFinder(List<String> explanation, String sample, String charsetName, Boolean hasByteOrderMarker, FileStructureOverrides overrides, TimeoutChecker timeoutChecker) throws Exception { Character delimiter = overrides.getDelimiter(); Character quote = overrides.getQuote(); Boolean shouldTrimFields = overrides.getShouldTrimFields(); List<FileStructureFinderFactory> factories; if (delimiter != null) { // If a precise delimiter is specified, we only need one structure finder // factory, and we'll tolerate as little as one column in the input factories = Collections.singletonList(new DelimitedFileStructureFinderFactory(delimiter, (quote == null) ? '"' : quote, 1, (shouldTrimFields == null) ? (delimiter == '|') : shouldTrimFields)); } else if (quote != null || shouldTrimFields != null) { // The delimiter is not specified, but some other aspect of delimited files is, // so clone our default delimited factories altering the overridden values factories = ORDERED_STRUCTURE_FACTORIES.stream().filter(factory -> factory instanceof DelimitedFileStructureFinderFactory) .map(factory -> ((DelimitedFileStructureFinderFactory) factory).makeSimilar(quote, shouldTrimFields)) .collect(Collectors.toList()); } else { // We can use the default factories, but possibly filtered down to a specific format factories = ORDERED_STRUCTURE_FACTORIES.stream() .filter(factory -> factory.canFindFormat(overrides.getFormat())).collect(Collectors.toList()); } for (FileStructureFinderFactory factory : factories) { timeoutChecker.check("high level format detection"); if (factory.canCreateFromSample(explanation, sample)) { return factory.createFromSample(explanation, sample, charsetName, hasByteOrderMarker, overrides, timeoutChecker); } } throw new IllegalArgumentException("Input did not match " + ((overrides.getFormat() == null) ? "any known formats" : "the specified format [" + overrides.getFormat() + "]")); } private Tuple<String, Boolean> sampleFile(Reader reader, String charsetName, int minLines, int maxLines, TimeoutChecker timeoutChecker) throws IOException { int lineCount = 0; BufferedReader bufferedReader = new BufferedReader(reader); StringBuilder sample = new StringBuilder(); // Don't include any byte-order-marker in the sample. (The logic to skip it works for both // UTF-8 and UTF-16 assuming the character set of the reader was correctly detected.) Boolean hasByteOrderMarker = null; if (charsetName.toUpperCase(Locale.ROOT).startsWith("UTF")) { int maybeByteOrderMarker = reader.read(); hasByteOrderMarker = ((char) maybeByteOrderMarker == '\uFEFF'); if (maybeByteOrderMarker >= 0 && hasByteOrderMarker == false && (char) maybeByteOrderMarker != '\r') { sample.appendCodePoint(maybeByteOrderMarker); if ((char) maybeByteOrderMarker == '\n') { ++lineCount; } } } String line; while ((line = bufferedReader.readLine()) != null && ++lineCount <= maxLines) { sample.append(line).append('\n'); timeoutChecker.check("sample line splitting"); } if (lineCount < minLines) { throw new IllegalArgumentException("Input contained too few lines [" + lineCount + "] to obtain a meaningful sample"); } return new Tuple<>(sample.toString(), hasByteOrderMarker); } }
{ "content_hash": "26579049c647dbe8e17a9547604ac4d0", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 140, "avg_line_length": 58.848101265822784, "alnum_prop": 0.6383093138309314, "repo_name": "gfyoung/elasticsearch", "id": "a508735af07f3d46d4472f2418041bcbddb07bf2", "size": "18837", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/filestructurefinder/FileStructureFinderManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "13592" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "330070" }, { "name": "HTML", "bytes": "2186" }, { "name": "Java", "bytes": "42238459" }, { "name": "Perl", "bytes": "7271" }, { "name": "Python", "bytes": "54395" }, { "name": "Shell", "bytes": "108747" } ], "symlink_target": "" }
import Component from '@ember/component' import ClusterDriver from 'shared/mixins/cluster-driver'; import layout from './template'; import { get, set, computed, observer, setProperties } from '@ember/object'; import { sortableNumericSuffix } from 'shared/utils/util'; import { reject, all } from 'rsvp'; import { inject as service } from '@ember/service'; import { equal } from '@ember/object/computed' const times = [ { value: null, label: 'Any Time', }, { value: '00:00', label: '12:00AM', }, { value: '03:00', label: '3:00AM', }, { value: '06:00', label: '6:00AM', }, { value: '09:00', label: '9:00AM', }, { value: '12:00', label: '12:00PM', }, { value: '15:00', label: '3:00PM', }, { value: '19:00', label: '7:00PM', }, { value: '21:00', label: '9:00PM', }, ] const imageType = [ { label: 'clusterNew.googlegke.imageType.UBUNTU', value: 'UBUNTU', }, { label: 'clusterNew.googlegke.imageType.COS', value: 'COS' }, ] const diskType = [ { label: 'clusterNew.googlegke.diskType.pd-standard', value: 'pd-standard', }, { label: 'clusterNew.googlegke.diskType.pd-ssd', value: 'pd-ssd', } ] const DEFAULT_AUTH_SCOPES = ['devstorage.read_only', 'logging.write', 'monitoring', 'servicecontrol', 'service.management.readonly', 'trace.append'] export default Component.extend(ClusterDriver, { intl: service(), layout, configField: 'googleKubernetesEngineConfig', step: 1, zones: null, versions: null, machineTypes: null, initialMasterVersion: null, maintenanceWindowTimes: times, eipIdContent: [], imageTypeContent: imageType, clusterAdvanced: false, nodeAdvanced: false, diskTypeContent: diskType, scopeConfig: {}, hideNewField: false, isNew: equal('mode', 'new'), editing: equal('mode', 'edit'), init() { this._super(...arguments); let config = get(this, 'cluster.googleKubernetesEngineConfig'); if ( !config ) { config = get(this, 'globalStore').createRecord({ type: 'googleKubernetesEngineConfig', diskSizeGb: 100, enableAlphaFeature: false, nodeCount: 3, machineType: 'n1-standard-2', zone: 'us-central1-f', clusterIpv4Cidr: '', minNodeCount: 1, maxNodeCount: 5, imageType: 'UBUNTU', diskType: 'pd-standard', taints: [], }); setProperties(this, { 'cluster.googleKubernetesEngineConfig': config, oauthScopesSelection: 'default', scopeConfig: { userInfo: 'none', computeEngine: 'none', storage: 'devstorage.read_only', taskQueue: 'none', bigQuery: 'none', cloudSQL: 'none', cloudDatastore: 'none', stackdriverLoggingAPI: 'logging.write', stackdriverMonitoringAPI: 'monitoring', cloudPlatform: 'none', bigtableData: 'none', bigtableAdmin: 'none', cloudPub: 'none', serviceControl: 'none', serviceManagement: 'service.management.readonly', stackdriverTrace: 'trace.append', cloudSourceRepositories: 'none', cloudDebugger: 'none' }, resourceLabels: [], labels: [], taints: [], }) } else { const { resourceLabels = [], labels = [], taints = [], imageType } = config if (!imageType) { set(this, 'hideNewField', true) } let map = {} if (resourceLabels) { resourceLabels.map((t = '') => { const split = t.split('=') set(map, split[0], split[1]) }) set(this, 'resourceLabels', map) } if (labels) { labels.map((t = '') => { const split = t.split('=') set(map, split[0], split[1]) }) set(this, 'labels', map) } if (taints) { let _taints = taints.map((t = '') => { const splitEffect = t.split(':') const splitLabel = (splitEffect[1] || '').split('=') return { effect: splitEffect[0], key: splitLabel[0], value: splitLabel[1], } }) set(this, 'taints', _taints) } else { set(this, 'taints', []) } } set(this, 'initialMasterVersion', get(this, 'config.masterVersion')); }, actions: { clickNext() { this.$('BUTTON[type="submit"]').click(); }, checkServiceAccount(cb) { set(this, 'errors', []); return all([ this.fetchZones(), this.fetchVersions(), this.fetchMachineTypes(), this.fetchNetworks(), this.fetchSubnetworks(), this.fetchServiceAccounts(), ]).then(() => { set(this, 'step', 2); cb(true); }).catch(() => { cb(false); }); }, setLabels(section) { const out = [] for (let key in section) { out.pushObject(`${ key }=${ section[key] }`) } set(this, 'config.resourceLabels', out); }, setNodeLabels(section) { const out = [] for (let key in section) { out.pushObject(`${ key }=${ section[key] }`) } set(this, 'config.labels', out); }, updateNameservers(nameservers) { set(this, 'config.masterAuthorizedNetworkCidrBlocks', nameservers); }, setTaints(value) { set(this, 'config.taints', value); }, }, credentialChanged: observer('config.credential', function() { if (this.saving) { return; } const str = get(this, 'config.credential'); if ( str ) { try { const obj = JSON.parse(str); // Note: this is a Google project id, not ours. const projectId = obj.project_id; set(this, 'config.projectId', projectId); } catch (e) { } } }), zoneChanged: observer('config.zone', 'zones.[]', function() { if (this.saving) { return; } const zones = get(this, 'zones') || []; const currentZone = zones.findBy('name', get(this, 'config.zone')); if ( !currentZone || currentZone.status.toLowerCase() !== 'up' ) { const newZone = zones.filter((x) => x.name.startsWith('us-')).find((x) => x.status.toLowerCase() === 'up'); if ( newZone ) { set(this, 'config.zone', newZone.name); } } this.fetchVersions(); this.fetchMachineTypes(); this.fetchNetworks(); this.fetchSubnetworks(); this.fetchServiceAccounts(); }), machineTypeChanged: observer('config.machineTypes', 'machineTypes.[]', function() { if (this.saving) { return; } const types = get(this, 'machineTypes') || []; const current = types.findBy('name', get(this, 'config.machineType')); if ( !current ) { set(this, 'config.machineType', get(types, 'firstObject.name')); } }), versionChanged: observer('config.masterVersion', 'versionChoices.[]', function() { if (this.saving) { return; } const versions = get(this, 'versionChoices') || []; const current = get(this, 'config.masterVersion'); const exists = versions[versions.indexOf(current)]; if ( !exists ) { set(this, 'config.masterVersion', versions[0]); } }), networkChange: observer('config.network', 'subNetworkContent.[]', function() { if (this.saving) { return; } const subNetworkContent = get(this, 'subNetworkContent') || [] if (subNetworkContent.length > 0) { set(this, 'config.subNetwork', subNetworkContent[0] && subNetworkContent[0].value) const secondaryIpRangeContent = get(this, 'secondaryIpRangeContent') || [] if (secondaryIpRangeContent.length > 0) { const value = secondaryIpRangeContent[0] && secondaryIpRangeContent[0].value setProperties(this, { 'config.ipPolicyClusterSecondaryRangeName': value, 'config.ipPolicyServicesSecondaryRangeName': value, }) } } }), secondaryIpRangeContentChange: observer('secondaryIpRangeContent.[]', 'config.useIpAliases', function() { if (this.saving) { return; } const secondaryIpRangeContent = get(this, 'secondaryIpRangeContent') || [] if (secondaryIpRangeContent.length === 0) { set(this, 'config.ipPolicyCreateSubnetwork', true) } }), useIpAliasesChange: observer('config.useIpAliases', function() { if (this.saving) { return; } if (!get(this, 'config.useIpAliases')) { set(this, 'config.enablePrivateNodes', false) } }), enablePrivateNodesChange: observer('config.enablePrivateNodes', function() { if (this.saving) { return; } const config = get(this, 'config') if (!get(config, 'enablePrivateNodes')) { setProperties(config, { enablePrivateEndpoint: false, masterIpv4CidrBlock: '', }) } }), zoneChoices: computed('zones.[]', function() { let out = (get(this, 'zones') || []).slice(); out.forEach((obj) => { set(obj, 'sortName', sortableNumericSuffix(obj.name)); set(obj, 'displayName', `${ obj.name } (${ obj.description })`); set(obj, 'disabled', obj.status.toLowerCase() !== 'up'); }); return out.sortBy('sortName') }), machineChoices: computed('machineTypes.[]', function() { let out = (get(this, 'machineTypes') || []).slice(); out.forEach((obj) => { set(obj, 'sortName', sortableNumericSuffix(obj.name)); set(obj, 'displayName', `${ obj.name } (${ obj.description })`); }); return out.sortBy('sortName') }), editedMachineChoice: computed('machineChoices', 'config', function() { return get(this, 'machineChoices').findBy('name', get(this, 'config.machineType')); }), versionChoices: computed('versions.validMasterVersions.[]', 'config.masterVersion', function() { return get(this, 'versions.validMasterVersions'); }), locationContent: computed('config.zone', function() { const zone = get(this, 'config.zone') const arr = zone.split('-') const locationName = `${ arr[0] }-${ arr[1] }` const zoneChoices = get(this, 'zoneChoices') return zoneChoices.filter((z) => (z.name || '').startsWith(locationName) && z.name !== zone) }), networkContent: computed('networks', function() { return get(this, 'networks') }), subNetworkContent: computed('subNetworks.[]', 'config.network', function() { const subNetworks = get(this, 'subNetworks') || [] const networkName = get(this, 'config.network') const out = subNetworks.filter((s) => { const { network = '' } = s const arr = network.split('/') || [] const networkDisplayName = arr[arr.length - 1] if (networkDisplayName === networkName) { return true } }) return out.map((o) => { return { label: `${ o.name }(${ o.ipCidrRange })`, value: o.name, secondaryIpRanges: o.secondaryIpRanges, } }) }), secondaryIpRangeContent: computed('subNetworkContent.[]', 'config.network', function() { const subNetworkContent = get(this, 'subNetworkContent') const { secondaryIpRanges = [] } = subNetworkContent return secondaryIpRanges.map((s) => { return { lable: `${ s.rangeName }(${ s.ipCidrRange })`, value: s.rangeName, } }) }), serviceAccountContent: computed('serviceAccounts', function() { const serviceAccounts = get(this, 'serviceAccounts') return serviceAccounts }), maintenanceWindowChoice: computed('maintenanceWindowTimes.[]', 'config.maintenanceWindow', function() { return get(this, 'maintenanceWindowTimes').findBy('value', get(this, 'config.maintenanceWindow')) || { label: 'Any Time' }; }), fetchZones() { return get(this, 'globalStore').rawRequest({ url: '/meta/gkeZones', method: 'POST', data: { credentials: get(this, 'config.credential'), projectId: get(this, 'config.projectId'), } }).then((xhr) => { const out = xhr.body.items; const locations = get(this, 'config.locations') || [] if (locations.length > 0) { out.map((o) => { if (locations.includes(o.name)) { set(o, 'checked', true) } }) } set(this, 'zones', out); return out; }).catch((xhr) => { set(this, 'errors', [xhr.body.error]); return reject(); }); }, fetchVersions() { return get(this, 'globalStore').rawRequest({ url: '/meta/gkeVersions', method: 'POST', data: { credentials: get(this, 'config.credential'), projectId: get(this, 'config.projectId'), zone: get(this, 'config.zone'), } }).then((xhr) => { const out = xhr.body; set(this, 'versions', out); this.versionChanged(); return out; }).catch((xhr) => { set(this, 'errors', [xhr.body.error]); return reject(); }); }, fetchMachineTypes() { return get(this, 'globalStore').rawRequest({ url: '/meta/gkeMachineTypes', method: 'POST', data: { credentials: get(this, 'config.credential'), projectId: get(this, 'config.projectId'), zone: get(this, 'config.zone'), } }).then((xhr) => { const out = xhr.body.items; set(this, 'machineTypes', out); return out; }).catch((xhr) => { set(this, 'errors', [xhr.body.error]); return reject(); }); }, fetchNetworks() { return get(this, 'globalStore').rawRequest({ url: '/meta/gkeNetworks', method: 'POST', data: { credentials: get(this, 'config.credential'), projectId: get(this, 'config.projectId'), zone: get(this, 'config.zone'), } }).then((xhr) => { const out = xhr.body.items || []; set(this, 'networks', out); if (get(this, 'mode') === 'new') { set(this, 'config.network', out[0] && out[0].name) } return out; }).catch((xhr) => { set(this, 'errors', [xhr.body.error]); return reject(); }); }, fetchSubnetworks() { const zone = get(this, 'config.zone') const zoneSplit = zone.split('-') return get(this, 'globalStore').rawRequest({ url: '/meta/gkeSubnetworks', method: 'POST', data: { credentials: get(this, 'config.credential'), projectId: get(this, 'config.projectId'), region: `${ zoneSplit[0] }-${ zoneSplit[1] }`, } }).then((xhr) => { const out = xhr.body.items || []; set(this, 'subNetworks', out); return out; }).catch((xhr) => { set(this, 'errors', [xhr.body.error]); return reject(); }); }, fetchServiceAccounts() { return get(this, 'globalStore').rawRequest({ url: '/meta/gkeServiceAccounts', method: 'POST', data: { credentials: get(this, 'config.credential'), projectId: get(this, 'config.projectId'), zone: get(this, 'config.zone'), } }).then((xhr) => { const out = xhr.body.accounts || []; set(this, 'serviceAccounts', out); const filter = out.filter((o) => o.displayName === 'Compute Engine default service account') if (get(this, 'mode') === 'new') { set(this, 'config.serviceAccount', filter[0] && filter[0].uniqueId) } return out; }).catch((xhr) => { set(this, 'errors', [xhr.body.error]); return reject(); }); }, validate() { const model = get(this, 'cluster'); const errors = model.validationErrors(); const { intl, config = {} } = this let { minNodeCount, maxNodeCount, enableNodepoolAutoscaling, nodeCount } = config if ( enableNodepoolAutoscaling ) { if ( nodeCount && maxNodeCount && minNodeCount ) { nodeCount = parseInt(nodeCount, 10); maxNodeCount = parseInt(maxNodeCount, 10); minNodeCount = parseInt(minNodeCount, 10); if (maxNodeCount < minNodeCount) { errors.pushObject(intl.t('clusterNew.googlegke.maxNodeCount.minError')) } if ( enableNodepoolAutoscaling && ( maxNodeCount < nodeCount ) ) { errors.pushObject(intl.t('clusterNew.googlegke.nodeCount.outsideError')) } if ( enableNodepoolAutoscaling && ( minNodeCount > nodeCount ) ) { errors.pushObject(intl.t('clusterNew.googlegke.nodeCount.outsideError')) } } else { if ( !nodeCount ) { errors.pushObject(intl.t('clusterNew.googlegke.nodeCount.required')) } if ( !maxNodeCount ) { errors.pushObject(intl.t('clusterNew.googlegke.maxNodeCount.required')) } if ( !minNodeCount ) { errors.pushObject(intl.t('clusterNew.googlegke.minNodeCount.required')) } } } if (!get(this, 'cluster.name')) { errors.pushObject(intl.t('clusterNew.name.required')) } const taints = get(this, 'taints') || [] if (taints.length > 0) { const filter = taints.filter((t) => !t.key || !t.value) if (filter.length > 0) { errors.pushObject(intl.t('clusterNew.googlegke.taints.required')) } } set(this, 'errors', errors); return errors.length === 0; }, willSave() { const config = get(this, 'config') || {} if (!get(config, 'enableNodepoolAutoscaling')) { setProperties(config, { minNodeCount: 0, maxNodeCount: 0, }) } if (get(this, 'config.useIpAliases') && get(config, 'ipPolicyCreateSubnetwork') && get(config, 'ipPolicyClusterIpv4CidrBlock')) { set(config, 'clusterIpv4Cidr', '') } if (!get(config, 'enableMasterAuthorizedNetwork')) { delete config.masterAuthorizedNetworkCidrBlocks } if (!get(config, 'resourceLabels')) { delete config.resourceLabels } const locationContent = get(this, 'locationContent') const locations = locationContent.filter((l) => l.checked).map((l) => l.name) if (locations.length > 0) { locations.push(get(config, 'zone')) set(config, 'locations', locations) } else { delete config.locations } if (get(this, 'oauthScopesSelection') === 'default') { set(config, 'oauthScopes', DEFAULT_AUTH_SCOPES.map((a) => `https://www.googleapis.com/auth/${ a }`)) } else if (get(this, 'oauthScopesSelection') === 'full') { set(config, 'oauthScopes', ['https://www.googleapis.com/auth/cloud-platform']) } else if (get(this, 'oauthScopesSelection') === 'custom') { const scopeConfig = get(this, 'scopeConfig') || {} let arr = [] Object.keys(scopeConfig).map((key) => { if (scopeConfig[key] !== 'none') { arr.pushObject(`https://www.googleapis.com/auth/${ scopeConfig[key] }`) } }) set(config, 'oauthScopes', arr) } const taints = get(this, 'taints') || [] if (taints.length > 0) { set(config, 'taints', taints.map((t) => { return `${ t.effect }:${ t.key }=${ t.value }` })) } else { set(config, 'taints', []) } set(config, 'issueClientCertificate', true) return this._super(...arguments); }, });
{ "content_hash": "75c7c815ef52fef5b73dae77158537da", "timestamp": "", "source": "github", "line_count": 740, "max_line_length": 148, "avg_line_length": 26.85810810810811, "alnum_prop": 0.5529056603773584, "repo_name": "lvuch/ui", "id": "74f3a3b97218fb9f1ac19f02685b17696672bc35", "size": "19875", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/shared/addon/components/cluster-driver/driver-googlegke/component.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "174666" }, { "name": "Dockerfile", "bytes": "196" }, { "name": "HTML", "bytes": "1415278" }, { "name": "JavaScript", "bytes": "2335968" }, { "name": "Shell", "bytes": "10901" } ], "symlink_target": "" }
<?php defined('COREPATH') or exit('No direct script access allowed'); ?> ERROR - 2017-08-29 02:03:29 --> Fatal Error - Call to undefined method Model\Test::get_company() in /var/www/ysgservice.com/fuel/app/classes/controller/api/test.php on line 15
{ "content_hash": "b2dae54ba4259c9541831924911f456b", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 175, "avg_line_length": 83.33333333333333, "alnum_prop": 0.732, "repo_name": "yyoshinori/CastlePortal", "id": "bb68dcd442f54f63cca6f11be8448abcee00f054", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fuel/app/logs/2017/08/29.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2172" }, { "name": "Batchfile", "bytes": "5124" }, { "name": "CSS", "bytes": "2022443" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "HTML", "bytes": "4111809" }, { "name": "JavaScript", "bytes": "9835909" }, { "name": "Makefile", "bytes": "8073" }, { "name": "PHP", "bytes": "2297635" }, { "name": "PowerShell", "bytes": "471" }, { "name": "Python", "bytes": "8002" }, { "name": "Ruby", "bytes": "1030" }, { "name": "Shell", "bytes": "1124" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.Research.Naiad; using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.DataStructures; using Microsoft.Research.Naiad.Frameworks.Lindi; using Microsoft.Research.Naiad.Frameworks.Reduction; using Microsoft.Research.Naiad.Frameworks.DifferentialDataflow; using Microsoft.Research.Naiad.Input; namespace Microsoft.Research.Naiad.Examples.PageRank { public class PageRank : Example { public struct IntInt : IEquatable<IntInt> { public int first; public int second; public bool Equals(IntInt that) { return first == that.first && second == that.second; } public int CompareTo(IntInt that) { if (this.first != that.first) return this.first - that.first; return this.second - that.second; } public override int GetHashCode() { return 47 * first + 36425232 * second; } public override string ToString() { return String.Format("{0} {1}", first, second); } public IntInt(int ss, int tt) { first = ss; second = tt; } } public struct IntDouble : IEquatable<IntDouble> { public int first; public double second; public bool Equals(IntDouble that) { return first == that.first && second == that.second; } public int CompareTo(IntDouble that) { if (first != that.first) return first - that.first; if (second < that.second) { return -1; } else if (second > that.second) { return 1; } else { return 0; } } public override int GetHashCode() { return 47 * first + 36425232 * second.GetHashCode(); } public override string ToString() { return String.Format("{0} {1}", first, second); } public IntDouble(int x, double y) { first = x; second = y; } } public IEnumerable<IntInt> read_edges(string filename) { StreamReader reader = File.OpenText(filename); for (; !reader.EndOfStream; ) { var elements = reader.ReadLine().Split(' '); yield return new IntInt(Convert.ToInt32(elements[0]),Convert.ToInt32(elements[1])); } } public IEnumerable<IntDouble> read_pr(string filename) { StreamReader reader = File.OpenText(filename); for (; !reader.EndOfStream; ) { var elements = reader.ReadLine().Split(' '); yield return new IntDouble(Convert.ToInt32(elements[0]),Convert.ToDouble(elements[1])); } } public struct Reducernode_cnt : IAddable<Reducernode_cnt> { public int value0; public Reducernode_cnt(int value0) { this.value0 = value0; } public Reducernode_cnt Add(Reducernode_cnt other) { value0 += other.value0; return this; } } public struct Reducerpr1 : IAddable<Reducerpr1> { public double value0; public Reducerpr1(double value0) { this.value0 = value0; } public Reducerpr1 Add(Reducerpr1 other) { value0 += other.value0; return this; } } public struct IntIntInt : IEquatable<IntIntInt> { public int first; public int second; public int third; public bool Equals(IntIntInt that) { return first == that.first && second == that.second && third == that.third; } public int CompareTo(IntIntInt that) { if (this.first != that.first) return this.first - that.first; if (this.second != that.second) return this.second - that.second; return this.third - that.third; } // Embarassing hashcodes public override int GetHashCode() { return first + 1234347 * second + 4311 * third; } public override string ToString() { return String.Format("{0} {1} {2}", first, second, third); } public IntIntInt(int x, int y, int z) { first = x; second = y; third = z; } } public struct IntIntIntDouble : IEquatable<IntIntIntDouble> { public int first; public int second; public int third; public double fourth; public bool Equals(IntIntIntDouble that) { return first == that.first && second == that.second && third == that.third && Math.Abs(fourth - that.fourth) < 0.0000001; } public int CompareTo(IntIntIntDouble that) { if (this.first != that.first) return this.first - that.first; if (this.second != that.second) return this.second - that.second; if (this.third != that.third) return this.third - that.third; return this.fourth - that.fourth < 0 ? -1 : 1; } // Embarassing hashcodes public override int GetHashCode() { return first + 1234347 * second + 4311 * third + fourth.GetHashCode(); } public override string ToString() { return String.Format("{0} {1} {2} {3}", first, second, third, fourth); } public IntIntIntDouble(int x, int y, int z, double zz) { first = x; second = y; third = z; fourth = zz; } } public string Usage {get {return "<graph> <local path prefix>";} } public void Execute(string[] args) { using (var computation = NewComputation.FromArgs(ref args)) { var edges_input = new BatchedDataSource<string>(); var pr_input = new BatchedDataSource<string>(); var edges = computation.NewInput(edges_input).SelectMany(line => read_edges(line)); var pr = computation.NewInput(pr_input).SelectMany(line => read_pr(line)); var node_cnt_tmp = edges.GenericAggregator(row => row.first, row => new Reducernode_cnt(1)); var node_cnt = node_cnt_tmp.Select(row => { Reducernode_cnt aggVal = (Reducernode_cnt)row.Second ; return new IntInt(row.First, aggVal.value0); }); var edgescnt = edges.Join(node_cnt, (IntInt left) => left.first, (IntInt right) => right.first, (IntInt left, IntInt right) => new IntIntInt(left.first, left.second , right.second)); for (int i = 0; i < 5; ++i) { var edgespr = edgescnt.Join(pr, (IntIntInt left) => left.first, (IntDouble right) => right.first, (IntIntInt left, IntDouble right) => new IntIntIntDouble(left.first, left.second, left.third , right.second)); var rankcnt = edgespr.Select(row => new IntIntIntDouble(row.first,row.second,row.third,row.fourth / row.third)); var links = rankcnt.Select(row => new IntDouble(row.second,row.fourth)); var pr1_tmp = links.GenericAggregator(row => row.first, row => new Reducerpr1(row.second)); var pr1 = pr1_tmp.Select(row => { Reducerpr1 aggVal = (Reducerpr1)row.Second ; return new IntDouble(row.First, aggVal.value0); }); var pr2 = pr1.Select(row => new IntDouble(row.first,0.85 * row.second)); pr = pr2.Select(row => new IntDouble(row.first,0.15 + row.second)); } int minThreadId = computation.Configuration.ProcessID * computation.Configuration.WorkerCount; StreamWriter[] file_pr = new StreamWriter[computation.Configuration.WorkerCount]; for (int i = 0; i < computation.Configuration.WorkerCount; ++i) { int j = minThreadId + i; file_pr[i] = new StreamWriter(args[2] + "/pagerank_" + args[1] + j + ".out"); } pr.Subscribe((i, l) => { foreach (var element in l) file_pr[i - minThreadId].WriteLine(element); }); computation.Activate(); edges_input.OnCompleted(args[2] + "/pagerank_" + args[1] + "_edges" + computation.Configuration.ProcessID + ".in"); pr_input.OnCompleted(args[2] + "/pagerank_" + args[1] + "_vertices" + computation.Configuration.ProcessID + ".in"); computation.Join(); for (int i = 0; i < computation.Configuration.WorkerCount; ++i) { file_pr[i].Close(); } } } public string Help { get { return "PageRank <graph> <local path prefix>"; } } } }
{ "content_hash": "6f0a9f78fee4a12d54f2858206919bb7", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 155, "avg_line_length": 30.768683274021353, "alnum_prop": 0.5825815405968078, "repo_name": "ms705/Naiad", "id": "deebb9176733aaf3214d217933bd9066ecd8322b", "size": "8646", "binary": false, "copies": "1", "ref": "refs/heads/release_0.5", "path": "Examples/Naiad/PageRank.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "2037350" }, { "name": "PowerShell", "bytes": "11092" }, { "name": "Shell", "bytes": "536" } ], "symlink_target": "" }
Source = \ alarmsI.cpp \ platformConfigI.cpp \ sessionI.cpp \ ClientAgent.cpp \ LocalCppOptions = IncludeDirs = \ /usr/include \ ${COMPILER_VERSION} \ ${ACE_ROOT} \ ${TAO_ROOT} \ ${TAO_ROOT}/orbsvcs \ LibraryDirs = \ /usr/lib \ ${ACE_ROOT}/ace \ ${ACE_ROOT}/lib \ ${DB_ROOT}/lib \ Libraries = \ pq \ pgtypes \ ACE \ ACE_RMCast \ TAO \ TAO_CosLifeCycle \ TAO_CosNaming \ TAO_IORInterceptor \ TAO_IORTable \ TAO_Messaging \ TAO_ObjRefTemplate \ TAO_PortableServer \ TAO_Svc_Utils \ TAO_Valuetype \ TAO_Utils \ emsidlscppsource \ platformutilities \ platformdatamgr \ platformlogger \ platformthreadmgr \ platformmsgmgr \ platformmessages \ platformopm \ Main = ClientAgent include $(DEV_ROOT)/make/Makefile
{ "content_hash": "80178362227f119fd5c66209011c91be", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 33, "avg_line_length": 16.163265306122447, "alnum_prop": 0.6439393939393939, "repo_name": "shorton3/dashingplatforms", "id": "da0fe223a939c55f390f002a21830ae2eed56b65", "size": "792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ems/clientagent/Makefile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "28256" }, { "name": "C++", "bytes": "2094215" }, { "name": "CSS", "bytes": "2445" }, { "name": "HTML", "bytes": "32772" }, { "name": "Java", "bytes": "112848" }, { "name": "Makefile", "bytes": "33095" }, { "name": "Shell", "bytes": "8603" } ], "symlink_target": "" }
<head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>{{ page.title | strip_html }} - Free tutorial to learn HTML and CSS</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui"> <meta property="og:type" content="website"> <meta property="og:url" content="http://marksheet.io"> <meta property="og:title" content="A free tutorial to learn HTML and CSS"> <meta property="og:description" content="MarkSheet is a free tutorial to learn HTML and CSS. It's short (just as long as a 50 page book), simple (for everyone: beginners, designers, developers), and free (as in 'free beer' and 'free speech'). It consists of 50 lessons across 4 chapters, covering the Web, HTML5, CSS3, and Sass."> <meta property="og:site_name" content="MarkSheet"> <meta property="og:image" content="http://marksheet.io/images/marksheet-facebook.png"> <meta property="fb:app_id" content="470761896424893"> <link rel="icon" href="/favicon.ico"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://trycodehub.github.io/CodeHubAndroid/css/main.css"> <!--[if IE]> <link rel="stylesheet" type="text/css" href="/css/ie.css" /> <![endif]--> </head>
{ "content_hash": "20460d4201f6c15c1c015ba732e9fa71", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 332, "avg_line_length": 71.10526315789474, "alnum_prop": 0.7061435973353072, "repo_name": "TryCodeHub/CodeHubAndroid", "id": "9efad824341119f045ec8f17e4ef7680f9e60fc5", "size": "1351", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "_includes/head.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34758" }, { "name": "HTML", "bytes": "26222" }, { "name": "JavaScript", "bytes": "419487" } ], "symlink_target": "" }
package org.usfirst.frc.team236.robot; import org.usfirst.frc.team236.robot.commands.ShiftDown; import org.usfirst.frc.team236.robot.commands.ShootCycle; import org.usfirst.frc.team236.robot.commands.autonomous.AutoShoot; import org.usfirst.frc.team236.robot.commands.autonomous.BackwardRawtonomous; import org.usfirst.frc.team236.robot.commands.autonomous.DoNothing; import org.usfirst.frc.team236.robot.commands.autonomous.ForwardRawtonomous; import org.usfirst.frc.team236.robot.commands.autonomous.LowBarRawtonomous; import org.usfirst.frc.team236.robot.commands.profiled.CrossLowBar; import org.usfirst.frc.team236.robot.commands.profiled.Reach; import org.usfirst.frc.team236.robot.subsystems.Arm; import org.usfirst.frc.team236.robot.subsystems.Drive; import org.usfirst.frc.team236.robot.subsystems.Hanger; import org.usfirst.frc.team236.robot.subsystems.Intake; import org.usfirst.frc.team236.robot.subsystems.Shooter; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.vision.USBCamera; import motionProfile.Profile; import updater.Updater; public class Robot extends IterativeRobot { // Subsystems public static Drive drive; public static Intake intake; public static Arm arm; public static Shooter shooter; public static Hanger hanger; public static OI oi; Command autonomousCommand; SendableChooser chooser; CameraServer server; USBCamera camera; Compressor compressor; public static AHRS navx; // Profiles public Profile crossLowBar; public Profile reach; public Profile toShoot; public Profile toLowGoal; public Profile bigCross; public void robotInit() { // Create subsystems drive = new Drive(); intake = new Intake(); arm = new Arm(); shooter = new Shooter(); hanger = new Hanger(); oi = new OI(); // Create motion profiles crossLowBar = new Profile(AutoMap.crossLowBar); reach = new Profile(AutoMap.reach); toShoot = new Profile(AutoMap.toShoot); toLowGoal = new Profile(AutoMap.toLowGoal); // Pick an auto chooser = new SendableChooser(); chooser.addDefault("Do Nothing", new DoNothing()); chooser.addObject("Low Bar", new LowBarRawtonomous()); chooser.addObject("Low Bar (profile)", new CrossLowBar(crossLowBar)); chooser.addObject("Reach", new Reach(reach)); chooser.addObject("Forward Rawto", new ForwardRawtonomous()); chooser.addObject("Backward Rawto", new BackwardRawtonomous()); chooser.addObject("Shoot", new AutoShoot()); SmartDashboard.putData("Auto mode", chooser); // Start camera stream camera = new USBCamera(); server = CameraServer.getInstance(); server.setQuality(40); server.startAutomaticCapture(camera); // Start compressor compressor = new Compressor(); compressor.start(); navx = new AHRS(SPI.Port.kMXP); } public void disabledInit() { SmartDashboard.putData("Auto mode", chooser); } public void disabledPeriodic() { Scheduler.getInstance().run(); if (arm.getBottomLimit()) { arm.zeroEncoder(); } SmartDashboard.putNumber("Left", drive.getLeftDistance()); SmartDashboard.putNumber("Right", drive.getRightDistance()); } public void autonomousInit() { drive.zeroEncoders(); arm.setSetpointRelative(0); autonomousCommand = ((Command) chooser.getSelected()); if (autonomousCommand != null) { autonomousCommand.start(); } Updater.getInstance().initControllers(); } public void autonomousPeriodic() { Scheduler.getInstance().run(); Updater.getInstance().updateAll(); SmartDashboard.putNumber("Velocity", drive.leftSide.getSpeed()); SmartDashboard.putNumber("Left", drive.getLeftDistance()); SmartDashboard.putNumber("Right", drive.getRightDistance()); SmartDashboard.putNumber("Arm angle", arm.getRawEncoder()); } public void teleopInit() { if (autonomousCommand != null) { autonomousCommand.cancel(); } drive.zeroEncoders(); arm.setSetpointRelative(0); } public void teleopPeriodic() { Scheduler.getInstance().run(); SmartDashboard.putNumber("Match Time", DriverStation.getInstance().getMatchTime()); SmartDashboard.putNumber("Arm angle", arm.getRawEncoder()); SmartDashboard.putNumber("Left", drive.getLeftDistance()); SmartDashboard.putNumber("Right", drive.getRightDistance()); SmartDashboard.putBoolean("Bottom Limit", arm.getBottomLimit()); SmartDashboard.putBoolean("Upper Limit", arm.getUpperLimit()); SmartDashboard.putNumber("Velocity", drive.leftSide.getSpeed()); SmartDashboard.putBoolean("Ball", intake.getLimit()); // Hackish way to shoot with both triggers if (oi.leftStick.getRawButton(1) && oi.rightStick.getRawButton(1)) { new ShootCycle().start(); } // Hackish way to ensure we end in low gear if (DriverStation.getInstance().getMatchTime() <= 1) { new ShiftDown().start(); } } public void testPeriodic() { } public void testInit() { arm.setSetpointRelative(0); LiveWindow.addActuator("Arm", "Arm", arm.getPIDController()); } }
{ "content_hash": "6e322c28947b325674f03a5f1425b839", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 84, "avg_line_length": 30.785310734463277, "alnum_prop": 0.7500458799779776, "repo_name": "Team236/2016-Robot", "id": "afcd9588345d29aeba21143a3394760cb9d504b9", "size": "5449", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/usfirst/frc/team236/robot/Robot.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "76559" } ], "symlink_target": "" }
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _keymaster = _interopRequireDefault(require("keymaster")); var _Store = _interopRequireDefault(require("./Store")); var _Header = _interopRequireDefault(require("./Header.react")); var _Footer = _interopRequireDefault(require("./Footer.react")); var _Constants = _interopRequireDefault(require("./Constants")); var _Bem = require("./Bem"); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var defaultKeyFilter = _keymaster["default"].filter; var Store = new _Store["default"](); var handleClose = function handleClose() { _keymaster["default"].deleteScope('react-popup'); _keymaster["default"].filter = defaultKeyFilter; Store.close(); }; var initialState = { id: null, title: null, buttons: null, content: null, visible: false, className: null, noOverlay: false, position: false, closeOnOutsideClick: true, onClose: function onClose() {}, onShow: function onShow() {} }; var Popup = /*#__PURE__*/function (_React$Component) { _inherits(Popup, _React$Component); var _super = _createSuper(Popup); function Popup(props) { var _this; _classCallCheck(this, Popup); _this = _super.call(this, props); initialState.closeOnOutsideClick = _this.props.closeOnOutsideClick; _this.state = initialState; _this.bound = { onShow: _this.onShow.bind(_assertThisInitialized(_this)), onClose: _this.onClose.bind(_assertThisInitialized(_this)), onRefresh: _this.onRefresh.bind(_assertThisInitialized(_this)), containerClick: _this.containerClick.bind(_assertThisInitialized(_this)), handleButtonClick: _this.handleButtonClick.bind(_assertThisInitialized(_this)) }; _this.boxRef = null; _this.defaultKeyBindings = { ok: _this.props.defaultOkKey, cancel: _this.props.defaultCancelKey }; return _this; } _createClass(Popup, [{ key: "componentDidMount", value: function componentDidMount() { Store.on(_Constants["default"].SHOW, this.bound.onShow); Store.on(_Constants["default"].CLOSE, this.bound.onClose); Store.on(_Constants["default"].REFRESH, this.bound.onRefresh); } }, { key: "componentDidUpdate", value: function componentDidUpdate() { if (this.boxRef) { this.boxRef.focus(); } this.setPosition(this.state.position); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { Store.removeListener(_Constants["default"].SHOW, this.bound.onShow); Store.removeListener(_Constants["default"].CLOSE, this.bound.onClose); Store.removeListener(_Constants["default"].REFRESH, this.bound.onRefresh); _keymaster["default"].deleteScope('react-popup'); _keymaster["default"].filter = defaultKeyFilter; } /** * Refresh popup position * @param position * @private */ }, { key: "onRefresh", value: function onRefresh(position) { this.setPosition(position); } /** * On popup close * @private */ }, { key: "onClose", value: function onClose() { _keymaster["default"].deleteScope('react-popup'); _keymaster["default"].filter = defaultKeyFilter; this.state.onClose(this.state.id, this.state.title); this.setState(initialState); } /** * On popup show * @private */ }, { key: "onShow", value: function onShow(id) { var _this2 = this; _keymaster["default"].deleteScope('react-popup'); _keymaster["default"].filter = function () { return true; }; var popup = Store.activePopup(); if (popup.buttons && !Object.prototype.hasOwnProperty.call(popup.buttons, 'left')) { popup.buttons.left = []; } if (popup.buttons && !Object.prototype.hasOwnProperty.call(popup.buttons, 'right')) { popup.buttons.right = []; } this.setState({ id: id, title: popup.title, content: popup.content, buttons: popup.buttons, visible: true, className: popup.className, noOverlay: popup.noOverlay, position: popup.position, closeOnOutsideClick: popup.closeOnOutsideClick, onClose: popup.onClose, onShow: popup.onShow }, function () { _keymaster["default"].setScope('react-popup'); _this2.state.onShow(_this2.state.id, _this2.state.title); if (_this2.props.escToClose) { (0, _keymaster["default"])('esc', 'react-popup', _this2.handleKeyEvent.bind(_this2, 'cancel', _this2.state.id)); } if (_this2.state.buttons) { if (_this2.state.buttons.left.length) { _this2.state.buttons.left.forEach(function (button) { return _this2.bindKeyEvents(button); }); } if (_this2.state.buttons.right.length) { _this2.state.buttons.right.forEach(function (button) { return _this2.bindKeyEvents(button); }); } } }); } }, { key: "setPosition", value: function setPosition(position) { var box = this.boxRef; var boxPosition = position; if (!box) { return; } if (!boxPosition) { boxPosition = this.state.position; } if (!boxPosition) { box.style.opacity = 1; box.style.top = null; box.style.left = null; box.style.margin = null; return; } if (typeof boxPosition === 'function') { boxPosition.call(null, box); return; } box.style.top = "".concat(parseInt(boxPosition.y, 10), "px"); box.style.left = "".concat(parseInt(boxPosition.x, 10), "px"); box.style.margin = 0; box.style.opacity = 1; } /** * Handle container click * @param e * @private */ }, { key: "containerClick", value: function containerClick() { if (this.state.closeOnOutsideClick) { handleClose(); } } }, { key: "bindKeyEvents", value: function bindKeyEvents(button) { var code = null; if (typeof button === 'string') { code = this.defaultKeyBindings[button]; } else if (Object.prototype.hasOwnProperty.call(button, 'key')) { code = button.key; } if (this.props.escToClose && code === 'esc') { return; } if (code) { (0, _keymaster["default"])(code, 'react-popup', this.handleKeyEvent.bind(this, button, this.state.id)); } } }, { key: "handleKeyEvent", value: function handleKeyEvent(button, id, e) { var excludeTags = ['INPUT', 'TEXTAREA', 'BUTTON']; if (this.state.id !== id || button.key === 'enter' && excludeTags.indexOf(e.target.tagName) >= 0) { return true; } if (typeof button === 'string') { handleClose(); } else if (Object.prototype.hasOwnProperty.call(button, 'action')) { this.handleButtonClick(button.action); } return false; } /** * Handle button clicks * @param action * @returns {*} * @private */ }, { key: "handleButtonClick", value: function handleButtonClick(action) { if (typeof action === 'function') { return action.call(this, Store); } return null; } }, { key: "className", value: function className(_className) { return (0, _Bem.element)(_className, this.props.className); } }, { key: "render", value: function render() { var _this3 = this; var className = this.props.className; var box = null; var overlayStyle = {}; if (this.state.visible) { var closeBtn = null; className += " ".concat(this.props.className, "--visible"); if (this.props.closeBtn) { closeBtn = /*#__PURE__*/(0, _jsxRuntime.jsx)("button", { onClick: handleClose, className: "".concat(this.props.className, "__close"), children: this.props.closeHtml }); } var boxClass = this.className('box'); if (this.state.className) { boxClass += " ".concat((0, _Bem.modifier)(this.state.className, boxClass)); } box = /*#__PURE__*/(0, _jsxRuntime.jsxs)("article", { role: "dialog", tabIndex: "-1", ref: function ref(el) { _this3.boxRef = el; }, style: { opacity: 0, outline: 'none' }, className: boxClass, children: [closeBtn, /*#__PURE__*/(0, _jsxRuntime.jsx)(_Header["default"], { title: this.state.title, className: this.className('box__header') }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { className: this.className('box__body'), children: this.state.content }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Footer["default"], { className: this.className('box__footer'), btnClass: this.props.btnClass, buttonClick: this.bound.handleButtonClick, onClose: handleClose, onOk: handleClose, defaultOk: this.props.defaultOk, defaultCancel: this.props.defaultCancel, buttons: this.state.buttons })] }); } if (this.state.noOverlay) { overlayStyle.background = 'transparent'; } return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", { className: className, children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", { role: "presentation", onClick: this.bound.containerClick, className: this.className('overlay'), style: overlayStyle }), box] }); } }], [{ key: "addShowListener", value: function addShowListener(callback) { Store.on(_Constants["default"].SHOW, callback); } }, { key: "removeShowListener", value: function removeShowListener(callback) { Store.removeListener(_Constants["default"].SHOW, callback); } }, { key: "addCloseListener", value: function addCloseListener(callback) { Store.on(_Constants["default"].CLOSE, callback); } }, { key: "removeCloseListener", value: function removeCloseListener(callback) { Store.removeListener(_Constants["default"].CLOSE, callback); } }, { key: "register", value: function register(data) { var id = Store.getId(); Store.popups[id] = Object.assign({}, initialState, data); return id; } }, { key: "queue", value: function queue(id) { if (!Object.prototype.hasOwnProperty.call(Store.popups, id)) { return false; } /** Add popup to queue */ Store.queue.push(id); /** Dispatch queue */ Store.dispatch(); return id; } }, { key: "create", value: function create(data, bringToFront) { /** Register popup */ var id = this.register(data); /** Queue popup */ if (bringToFront === true) { var currentlyActive = Store.active; Store.active = null; this.queue(id); this.queue(currentlyActive); Store.dispatch(); } else { this.queue(id); } return id; } }, { key: "alert", value: function alert(text, title, bringToFront) { var data = { title: title, content: text, buttons: { right: ['ok'] } }; return this.create(data, bringToFront); } }, { key: "close", value: function close() { Store.close(); } }, { key: "registerPlugin", value: function registerPlugin(name, callback) { Store.plugins[name] = callback.bind(this); } }, { key: "plugins", value: function plugins() { return Store.plugins; } }, { key: "refreshPosition", value: function refreshPosition(position) { return Store.refreshPosition(position); } }, { key: "clearQueue", value: function clearQueue() { return Store.clearQueue(); } }]); return Popup; }(_react["default"].Component); _defineProperty(Popup, "defaultProps", { className: 'mm-popup', btnClass: 'mm-popup__btn', closeBtn: true, closeHtml: null, defaultOk: 'Ok', defaultOkKey: 'enter', defaultCancel: 'Cancel', defaultCancelKey: 'esc', closeOnOutsideClick: true, escToClose: true, onClose: function onClose() {}, onShow: function onShow() {} }); Popup.propTypes = { className: _propTypes["default"].string, btnClass: _propTypes["default"].string, closeBtn: _propTypes["default"].bool, closeHtml: _propTypes["default"].node, defaultOk: _propTypes["default"].string, defaultOkKey: _propTypes["default"].string, defaultCancel: _propTypes["default"].string, defaultCancelKey: _propTypes["default"].string, closeOnOutsideClick: _propTypes["default"].bool, escToClose: _propTypes["default"].bool, onClose: _propTypes["default"].func, onShow: _propTypes["default"].func }; var _default = Popup; exports["default"] = _default;
{ "content_hash": "b3cb7127195025bc7368e2bdaddcd6dc", "timestamp": "", "source": "github", "line_count": 524, "max_line_length": 452, "avg_line_length": 32.00954198473283, "alnum_prop": 0.6119358492815835, "repo_name": "minutemailer/react-popup", "id": "f20f47c609ccc9e69fdbf261ed8c1ac19a585a66", "size": "16773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/Popup.react.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9351" }, { "name": "HTML", "bytes": "403" }, { "name": "JavaScript", "bytes": "21852" } ], "symlink_target": "" }
package com.demigodsrpg.chitchat.util; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; public class ClassPathHack { private static final Class[] parameters = new Class[]{URL.class}; private ClassPathHack() { } public static void addFile(File f, URLClassLoader cL) throws IOException { addURL(f.toURI().toURL(), cL); } @SuppressWarnings({"unchecked", "RedundantArrayCreation"}) public static void addURL(URL u, URLClassLoader cL) throws IOException { Class urlClassLoader = URLClassLoader.class; try { Method method = urlClassLoader.getDeclaredMethod("addURL", parameters); method.setAccessible(true); method.invoke(cL, new Object[]{u}); } catch (Throwable t) { t.printStackTrace(); throw new IOException("Error, could not add URL to system classloader"); } } }
{ "content_hash": "36f5e0f44c43da47a3db1849f6aee92e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 84, "avg_line_length": 29.90909090909091, "alnum_prop": 0.6646403242147924, "repo_name": "DemigodsRPG/Chitchat", "id": "fbb96b68426e93cbd2a683fdb9b974875bd4a1de", "size": "1643", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/demigodsrpg/chitchat/util/ClassPathHack.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "65890" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Thu Nov 13 21:22:01 UTC 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.yarn.api.records.ReservationId (Apache Hadoop Main 2.6.0 API) </TITLE> <META NAME="date" CONTENT="2014-11-13"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.yarn.api.records.ReservationId (Apache Hadoop Main 2.6.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/yarn/api/records//class-useReservationId.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ReservationId.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.yarn.api.records.ReservationId</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.mapreduce"><B>org.apache.hadoop.mapreduce</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.yarn.api.protocolrecords"><B>org.apache.hadoop.yarn.api.protocolrecords</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.yarn.api.records"><B>org.apache.hadoop.yarn.api.records</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.mapreduce"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A> in <A HREF="../../../../../../../org/apache/hadoop/mapreduce/package-summary.html">org.apache.hadoop.mapreduce</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/mapreduce/package-summary.html">org.apache.hadoop.mapreduce</A> that return <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></CODE></FONT></TD> <TD><CODE><B>Job.</B><B><A HREF="../../../../../../../org/apache/hadoop/mapreduce/Job.html#getReservationId()">getReservationId</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the reservation to which the job is submitted to, if any</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/mapreduce/package-summary.html">org.apache.hadoop.mapreduce</A> with parameters of type <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>Job.</B><B><A HREF="../../../../../../../org/apache/hadoop/mapreduce/Job.html#setReservationId(org.apache.hadoop.yarn.api.records.ReservationId)">setReservationId</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set the reservation to which the job is submitted to</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.yarn.api.protocolrecords"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A> in <A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/package-summary.html">org.apache.hadoop.yarn.api.protocolrecords</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/package-summary.html">org.apache.hadoop.yarn.api.protocolrecords</A> that return <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></CODE></FONT></TD> <TD><CODE><B>ReservationDeleteRequest.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationDeleteRequest.html#getReservationId()">getReservationId</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><CODE>ReservationId</CODE></A>, that corresponds to a valid resource allocation in the scheduler (between start and end time of this reservation)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></CODE></FONT></TD> <TD><CODE><B>ReservationSubmissionResponse.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationSubmissionResponse.html#getReservationId()">getReservationId</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><CODE>ReservationId</CODE></A>, that corresponds to a valid resource allocation in the scheduler (between start and end time of this reservation)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></CODE></FONT></TD> <TD><CODE><B>ReservationUpdateRequest.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationUpdateRequest.html#getReservationId()">getReservationId</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><CODE>ReservationId</CODE></A>, that corresponds to a valid resource allocation in the scheduler (between start and end time of this reservation)</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/package-summary.html">org.apache.hadoop.yarn.api.protocolrecords</A> with parameters of type <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationUpdateRequest.html" title="class in org.apache.hadoop.yarn.api.protocolrecords">ReservationUpdateRequest</A></CODE></FONT></TD> <TD><CODE><B>ReservationUpdateRequest.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationUpdateRequest.html#newInstance(org.apache.hadoop.yarn.api.records.ReservationDefinition, org.apache.hadoop.yarn.api.records.ReservationId)">newInstance</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationDefinition.html" title="class in org.apache.hadoop.yarn.api.records">ReservationDefinition</A>&nbsp;reservationDefinition, <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationDeleteRequest.html" title="class in org.apache.hadoop.yarn.api.protocolrecords">ReservationDeleteRequest</A></CODE></FONT></TD> <TD><CODE><B>ReservationDeleteRequest.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationDeleteRequest.html#newInstance(org.apache.hadoop.yarn.api.records.ReservationId)">newInstance</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationSubmissionResponse.html" title="class in org.apache.hadoop.yarn.api.protocolrecords">ReservationSubmissionResponse</A></CODE></FONT></TD> <TD><CODE><B>ReservationSubmissionResponse.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationSubmissionResponse.html#newInstance(org.apache.hadoop.yarn.api.records.ReservationId)">newInstance</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;void</CODE></FONT></TD> <TD><CODE><B>ReservationDeleteRequest.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationDeleteRequest.html#setReservationId(org.apache.hadoop.yarn.api.records.ReservationId)">setReservationId</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set the <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><CODE>ReservationId</CODE></A>, that correspond to a valid resource allocation in the scheduler (between start and end time of this reservation)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;void</CODE></FONT></TD> <TD><CODE><B>ReservationSubmissionResponse.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationSubmissionResponse.html#setReservationId(org.apache.hadoop.yarn.api.records.ReservationId)">setReservationId</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set the <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><CODE>ReservationId</CODE></A>, that correspond to a valid resource allocation in the scheduler (between start and end time of this reservation)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;void</CODE></FONT></TD> <TD><CODE><B>ReservationUpdateRequest.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/protocolrecords/ReservationUpdateRequest.html#setReservationId(org.apache.hadoop.yarn.api.records.ReservationId)">setReservationId</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set the <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><CODE>ReservationId</CODE></A>, that correspond to a valid resource allocation in the scheduler (between start and end time of this reservation)</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.yarn.api.records"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A> in <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/package-summary.html">org.apache.hadoop.yarn.api.records</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/package-summary.html">org.apache.hadoop.yarn.api.records</A> that return <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></CODE></FONT></TD> <TD><CODE><B>ApplicationSubmissionContext.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ApplicationSubmissionContext.html#getReservationID()">getReservationID</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get the reservation id, that corresponds to a valid resource allocation in the scheduler (between start and end time of the corresponding reservation)</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></CODE></FONT></TD> <TD><CODE><B>ReservationId.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html#newInstance(long, long)">newInstance</A></B>(long&nbsp;clusterTimestamp, long&nbsp;id)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></CODE></FONT></TD> <TD><CODE><B>ReservationId.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html#parseReservationId(java.lang.String)">parseReservationId</A></B>(<A HREF="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;reservationId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Parse the string argument as a <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><CODE>ReservationId</CODE></A></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/package-summary.html">org.apache.hadoop.yarn.api.records</A> with parameters of type <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B>ReservationId.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html#compareTo(org.apache.hadoop.yarn.api.records.ReservationId)">compareTo</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;other)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>abstract &nbsp;void</CODE></FONT></TD> <TD><CODE><B>ApplicationSubmissionContext.</B><B><A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ApplicationSubmissionContext.html#setReservationID(org.apache.hadoop.yarn.api.records.ReservationId)">setReservationID</A></B>(<A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records">ReservationId</A>&nbsp;reservationID)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set the reservation id, that correspond to a valid resource allocation in the scheduler (between start and end time of the corresponding reservation)</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/yarn/api/records/ReservationId.html" title="class in org.apache.hadoop.yarn.api.records"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/yarn/api/records//class-useReservationId.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ReservationId.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "d2e6e75cabc821dd90f9ac2fa0cfb573", "timestamp": "", "source": "github", "line_count": 383, "max_line_length": 487, "avg_line_length": 65.2219321148825, "alnum_prop": 0.6676941553242594, "repo_name": "gsoundar/mambo-ec2-deploy", "id": "2042da3fa5c52b7738c41fb7e58ddc84c0999d99", "size": "24980", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/hadoop-2.6.0/share/doc/hadoop/api/org/apache/hadoop/yarn/api/records/class-use/ReservationId.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23179" }, { "name": "CSS", "bytes": "39965" }, { "name": "HTML", "bytes": "263271260" }, { "name": "Java", "bytes": "103085" }, { "name": "JavaScript", "bytes": "1347" }, { "name": "Python", "bytes": "4101" }, { "name": "Ruby", "bytes": "262588" }, { "name": "Shell", "bytes": "118548" } ], "symlink_target": "" }
package org.cobbzilla.wizard.client.script; import org.cobbzilla.wizard.util.RestResponse; import java.util.Map; public interface ApiRunnerListener { String getName(); ApiRunner getApiRunner(); void setApiRunner(ApiRunner runner); default void setCtxVars(Map<String, Object> ctx) {} void beforeScript(String before, Map<String, Object> ctx) throws Exception; void afterScript(String after, Map<String, Object> ctx) throws Exception; void beforeCall(ApiScript script, Map<String, Object> ctx); void afterCall(ApiScript script, Map<String, Object> ctx, RestResponse response); void statusCheckFailed(ApiScript script, String uri, RestResponse restResponse); void conditionCheckFailed(String message, ApiScript script, RestResponse restResponse, ApiScriptResponseCheck check, Map<String, Object> ctx); void sessionIdNotFound(ApiScript script, RestResponse restResponse); void scriptCompleted(ApiScript script); void scriptTimedOut(ApiScript script); void unexpectedResponse(ApiScript script, RestResponse restResponse); boolean skipCheck(ApiScript script, ApiScriptResponseCheck check); }
{ "content_hash": "e858ef10e74154a027fb3aed7bf91243", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 120, "avg_line_length": 35.96969696969697, "alnum_prop": 0.7573715248525695, "repo_name": "cobbzilla/cobbzilla-wizard", "id": "2a3a2c6adb376e7494ddfdd9a5024bbab9bef5dd", "size": "1187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wizard-common/src/main/java/org/cobbzilla/wizard/client/script/ApiRunnerListener.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Handlebars", "bytes": "1168" }, { "name": "Java", "bytes": "1130683" }, { "name": "Lua", "bytes": "1246" }, { "name": "Thrift", "bytes": "279" } ], "symlink_target": "" }
declare const gT: import('../tia-types').GlobalTiaObjects; gT.t.setTitle('TypeScript testcase test');
{ "content_hash": "e24ef1f54c1474065191a24cae4f8d7c", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 58, "avg_line_length": 34.333333333333336, "alnum_prop": 0.7475728155339806, "repo_name": "Dzenly/tia", "id": "38f9affede84711d03b7187101825524f04ab424", "size": "103", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/testsDir/testsSubDir/__tia-tests__/tia/10_ts/00_just-ts-test.tia.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4322" }, { "name": "JavaScript", "bytes": "59313" }, { "name": "Shell", "bytes": "2840" }, { "name": "TypeScript", "bytes": "275611" } ], "symlink_target": "" }
**WHAT:** This is an example of Bob Nystrom's "[Baby's First Garbage Collector](http://journal.stuffwithstuff.com/2013/12/08/babys-first-garbage-collector/)," which I've been wanting to implement for a while in order to understand it better. To make the problem harder (as I always do), I decided to write it in C++, and to make it even more fun, I've implemented it using the new Variant container from C++17. **WHY:** I've never written a garbage collector before. Now I know what it is and how it works. **REQURIEMENTS:** This code has been tested with gcc-7.3, and should work on any C++17-compliant compiler with the relevant standard library. Unlike the previous edition, it has not been tested with Clang. **STATUS:** **December 30, 2016:** This project is **complete.** No new features are being considered. **DETAILS:** The collector Nystrom wrote is a simple bi-color mark-and-sweep collector for a singly threaded process with distinct pauses based upon a straightforward memory usage heuristic. That heuristic is simply, "Is the amount of memory currently in use twice as much as the last time we garbage collected?" If the answer is yes, the collector runs and sweeps up the stack. Nystrom's code is highly readable, and I hope mine is as well. Because I used Variant, my Object class has an internal Pair class, and then the Variant is just \<int, Pair\>, where "Pair" is a pair of pointers to other objects. The entirety of the VM is basically a stack of singly-linked lists which either represents integers or collections of integers in a Lisp-like structure. The allocator creates two kinds of objects, then: pairs, and lists. A pair is created by pushing two other objects onto the stack, then calling `push()`, which pops them off the stack and replaces them with a Pair object. The VM class has two methods, both named `push()`, one of which pushes an integer, the other a pair. Since a pair is built from objects on the stack, the Pair version takes no arguments, and since C++14 and beyond have move semantics that Variant honors, Variant\<Pair\> only constructs a single pair. Pretty nice. I was also able to use both lambda-style and constructor-style visitors in my Variant, which was a fun little bonus. In the end, this becomes a pair of linked lists with different roots; one pair can orphan the lists, the other can't. We traverse up the spine of the stack, following each scope's list and marking the objects as found. We then traverse the other list and, for every object not marked, we get a pointer to it, collapse the list around it, and delete it. Very simple and elegant. I hope, eventually, to move onto tri-color, multi-threaded garbage collectors someday. According to Nystrom, *this* garbage collector is the actual algorithm used in early versions of Lua, so it's not a toy. **NOTE:** The previous edition of this project used the MapBox variant class (https://github.com/mapbox/variant). As of the stabilization of C++-17, the standard library's variant class works fine with the existing code. **BUILDING:** From the base directory of the project: mkdir build cd build cmake .. make And you should be able to run the basic tests. It's just one file. Unfortunately, I was simpleminded with the include paths, so it can't be built anywhere but from the base directory without fiddling with the `CMakeLists.txt` file.
{ "content_hash": "e2d33fd13ce21d42231706c4cb562a03", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 112, "avg_line_length": 41.59756097560975, "alnum_prop": 0.7622398123717385, "repo_name": "elfsternberg/SimpleGarbageCollector", "id": "420906c50a87cd9863c4e48f1288b923cf8fd3c7", "size": "3411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "43682" }, { "name": "CMake", "bytes": "150" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd"> <changeSet id="add-data-cleansing-step-type" author="ricci" dbms="postgresql"> <comment>Add data cleansing step type column</comment> <addColumn tableName="ofc_data_cleansing_step"> <column name="type" type="char" defaultValue="a" /> </addColumn> </changeSet> <changeSet id="add-record-application-version" author="ricci" dbms="postgresql"> <comment>Add record application version column</comment> <addColumn tableName="ofc_record"> <column name="app_version" type="varchar(63)" defaultValue="3.9.0" /> </addColumn> </changeSet> </databaseChangeLog>
{ "content_hash": "d3e79e8447f14e095f42a536263e3bd7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 131, "avg_line_length": 39.625, "alnum_prop": 0.6729758149316509, "repo_name": "openforis/collect", "id": "d161bcd867815868a50e4f326f3e1de4f63ace7b", "size": "951", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "collect-core/src/main/resources/org/openforis/collect/db/changelog/postgresql/db.changelog-20160825.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2032" }, { "name": "CSS", "bytes": "492878" }, { "name": "HTML", "bytes": "55093" }, { "name": "Java", "bytes": "6027874" }, { "name": "JavaScript", "bytes": "5049757" }, { "name": "Less", "bytes": "60736" }, { "name": "SCSS", "bytes": "310370" }, { "name": "Shell", "bytes": "515" }, { "name": "TSQL", "bytes": "1199" }, { "name": "XSLT", "bytes": "8150" } ], "symlink_target": "" }
<?php global $lang; $lang['en_US']['Page']['PLURALNAME'] = array( 'Pags', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Page']['SINGULARNAME'] = array( 'Page', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['AdvancedSearchForm']['ALLWORDS'] = 'All Words'; $lang['en_US']['AdvancedSearchForm']['ATLEAST'] = 'At Least One Of the Words'; $lang['en_US']['AdvancedSearchForm']['EXACT'] = 'Exact Phrase'; $lang['en_US']['AdvancedSearchForm']['FROM'] = 'From'; $lang['en_US']['AdvancedSearchForm']['GO'] = 'Go'; $lang['en_US']['AdvancedSearchForm']['LASTUPDATED'] = 'Last Updated'; $lang['en_US']['AdvancedSearchForm']['LASTUPDATEDHEADER'] = 'LAST UPDATED'; $lang['en_US']['AdvancedSearchForm']['PAGETITLE'] = 'Page Title'; $lang['en_US']['AdvancedSearchForm']['RELEVANCE'] = 'Relevance'; $lang['en_US']['AdvancedSearchForm']['SEARCHBY'] = 'SEARCH BY'; $lang['en_US']['AdvancedSearchForm']['SORTBY'] = 'SORT RESULTS BY'; $lang['en_US']['AdvancedSearchForm']['TO'] = 'To'; $lang['en_US']['AdvancedSearchForm']['WITHOUT'] = 'Without the Words'; $lang['en_US']['AssetAdmin']['CHOOSEFILE'] = 'Choose file: '; $lang['en_US']['BBCodeParser']['ALIGNEMENT'] = 'Alignment'; $lang['en_US']['BBCodeParser']['ALIGNEMENTEXAMPLE'] = 'right aligned'; $lang['en_US']['BBCodeParser']['BOLD'] = 'Bold Text'; $lang['en_US']['BBCodeParser']['BOLDEXAMPLE'] = 'Bold'; $lang['en_US']['BBCodeParser']['CODE'] = 'Code Block'; $lang['en_US']['BBCodeParser']['CODEDESCRIPTION'] = 'Unformatted code block'; $lang['en_US']['BBCodeParser']['CODEEXAMPLE'] = 'Code block'; $lang['en_US']['BBCodeParser']['COLORED'] = 'Colored text'; $lang['en_US']['BBCodeParser']['COLOREDEXAMPLE'] = 'blue text'; $lang['en_US']['BBCodeParser']['EMAILLINK'] = 'Email link'; $lang['en_US']['BBCodeParser']['EMAILLINKDESCRIPTION'] = 'Create link to an email address'; $lang['en_US']['BBCodeParser']['IMAGE'] = 'Image'; $lang['en_US']['BBCodeParser']['IMAGEDESCRIPTION'] = 'Show an image in your post'; $lang['en_US']['BBCodeParser']['ITALIC'] = 'Italic Text'; $lang['en_US']['BBCodeParser']['ITALICEXAMPLE'] = 'Italics'; $lang['en_US']['BBCodeParser']['LINK'] = 'Website link'; $lang['en_US']['BBCodeParser']['LINKDESCRIPTION'] = 'Link to another website or URL'; $lang['en_US']['BBCodeParser']['STRUCK'] = 'Struck-out Text'; $lang['en_US']['BBCodeParser']['STRUCKEXAMPLE'] = 'Struck-out'; $lang['en_US']['BBCodeParser']['UNDERLINE'] = 'Underlined Text'; $lang['en_US']['BBCodeParser']['UNDERLINEEXAMPLE'] = 'Underlined'; $lang['en_US']['BBCodeParser']['UNORDERED'] = 'Unordered list'; $lang['en_US']['BBCodeParser']['UNORDEREDDESCRIPTION'] = 'Unordered list'; $lang['en_US']['BBCodeParser']['UNORDEREDEXAMPLE1'] = 'unordered item 1'; $lang['en_US']['BasicAuth']['ENTERINFO'] = 'Please enter a username and password.'; $lang['en_US']['BasicAuth']['ERRORNOTADMIN'] = 'That user is not an administrator.'; $lang['en_US']['BasicAuth']['ERRORNOTREC'] = 'That username / password isn\'t recognised'; $lang['en_US']['Boolean']['ANY'] = 'Any'; $lang['en_US']['Boolean']['NO'] = 'No'; $lang['en_US']['Boolean']['YES'] = 'Yes'; $lang['en_US']['CMSMain']['DELETE'] = 'Delete from the draft site'; $lang['en_US']['CMSMain']['DELETEFP'] = 'Delete from the published site'; $lang['en_US']['CMSMain']['RESTORE'] = 'Restore'; $lang['en_US']['CMSMain']['SAVE'] = 'Save'; $lang['en_US']['ChangePasswordEmail.ss']['CHANGEPASSWORDTEXT1'] = array( 'You changed your password for', PR_MEDIUM, 'for a url' ); $lang['en_US']['ChangePasswordEmail.ss']['CHANGEPASSWORDTEXT2'] = 'You can now use the following credentials to log in:'; $lang['en_US']['ChangePasswordEmail.ss']['EMAIL'] = 'Email'; $lang['en_US']['ChangePasswordEmail.ss']['HELLO'] = 'Hi'; $lang['en_US']['ChangePasswordEmail.ss']['PASSWORD'] = 'Password'; $lang['en_US']['CheckboxField']['NO'] = 'No'; $lang['en_US']['CheckboxField']['YES'] = 'Yes'; $lang['en_US']['ComplexTableField']['CLOSEPOPUP'] = 'Close Popup'; $lang['en_US']['ComplexTableField']['SUCCESSADD'] = 'Added %s %s %s'; $lang['en_US']['ComplexTableField']['SUCCESSEDIT'] = 'Saved %s %s %s'; $lang['en_US']['ComplexTableField.ss']['ADDITEM'] = array( 'Add %s', PR_MEDIUM, 'Add [name]' ); $lang['en_US']['ComplexTableField.ss']['CSVEXPORT'] = 'Export to CSV'; $lang['en_US']['ComplexTableField.ss']['NOITEMSFOUND'] = 'No items found'; $lang['en_US']['ComplexTableField.ss']['SORTASC'] = 'Sort ascending'; $lang['en_US']['ComplexTableField.ss']['SORTDESC'] = 'Sort descending'; $lang['en_US']['ComplexTableField_popup.ss']['NEXT'] = 'Next'; $lang['en_US']['ComplexTableField_popup.ss']['PREVIOUS'] = 'Previous'; $lang['en_US']['ConfirmedPasswordField']['ATLEAST'] = 'Passwords must be at least %s characters long.'; $lang['en_US']['ConfirmedPasswordField']['BETWEEN'] = 'Passwords must be %s to %s characters long.'; $lang['en_US']['ConfirmedPasswordField']['HAVETOMATCH'] = 'Passwords have to match.'; $lang['en_US']['ConfirmedPasswordField']['LEASTONE'] = 'Passwords must have at least one digit and one alphanumeric character.'; $lang['en_US']['ConfirmedPasswordField']['MAXIMUM'] = 'Passwords must be at most %s characters long.'; $lang['en_US']['ConfirmedPasswordField']['NOEMPTY'] = 'Passwords can\'t be empty.'; $lang['en_US']['ConfirmedPasswordField']['SHOWONCLICKTITLE'] = array( 'Change Password', PR_MEDIUM, 'Label of the link which triggers display of the "change password" formfields' ); $lang['en_US']['ContentControl']['NOTEWONTBESHOWN'] = 'Note: this message will not be shown to your visitors'; $lang['en_US']['ContentController']['ARCHIVEDSITE'] = 'Archived Site'; $lang['en_US']['ContentController']['ARCHIVEDSITEFROM'] = 'Archived site from'; $lang['en_US']['ContentController']['CMS'] = 'CMS'; $lang['en_US']['ContentController']['DRAFTSITE'] = 'Draft Site'; $lang['en_US']['ContentController']['DRAFT_SITE_ACCESS_RESTRICTION'] = 'You must log in with your CMS password in order to view the draft or archived content. <a href="%s">Click here to go back to the published site.</a>'; $lang['en_US']['ContentController']['LOGGEDINAS'] = 'Logged in as'; $lang['en_US']['ContentController']['LOGIN'] = 'Login'; $lang['en_US']['ContentController']['LOGOUT'] = 'Log out'; $lang['en_US']['ContentController']['NOTLOGGEDIN'] = 'Not logged in'; $lang['en_US']['ContentController']['PUBLISHEDSITE'] = 'Published Site'; $lang['en_US']['ContentController']['VIEWPAGEIN'] = 'View Page in:'; $lang['en_US']['CreditCardField']['FIRST'] = 'first'; $lang['en_US']['CreditCardField']['FOURTH'] = 'fourth'; $lang['en_US']['CreditCardField']['SECOND'] = 'second'; $lang['en_US']['CreditCardField']['THIRD'] = 'third'; $lang['en_US']['CreditCardField']['VALIDATIONJS1'] = 'Please ensure you have entered the'; $lang['en_US']['CreditCardField']['VALIDATIONJS2'] = 'credit card number correctly.'; $lang['en_US']['CurrencyField']['CURRENCYSYMBOL'] = '$'; $lang['en_US']['CurrencyField']['VALIDATIONJS'] = 'Please enter a valid currency.'; $lang['en_US']['DataObject']['PLURALNAME'] = array( 'Data Objects', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['DataObject']['SINGULARNAME'] = array( 'Data Object', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Date']['DAY'] = ' day'; $lang['en_US']['Date']['DAYS'] = ' days'; $lang['en_US']['Date']['HOUR'] = ' hour'; $lang['en_US']['Date']['HOURS'] = ' hours'; $lang['en_US']['Date']['MIN'] = ' min'; $lang['en_US']['Date']['MINS'] = ' mins'; $lang['en_US']['Date']['MONTH'] = ' month'; $lang['en_US']['Date']['MONTHS'] = ' months'; $lang['en_US']['Date']['SEC'] = ' sec'; $lang['en_US']['Date']['SECS'] = ' secs'; $lang['en_US']['Date']['TIMEDIFFAGO'] = array( '%s ago', PR_MEDIUM, 'Natural language time difference, e.g. 2 hours ago' ); $lang['en_US']['Date']['TIMEDIFFAWAY'] = array( '%s away', PR_MEDIUM, 'Natural language time difference, e.g. 2 hours away' ); $lang['en_US']['Date']['YEAR'] = ' year'; $lang['en_US']['Date']['YEARS'] = ' years'; $lang['en_US']['DateField']['NOTSET'] = 'not set'; $lang['en_US']['DateField']['TODAY'] = 'today'; $lang['en_US']['DateField']['VALIDATIONJS'] = 'Please enter a valid date format.'; $lang['en_US']['DateField']['VALIDDATEFORMAT2'] = 'Please enter a valid date format (%s).'; $lang['en_US']['DateField']['VALIDDATEMAXDATE'] = 'Your date has to be older or matching the maximum allowed date (%s)'; $lang['en_US']['DateField']['VALIDDATEMINDATE'] = 'Your date has to be newer or matching the minimum allowed date (%s)'; $lang['en_US']['DropdownField']['CHOOSE'] = array( '(Choose)', PR_MEDIUM, 'start value of a dropdown' ); $lang['en_US']['EmailField']['VALIDATION'] = 'Please enter an email address.'; $lang['en_US']['EmailField']['VALIDATIONJS'] = 'Please enter an email address.'; $lang['en_US']['Email_BounceRecord']['PLURALNAME'] = array( 'Email Bounce Records', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Email_BounceRecord']['SINGULARNAME'] = array( 'Email Bounce Record', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Enum']['ANY'] = 'Any'; $lang['en_US']['ErrorPage']['400'] = '400 - Bad Request'; $lang['en_US']['ErrorPage']['401'] = '401 - Unauthorized'; $lang['en_US']['ErrorPage']['403'] = '403 - Forbidden'; $lang['en_US']['ErrorPage']['404'] = '404 - Not Found'; $lang['en_US']['ErrorPage']['405'] = '405 - Method Not Allowed'; $lang['en_US']['ErrorPage']['406'] = '406 - Not Acceptable'; $lang['en_US']['ErrorPage']['407'] = '407 - Proxy Authentication Required'; $lang['en_US']['ErrorPage']['408'] = '408 - Request Timeout'; $lang['en_US']['ErrorPage']['409'] = '409 - Conflict'; $lang['en_US']['ErrorPage']['410'] = '410 - Gone'; $lang['en_US']['ErrorPage']['411'] = '411 - Length Required'; $lang['en_US']['ErrorPage']['412'] = '412 - Precondition Failed'; $lang['en_US']['ErrorPage']['413'] = '413 - Request Entity Too Large'; $lang['en_US']['ErrorPage']['414'] = '414 - Request-URI Too Long'; $lang['en_US']['ErrorPage']['415'] = '415 - Unsupported Media Type'; $lang['en_US']['ErrorPage']['416'] = '416 - Request Range Not Satisfiable'; $lang['en_US']['ErrorPage']['417'] = '417 - Expectation Failed'; $lang['en_US']['ErrorPage']['500'] = '500 - Internal Server Error'; $lang['en_US']['ErrorPage']['501'] = '501 - Not Implemented'; $lang['en_US']['ErrorPage']['502'] = '502 - Bad Gateway'; $lang['en_US']['ErrorPage']['503'] = '503 - Service Unavailable'; $lang['en_US']['ErrorPage']['504'] = '504 - Gateway Timeout'; $lang['en_US']['ErrorPage']['505'] = '505 - HTTP Version Not Supported'; $lang['en_US']['ErrorPage']['CODE'] = 'Error code'; $lang['en_US']['ErrorPage']['DEFAULTERRORPAGECONTENT'] = '<p>Sorry, it seems you were trying to access a page that doesn\'t exist.</p><p>Please check the spelling of the URL you were trying to access and try again.</p>'; $lang['en_US']['ErrorPage']['DEFAULTERRORPAGETITLE'] = 'Page not found'; $lang['en_US']['ErrorPage']['DEFAULTSERVERERRORPAGECONTENT'] = '<p>Sorry, there was a problem with handling your request.</p>'; $lang['en_US']['ErrorPage']['DEFAULTSERVERERRORPAGETITLE'] = 'Server error'; $lang['en_US']['ErrorPage']['ERRORFILEPROBLEM'] = 'Error opening file "%s" for writing. Please check file permissions.'; $lang['en_US']['ErrorPage']['PLURALNAME'] = array( 'Error Pags', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['ErrorPage']['SINGULARNAME'] = array( 'Error Page', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['File']['Content'] = 'Content'; $lang['en_US']['File']['Filename'] = 'Filename'; $lang['en_US']['File']['INVALIDEXTENSION'] = array( 'Extension is not allowed (valid: %s)', PR_MEDIUM, 'Argument 1: Comma-separated list of valid extensions' ); $lang['en_US']['File']['NOFILESIZE'] = 'Filesize is zero bytes.'; $lang['en_US']['File']['NOVALIDUPLOAD'] = 'File is not a valid upload'; $lang['en_US']['File']['Name'] = 'Name'; $lang['en_US']['File']['PLURALNAME'] = array( 'Files', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['File']['SINGULARNAME'] = array( 'File', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['File']['Sort'] = 'Sort Order'; $lang['en_US']['File']['TOOLARGE'] = array( 'Filesize is too large, maximum %s allowed.', PR_MEDIUM, 'Argument 1: Filesize (e.g. 1MB)' ); $lang['en_US']['File']['Title'] = 'Title'; $lang['en_US']['FileIFrameField']['ATTACH'] = 'Attach %s'; $lang['en_US']['FileIFrameField']['ATTACHONCESAVED'] = '%ss can be attached once you have saved the record for the first time.'; $lang['en_US']['FileIFrameField']['DELETE'] = 'Delete %s'; $lang['en_US']['FileIFrameField']['FILE'] = 'File'; $lang['en_US']['FileIFrameField']['FROMCOMPUTER'] = 'From your Computer'; $lang['en_US']['FileIFrameField']['FROMFILESTORE'] = 'From the File Store'; $lang['en_US']['FileIFrameField']['NOSOURCE'] = 'Please select a source file to attach'; $lang['en_US']['FileIFrameField']['REPLACE'] = 'Replace %s'; $lang['en_US']['FileIFrameField.ss']['TITLE'] = 'Image Uploading Iframe'; $lang['en_US']['Folder']['CREATED'] = 'First Uploaded'; $lang['en_US']['Folder']['DELETEUNUSEDTHUMBNAILS'] = 'Delete unused thumbnails'; $lang['en_US']['Folder']['DELSELECTED'] = 'Delete selected files'; $lang['en_US']['Folder']['DETAILSTAB'] = 'Details'; $lang['en_US']['Folder']['FILENAME'] = 'Filename'; $lang['en_US']['Folder']['FILESTAB'] = 'Files'; $lang['en_US']['Folder']['LASTEDITED'] = 'Last Updated'; $lang['en_US']['Folder']['PLURALNAME'] = array( 'Files', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Folder']['SINGULARNAME'] = array( 'File', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Folder']['TITLE'] = 'Title'; $lang['en_US']['Folder']['TYPE'] = 'Type'; $lang['en_US']['Folder']['UNUSEDFILESTAB'] = 'Unused files'; $lang['en_US']['Folder']['UNUSEDFILESTITLE'] = 'Unused files'; $lang['en_US']['Folder']['UNUSEDTHUMBNAILSTITLE'] = 'Unused thumbnails'; $lang['en_US']['Folder']['UPLOADTAB'] = 'Upload'; $lang['en_US']['Folder']['URL'] = 'URL'; $lang['en_US']['Folder']['VIEWASSET'] = 'View Asset'; $lang['en_US']['Folder']['VIEWEDITASSET'] = 'View/Edit Asset'; $lang['en_US']['ForgotPasswordEmail.ss']['HELLO'] = 'Hi'; $lang['en_US']['ForgotPasswordEmail.ss']['TEXT1'] = 'Here is your'; $lang['en_US']['ForgotPasswordEmail.ss']['TEXT2'] = 'password reset link'; $lang['en_US']['ForgotPasswordEmail.ss']['TEXT3'] = 'for'; $lang['en_US']['Form']['FIELDISREQUIRED'] = '%s is required'; $lang['en_US']['Form']['LANGAOTHER'] = 'Other languages'; $lang['en_US']['Form']['LANGAVAIL'] = 'Available languages'; $lang['en_US']['Form']['VALIDATIONCREDITNUMBER'] = 'Please ensure you have entered the %s credit card number correctly.'; $lang['en_US']['Form']['VALIDATIONFAILED'] = 'Validation failed'; $lang['en_US']['Form']['VALIDATIONNOTUNIQUE'] = 'The value entered is not unique'; $lang['en_US']['Form']['VALIDATIONPASSWORDSDONTMATCH'] = 'Passwords don\'t match'; $lang['en_US']['Form']['VALIDATIONPASSWORDSNOTEMPTY'] = 'Passwords can\'t be empty'; $lang['en_US']['Form']['VALIDATIONSTRONGPASSWORD'] = 'Passwords must have at least one digit and one alphanumeric character.'; $lang['en_US']['Form']['VALIDATOR'] = 'Validator'; $lang['en_US']['Form']['VALIDCURRENCY'] = 'Please enter a valid currency.'; $lang['en_US']['FormField']['NONE'] = 'none'; $lang['en_US']['Group']['Code'] = array( 'Group Code', PR_MEDIUM, 'Programmatical code identifying a group' ); $lang['en_US']['Group']['DefaultGroupTitleAdministrators'] = 'Administrators'; $lang['en_US']['Group']['DefaultGroupTitleContentAuthors'] = 'Content Authors'; $lang['en_US']['Group']['Description'] = 'Description'; $lang['en_US']['Group']['IPRestrictions'] = 'IP Address Restrictions'; $lang['en_US']['Group']['Locked'] = array( 'Locked?', PR_MEDIUM, 'Group is locked in the security administration area' ); $lang['en_US']['Group']['PLURALNAME'] = array( 'Groups', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Group']['Parent'] = array( 'Parent Group', PR_MEDIUM, 'One group has one parent group' ); $lang['en_US']['Group']['SINGULARNAME'] = array( 'Group', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Group']['Sort'] = 'Sort Order'; $lang['en_US']['Group']['has_many_Permissions'] = array( 'Permissions', PR_MEDIUM, 'One group has many permissions' ); $lang['en_US']['Group']['many_many_Members'] = array( 'Members', PR_MEDIUM, 'One group has many members' ); $lang['en_US']['HtmlEditorField']['ANCHORVALUE'] = 'Anchor'; $lang['en_US']['HtmlEditorField']['BUTTONINSERTFLASH'] = 'Insert Flash'; $lang['en_US']['HtmlEditorField']['BUTTONINSERTIMAGE'] = 'Insert image'; $lang['en_US']['HtmlEditorField']['BUTTONINSERTLINK'] = 'Insert link'; $lang['en_US']['HtmlEditorField']['BUTTONREMOVELINK'] = 'Remove link'; $lang['en_US']['HtmlEditorField']['CAPTIONTEXT'] = 'Caption text'; $lang['en_US']['HtmlEditorField']['CLOSE'] = 'close'; $lang['en_US']['HtmlEditorField']['CSSCLASS'] = 'Alignment / style'; $lang['en_US']['HtmlEditorField']['CSSCLASSCENTER'] = 'Centered, on its own.'; $lang['en_US']['HtmlEditorField']['CSSCLASSLEFT'] = 'On the left, with text wrapping around.'; $lang['en_US']['HtmlEditorField']['CSSCLASSLEFTALONE'] = 'On the left, on its own.'; $lang['en_US']['HtmlEditorField']['CSSCLASSRIGHT'] = 'On the right, with text wrapping around.'; $lang['en_US']['HtmlEditorField']['EMAIL'] = 'Email address'; $lang['en_US']['HtmlEditorField']['FILE'] = 'File'; $lang['en_US']['HtmlEditorField']['FLASH'] = 'Flash'; $lang['en_US']['HtmlEditorField']['FOLDER'] = 'Folder'; $lang['en_US']['HtmlEditorField']['IMAGE'] = 'Image'; $lang['en_US']['HtmlEditorField']['IMAGEALTTEXT'] = 'Alternative text (alt) - shown if image cannot be displayed'; $lang['en_US']['HtmlEditorField']['IMAGEDIMENSIONS'] = 'Dimensions'; $lang['en_US']['HtmlEditorField']['IMAGEHEIGHTPX'] = 'Height'; $lang['en_US']['HtmlEditorField']['IMAGETITLE'] = 'Title text (tooltip) - for additional information about the image'; $lang['en_US']['HtmlEditorField']['IMAGEWIDTHPX'] = 'Width'; $lang['en_US']['HtmlEditorField']['LINK'] = 'Link'; $lang['en_US']['HtmlEditorField']['LINKANCHOR'] = 'Anchor on this page'; $lang['en_US']['HtmlEditorField']['LINKDESCR'] = 'Link description'; $lang['en_US']['HtmlEditorField']['LINKEMAIL'] = 'Email address'; $lang['en_US']['HtmlEditorField']['LINKEXTERNAL'] = 'Another website'; $lang['en_US']['HtmlEditorField']['LINKFILE'] = 'Download a file'; $lang['en_US']['HtmlEditorField']['LINKINTERNAL'] = 'Page on the site'; $lang['en_US']['HtmlEditorField']['LINKOPENNEWWIN'] = 'Open link in a new window?'; $lang['en_US']['HtmlEditorField']['LINKTEXT'] = 'Link text'; $lang['en_US']['HtmlEditorField']['LINKTO'] = 'Link to'; $lang['en_US']['HtmlEditorField']['PAGE'] = 'Page'; $lang['en_US']['HtmlEditorField']['SEARCHFILENAME'] = 'Search by file name'; $lang['en_US']['HtmlEditorField']['SHOWUPLOADFORM'] = 'Upload File'; $lang['en_US']['HtmlEditorField']['URL'] = 'URL'; $lang['en_US']['Image']['PLURALNAME'] = array( 'Files', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Image']['SINGULARNAME'] = array( 'File', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['ImageField']['IMAGE'] = 'Image'; $lang['en_US']['Image_Cached']['PLURALNAME'] = array( 'Files', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Image_Cached']['SINGULARNAME'] = array( 'File', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Image_iframe.ss']['TITLE'] = 'Image Uploading Iframe'; $lang['en_US']['LoginAttempt']['Email'] = 'Email Address'; $lang['en_US']['LoginAttempt']['IP'] = 'IP Address'; $lang['en_US']['LoginAttempt']['PLURALNAME'] = array( 'Login Attempts', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['LoginAttempt']['SINGULARNAME'] = array( 'Login Attempt', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['LoginAttempt']['Status'] = 'Status'; $lang['en_US']['Member']['ADDRESS'] = 'Address'; $lang['en_US']['Member']['BUTTONCHANGEPASSWORD'] = 'Change Password'; $lang['en_US']['Member']['BUTTONLOGIN'] = 'Log in'; $lang['en_US']['Member']['BUTTONLOGINOTHER'] = 'Log in as someone else'; $lang['en_US']['Member']['BUTTONLOSTPASSWORD'] = 'I\'ve lost my password'; $lang['en_US']['Member']['CONFIRMNEWPASSWORD'] = 'Confirm New Password'; $lang['en_US']['Member']['CONFIRMPASSWORD'] = 'Confirm Password'; $lang['en_US']['Member']['CONTACTINFO'] = 'Contact Information'; $lang['en_US']['Member']['DefaultAdminFirstname'] = 'Default Admin'; $lang['en_US']['Member']['DefaultDateTime'] = 'default'; $lang['en_US']['Member']['EMAIL'] = 'Email'; $lang['en_US']['Member']['EMAILSIGNUPINTRO1'] = 'Thanks for signing up to become a new member, your details are listed below for future reference.'; $lang['en_US']['Member']['EMAILSIGNUPINTRO2'] = 'You can login to the website using the credentials listed below'; $lang['en_US']['Member']['EMAILSIGNUPSUBJECT'] = 'Thanks for signing up'; $lang['en_US']['Member']['EMPTYNEWPASSWORD'] = 'The new password can\'t be empty, please try again'; $lang['en_US']['Member']['ENTEREMAIL'] = 'Please enter an email address to get a password reset link.'; $lang['en_US']['Member']['ERRORLOCKEDOUT'] = 'Your account has been temporarily disabled because of too many failed attempts at logging in. Please try again in 20 minutes.'; $lang['en_US']['Member']['ERRORNEWPASSWORD'] = 'You have entered your new password differently, try again'; $lang['en_US']['Member']['ERRORPASSWORDNOTMATCH'] = 'Your current password does not match, please try again'; $lang['en_US']['Member']['ERRORWRONGCRED'] = 'That doesn\'t seem to be the right e-mail address or password. Please try again.'; $lang['en_US']['Member']['FIRSTNAME'] = 'First Name'; $lang['en_US']['Member']['GREETING'] = 'Welcome'; $lang['en_US']['Member']['INTERFACELANG'] = array( 'Interface Language', PR_MEDIUM, 'Language of the CMS' ); $lang['en_US']['Member']['INVALIDNEWPASSWORD'] = 'We couldn\'t accept that password: %s'; $lang['en_US']['Member']['LOGGEDINAS'] = 'You\'re logged in as %s.'; $lang['en_US']['Member']['MOBILE'] = 'Mobile'; $lang['en_US']['Member']['NAME'] = 'Name'; $lang['en_US']['Member']['NEWPASSWORD'] = 'New Password'; $lang['en_US']['Member']['PASSWORD'] = 'Password'; $lang['en_US']['Member']['PASSWORDCHANGED'] = 'Your password has been changed, and a copy emailed to you.'; $lang['en_US']['Member']['PERSONALDETAILS'] = array( 'Personal Details', PR_MEDIUM, 'Headline for formfields' ); $lang['en_US']['Member']['PHONE'] = 'Phone'; $lang['en_US']['Member']['PLURALNAME'] = array( 'Members', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Member']['PROFILESAVESUCCESS'] = 'Successfully saved.'; $lang['en_US']['Member']['REMEMBERME'] = 'Remember me next time?'; $lang['en_US']['Member']['SINGULARNAME'] = array( 'Member', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Member']['SUBJECTPASSWORDCHANGED'] = array( 'Your password has been changed', PR_MEDIUM, 'Email subject' ); $lang['en_US']['Member']['SUBJECTPASSWORDRESET'] = array( 'Your password reset link', PR_MEDIUM, 'Email subject' ); $lang['en_US']['Member']['SURNAME'] = 'Surname'; $lang['en_US']['Member']['USERDETAILS'] = array( 'User Details', PR_MEDIUM, 'Headline for formfields' ); $lang['en_US']['Member']['VALIDATIONMEMBEREXISTS'] = 'A member already exists with the same %s'; $lang['en_US']['Member']['ValidationIdentifierFailed'] = array( 'Can\'t overwrite existing member #%d with identical identifier (%s = %s))', PR_MEDIUM, 'The values in brackets show a fieldname mapped to a value, usually denoting an existing email address' ); $lang['en_US']['Member']['WELCOMEBACK'] = 'Welcome Back, %s'; $lang['en_US']['Member']['YOUROLDPASSWORD'] = 'Your old password'; $lang['en_US']['Member']['belongs_many_many_Groups'] = array( 'Groups', PR_MEDIUM, 'Security Groups this member belongs to' ); $lang['en_US']['Member']['db_LastVisited'] = 'Last Visited Date'; $lang['en_US']['Member']['db_Locale'] = 'Interface Locale'; $lang['en_US']['Member']['db_LockedOutUntil'] = array( 'Locked out until', PR_MEDIUM, 'Security related date' ); $lang['en_US']['Member']['db_NumVisit'] = 'Number of Visits'; $lang['en_US']['Member']['db_Password'] = 'Password'; $lang['en_US']['Member']['db_PasswordExpiry'] = array( 'Password Expiry Date', PR_MEDIUM, 'Password expiry date' ); $lang['en_US']['MemberAuthenticator']['TITLE'] = 'E-mail &amp; Password'; $lang['en_US']['MemberDatetimeOptionsetField']['AMORPM'] = array( 'AM (Ante meridiem) or PM (Post meridiem)', 40, 'Help text describing what "a" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['Custom'] = 'Custom'; $lang['en_US']['MemberDatetimeOptionsetField']['DATEFORMATBAD'] = 'Date format is invalid'; $lang['en_US']['MemberDatetimeOptionsetField']['DAYNOLEADING'] = array( 'Day of month without leading zero', 40, 'Help text describing what "d" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['DIGITSDECFRACTIONSECOND'] = array( 'One or more digits representing a decimal fraction of a second', 40, 'Help text describing what "s" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['FOURDIGITYEAR'] = array( 'Four-digit year', 40, 'Help text describing what "YYYY" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['FULLNAMEMONTH'] = array( 'Full name of month (e.g. June)', 40, 'Help text describing what "MMMM" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['HOURNOLEADING'] = array( 'Hour without leading zero', 40, 'Help text describing what "h" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['MINUTENOLEADING'] = array( 'Minute without leading zero', 40, 'Help text describing what "m" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['MONTHNOLEADING'] = array( 'Month digit without leading zero', 40, 'Help text describing what "M" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['Preview'] = 'Preview'; $lang['en_US']['MemberDatetimeOptionsetField']['SHORTMONTH'] = array( 'Short name of month (e.g. Jun)', 40, 'Help text letting describing what "MMM" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['TOGGLEHELP'] = 'Toggle formatting help'; $lang['en_US']['MemberDatetimeOptionsetField']['TWODIGITDAY'] = array( 'Two-digit day of month', 40, 'Help text describing what "dd" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['TWODIGITHOUR'] = array( 'Two digits of hour (00 through 23)', 40, 'Help text describing what "hh" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['TWODIGITMINUTE'] = array( 'Two digits of minute (00 through 59)', 40, 'Help text describing what "mm" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['TWODIGITMONTH'] = array( 'Two-digit month (01=January, etc.)', 40, 'Help text describing what "MM" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['TWODIGITSECOND'] = array( 'Two digits of second (00 through 59)', 40, 'Help text describing what "ss" means in ISO date formatting' ); $lang['en_US']['MemberDatetimeOptionsetField']['TWODIGITYEAR'] = array( 'Two-digit year', 40, 'Help text describing what "YY" means in ISO date formatting' ); $lang['en_US']['MemberPassword']['PLURALNAME'] = array( 'Member Passwords', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['MemberPassword']['SINGULARNAME'] = array( 'Member Password', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['MoneyField']['FIELDLABELAMOUNT'] = 'Amount'; $lang['en_US']['MoneyField']['FIELDLABELCURRENCY'] = 'Currency'; $lang['en_US']['MyEntity']['MyNamespace'] = 'My default natural language value'; $lang['en_US']['MyNamespace']['MYENTITY'] = 'Counting %s things'; $lang['en_US']['NullableField']['IsNullLabel'] = array( 'Is Null', PR_HIGH ); $lang['en_US']['NumericField']['VALIDATION'] = '\'%s\' is not a number, only numbers can be accepted for this field'; $lang['en_US']['NumericField']['VALIDATIONJS'] = 'is not a number, only numbers can be accepted for this field'; $lang['en_US']['Permission']['AdminGroup'] = 'Administrator'; $lang['en_US']['Permission']['FULLADMINRIGHTS'] = 'Full administrative rights'; $lang['en_US']['Permission']['FULLADMINRIGHTS_HELP'] = 'Implies and overrules all other assigned permissions.'; $lang['en_US']['Permission']['PLURALNAME'] = array( 'Permissions', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Permission']['SINGULARNAME'] = array( 'Permission', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['PermissionCheckboxSetField']['AssignedTo'] = 'assigned to "%s"'; $lang['en_US']['PermissionCheckboxSetField']['FromGroup'] = array( 'inherited from group "%s"', PR_MEDIUM, 'A permission inherited from a certain group' ); $lang['en_US']['PermissionCheckboxSetField']['FromRole'] = array( 'inherited from role "%s"', PR_MEDIUM, 'A permission inherited from a certain permission role' ); $lang['en_US']['PermissionCheckboxSetField']['FromRoleOnGroup'] = array( 'inherited from role "%s" on group "%s"', PR_MEDIUM, 'A permission inherited from a role on a certain group' ); $lang['en_US']['PermissionRole']['PLURALNAME'] = array( 'Roles', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['PermissionRole']['SINGULARNAME'] = array( 'Role', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['PermissionRoleCode']['PLURALNAME'] = array( 'Permission Role Cods', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['PermissionRoleCode']['SINGULARNAME'] = array( 'Permission Role Code', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Permissions']['CONTENT_CATEGORY'] = 'Content permissions'; $lang['en_US']['Permissions']['PERMISSIONS_CATEGORY'] = 'Roles and access permissions'; $lang['en_US']['PhoneNumberField']['VALIDATION'] = 'Please enter a valid phone number'; $lang['en_US']['QueuedEmail']['PLURALNAME'] = array( 'Queued Emails', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['QueuedEmail']['SINGULARNAME'] = array( 'Queued Email', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['RedirectorPage']['HASBEENSETUP'] = 'A redirector page has been set up without anywhere to redirect to.'; $lang['en_US']['RedirectorPage']['HEADER'] = 'This page will redirect users to another page'; $lang['en_US']['RedirectorPage']['OTHERURL'] = 'Other website URL'; $lang['en_US']['RedirectorPage']['PLURALNAME'] = array( 'Redirector Pags', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['RedirectorPage']['REDIRECTTO'] = 'Redirect to'; $lang['en_US']['RedirectorPage']['REDIRECTTOEXTERNAL'] = 'Another website'; $lang['en_US']['RedirectorPage']['REDIRECTTOPAGE'] = 'A page on your website'; $lang['en_US']['RedirectorPage']['SINGULARNAME'] = array( 'Redirector Page', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['RedirectorPage']['YOURPAGE'] = 'Page on your website'; $lang['en_US']['RelationComplexTableField.ss']['ADD'] = 'Add'; $lang['en_US']['RelationComplexTableField.ss']['CSVEXPORT'] = 'Export to CSV'; $lang['en_US']['RelationComplexTableField.ss']['NOTFOUND'] = 'No items found'; $lang['en_US']['RemoveOrphanedPagesTask']['BUTTONRUN'] = 'Run'; $lang['en_US']['RemoveOrphanedPagesTask']['CHOOSEOPERATION'] = 'Choose operation:'; $lang['en_US']['RemoveOrphanedPagesTask']['DELETEWARNING'] = 'Warning: These operations are not reversible. Please handle with care.'; $lang['en_US']['RemoveOrphanedPagesTask']['HEADER'] = 'Remove all orphaned pages task'; $lang['en_US']['RemoveOrphanedPagesTask']['NONEFOUND'] = 'No orphans found'; $lang['en_US']['RemoveOrphanedPagesTask']['NONEREMOVED'] = 'None removed'; $lang['en_US']['RemoveOrphanedPagesTask']['OPERATION_REMOVE'] = 'Remove selected from all stages (WARNING: Will destroy all selected pages from both stage and live)'; $lang['en_US']['RemoveOrphanedPagesTask']['SELECTALL'] = 'select all'; $lang['en_US']['RemoveOrphanedPagesTask']['UNSELECTALL'] = 'unselect all'; $lang['en_US']['SearchForm']['GO'] = 'Go'; $lang['en_US']['SearchForm']['SEARCH'] = 'Search'; $lang['en_US']['SearchForm']['SearchResults'] = 'Search Results'; $lang['en_US']['Security']['ALREADYLOGGEDIN'] = array( 'You don\'t have access to this page. If you have another account that can access that page, you can log in again below.', PR_MEDIUM, '%s will be replaced with a link to log in.' ); $lang['en_US']['Security']['BUTTONSEND'] = 'Send me the password reset link'; $lang['en_US']['Security']['CHANGEPASSWORDBELOW'] = 'You can change your password below.'; $lang['en_US']['Security']['CHANGEPASSWORDHEADER'] = 'Change your password'; $lang['en_US']['Security']['ENTERNEWPASSWORD'] = 'Please enter a new password.'; $lang['en_US']['Security']['ERRORPASSWORDPERMISSION'] = 'You must be logged in in order to change your password!'; $lang['en_US']['Security']['IPADDRESSES'] = 'IP Addresses'; $lang['en_US']['Security']['LOGGEDOUT'] = 'You have been logged out. If you would like to log in again, enter your credentials below.'; $lang['en_US']['Security']['LOGIN'] = 'Log in'; $lang['en_US']['Security']['LOSTPASSWORDHEADER'] = 'Lost Password'; $lang['en_US']['Security']['NOTEPAGESECURED'] = 'That page is secured. Enter your credentials below and we will send you right along.'; $lang['en_US']['Security']['NOTERESETLINKINVALID'] = '<p>The password reset link is invalid or expired.</p><p>You can request a new one <a href="%s">here</a> or change your password after you <a href="%s">logged in</a>.</p>'; $lang['en_US']['Security']['NOTERESETPASSWORD'] = 'Enter your e-mail address and we will send you a link with which you can reset your password'; $lang['en_US']['Security']['PASSWORDSENTHEADER'] = 'Password reset link sent to \'%s\''; $lang['en_US']['Security']['PASSWORDSENTTEXT'] = 'Thank you! A reset link has been sent to \'%s\', provided an account exists for this email address.'; $lang['en_US']['SecurityAdmin']['GROUPNAME'] = 'Group name'; $lang['en_US']['SecurityAdmin']['IPADDRESSESHELP'] = '<p>You can restrict this group to a particular IP address range (one range per line). <br />Ranges can be in any of the following forms: <br /> 203.96.152.12<br /> 203.96.152/24<br /> 203.96/16<br /> 203/8<br /><br />If you enter one or more IP address ranges in this box, then members will only get the rights of being in this group if they log on from one of the valid IP addresses. It won\'t prevent people from logging in. This is because the same user might have to log in to access parts of the system without IP address restrictions.'; $lang['en_US']['SecurityAdmin']['MEMBERS'] = 'Members'; $lang['en_US']['SecurityAdmin']['NEWGROUPPREFIX'] = 'new-'; $lang['en_US']['SecurityAdmin']['PERMISSIONS'] = 'Permissions'; $lang['en_US']['SecurityAdmin']['ROLES'] = 'Roles'; $lang['en_US']['SecurityAdmin']['ROLESDESCRIPTION'] = 'This section allows you to add roles to this group. Roles are logical groupings of permissions, which can be editied in the Roles tab'; $lang['en_US']['SecurityAdmin']['VIEWUSER'] = 'View User'; $lang['en_US']['SilverStripeNavigatorLink']['ShareInstructions'] = 'To share a this to this page, copy and paste the link below.'; $lang['en_US']['SilverStripeNavigatorLink']['ShareLink'] = 'Share link'; $lang['en_US']['SilverStripeNavigatorLinkl']['CloseLink'] = 'Close'; $lang['en_US']['SimpleImageField']['NOUPLOAD'] = 'No Image Uploaded'; $lang['en_US']['SiteConfig']['DEFAULTTHEME'] = '(Use default theme)'; $lang['en_US']['SiteConfig']['EDITHEADER'] = 'Who can edit pages on this site?'; $lang['en_US']['SiteConfig']['EDIT_PERMISSION'] = 'Manage site configuration'; $lang['en_US']['SiteConfig']['EDIT_PERMISSION_HELP'] = 'Ability to edit global access settings/top-level page permissions.'; $lang['en_US']['SiteConfig']['PLURALNAME'] = array( 'Site Configs', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['SiteConfig']['SINGULARNAME'] = array( 'Site Config', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['SiteConfig']['SITENAMEDEFAULT'] = 'Your Site Name'; $lang['en_US']['SiteConfig']['SITETAGLINE'] = 'Site Tagline/Slogan'; $lang['en_US']['SiteConfig']['SITETITLE'] = 'Site title'; $lang['en_US']['SiteConfig']['TABACCESS'] = 'Access'; $lang['en_US']['SiteConfig']['TABMAIN'] = 'Main'; $lang['en_US']['SiteConfig']['TAGLINEDEFAULT'] = 'your tagline here'; $lang['en_US']['SiteConfig']['THEME'] = 'Theme'; $lang['en_US']['SiteConfig']['TOPLEVELCREATE'] = 'Who can create pages in the root of the site?'; $lang['en_US']['SiteConfig']['VIEWHEADER'] = 'Who can view pages on this site?'; $lang['en_US']['SiteTree']['ACCESSANYONE'] = 'Anyone'; $lang['en_US']['SiteTree']['ACCESSHEADER'] = 'Who can view this page?'; $lang['en_US']['SiteTree']['ACCESSLOGGEDIN'] = 'Logged-in users'; $lang['en_US']['SiteTree']['ACCESSONLYTHESE'] = 'Only these people (choose from list)'; $lang['en_US']['SiteTree']['ADDEDTODRAFT'] = 'Added to draft site'; $lang['en_US']['SiteTree']['ALLOWCOMMENTS'] = 'Allow comments on this page?'; $lang['en_US']['SiteTree']['APPEARSVIRTUALPAGES'] = 'This content also appears on the virtual pages in the %s sections.'; $lang['en_US']['SiteTree']['BUTTONCANCELDRAFT'] = 'Cancel draft changes'; $lang['en_US']['SiteTree']['BUTTONCANCELDRAFTDESC'] = 'Delete your draft and revert to the currently published page'; $lang['en_US']['SiteTree']['BUTTONSAVEPUBLISH'] = 'Save and Publish'; $lang['en_US']['SiteTree']['BUTTONUNPUBLISH'] = 'Unpublish'; $lang['en_US']['SiteTree']['BUTTONUNPUBLISHDESC'] = 'Remove this page from the published site'; $lang['en_US']['SiteTree']['CHANGETO'] = array( 'Change to "%s"', PR_MEDIUM, 'Pagetype selection dropdown with class names' ); $lang['en_US']['SiteTree']['Comments'] = 'Comments'; $lang['en_US']['SiteTree']['Content'] = array( 'Content', PR_MEDIUM, 'Main HTML Content for a page' ); $lang['en_US']['SiteTree']['DEFAULTABOUTCONTENT'] = '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>'; $lang['en_US']['SiteTree']['DEFAULTABOUTTITLE'] = 'About Us'; $lang['en_US']['SiteTree']['DEFAULTCONTACTCONTENT'] = '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>'; $lang['en_US']['SiteTree']['DEFAULTCONTACTTITLE'] = 'Contact Us'; $lang['en_US']['SiteTree']['DEFAULTHOMECONTENT'] = '<p>Welcome to SilverStripe! This is the default homepage. You can edit this page by opening <a href="admin/">the CMS</a>. You can now access the <a href="http://doc.silverstripe.org">developer documentation</a>, or begin <a href="http://doc.silverstripe.org/doku.php?id=tutorials">the tutorials.</a></p>'; $lang['en_US']['SiteTree']['DEFAULTHOMETITLE'] = 'Home'; $lang['en_US']['SiteTree']['DELETEDPAGE'] = 'Deleted page'; $lang['en_US']['SiteTree']['DEPENDENT_NOTE'] = 'The following pages depend on this page. This includes virtual pages, redirector pages, and pages with content links.'; $lang['en_US']['SiteTree']['DependtPageColumnLinkType'] = 'Link type'; $lang['en_US']['SiteTree']['DependtPageColumnURL'] = 'URL'; $lang['en_US']['SiteTree']['EDITANYONE'] = 'Anyone who can log-in to the CMS'; $lang['en_US']['SiteTree']['EDITHEADER'] = 'Who can edit this page?'; $lang['en_US']['SiteTree']['EDITONLYTHESE'] = 'Only these people (choose from list)'; $lang['en_US']['SiteTree']['EDITORGROUPS'] = 'Editor Groups'; $lang['en_US']['SiteTree']['EDIT_ALL_DESCRIPTION'] = 'Edit any page'; $lang['en_US']['SiteTree']['EDIT_ALL_HELP'] = 'Ability to edit any page on the site, regardless of the settings on the Access tab. Requires the "Access to Site Content" permission'; $lang['en_US']['SiteTree']['Editors'] = 'Editors Groups'; $lang['en_US']['SiteTree']['HASBROKENLINKS'] = 'This page has broken links.'; $lang['en_US']['SiteTree']['HOMEPAGEFORDOMAIN'] = array( 'Domain(s)', PR_MEDIUM, 'Listing domains that should be used as homepage' ); $lang['en_US']['SiteTree']['HTMLEDITORTITLE'] = array( 'Content', PR_MEDIUM, 'HTML editor title' ); $lang['en_US']['SiteTree']['HomepageForDomain'] = 'Hompage for this domain'; $lang['en_US']['SiteTree']['INHERIT'] = 'Inherit from parent page'; $lang['en_US']['SiteTree']['LINKCHANGENOTE'] = 'Changing this page\'s link will also affect the links of all child pages.'; $lang['en_US']['SiteTree']['MENUTITLE'] = 'Navigation label'; $lang['en_US']['SiteTree']['METADESC'] = 'Description'; $lang['en_US']['SiteTree']['METAEXTRA'] = 'Custom Meta Tags'; $lang['en_US']['SiteTree']['METAHEADER'] = 'Search Engine Meta-tags'; $lang['en_US']['SiteTree']['METAKEYWORDS'] = 'Keywords'; $lang['en_US']['SiteTree']['METATITLE'] = 'Title'; $lang['en_US']['SiteTree']['MODIFIEDONDRAFT'] = 'Modified on draft site'; $lang['en_US']['SiteTree']['NOTEUSEASHOMEPAGE'] = 'Use this page as the \'home page\' for the following domains: (separate multiple domains with commas)'; $lang['en_US']['SiteTree']['PAGELOCATION'] = 'Page location'; $lang['en_US']['SiteTree']['PAGETITLE'] = 'Page name'; $lang['en_US']['SiteTree']['PAGETYPE'] = array( 'Page type', PR_MEDIUM, 'Classname of a page object' ); $lang['en_US']['SiteTree']['PARENTID'] = array( 'Parent page', PR_MEDIUM ); $lang['en_US']['SiteTree']['PARENTTYPE'] = array( 'Page location', PR_MEDIUM ); $lang['en_US']['SiteTree']['PARENTTYPE_ROOT'] = 'Top-level page'; $lang['en_US']['SiteTree']['PARENTTYPE_SUBPAGE'] = 'Sub-page underneath a parent page (choose below)'; $lang['en_US']['SiteTree']['PERMISSION_GRANTACCESS_DESCRIPTION'] = 'Manage access rights for content'; $lang['en_US']['SiteTree']['PERMISSION_GRANTACCESS_HELP'] = 'Allow setting of page-specific access restrictions in the "Pages" section.'; $lang['en_US']['SiteTree']['PLURALNAME'] = array( 'Site Tres', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['SiteTree']['REMOVEDFROMDRAFT'] = 'Removed from draft site'; $lang['en_US']['SiteTree']['REMOVE_INSTALL_WARNING'] = 'Warning: You should remove install.php from this SilverStripe install for security reasons.'; $lang['en_US']['SiteTree']['REORGANISE_DESCRIPTION'] = 'Change site structure'; $lang['en_US']['SiteTree']['REORGANISE_HELP'] = 'Rearrange pages in the site tree through drag&drop.'; $lang['en_US']['SiteTree']['SHOWINMENUS'] = 'Show in menus?'; $lang['en_US']['SiteTree']['SHOWINSEARCH'] = 'Show in search?'; $lang['en_US']['SiteTree']['SINGULARNAME'] = array( 'Site Tree', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['SiteTree']['TABACCESS'] = 'Access'; $lang['en_US']['SiteTree']['TABBEHAVIOUR'] = 'Behaviour'; $lang['en_US']['SiteTree']['TABCONTENT'] = 'Content'; $lang['en_US']['SiteTree']['TABDEPENDENT'] = 'Dependent pages'; $lang['en_US']['SiteTree']['TABMAIN'] = 'Main'; $lang['en_US']['SiteTree']['TABMETA'] = 'Metadata'; $lang['en_US']['SiteTree']['TABTODO'] = 'To-do'; $lang['en_US']['SiteTree']['TODOHELP'] = '<p>You can use this to keep track of work that needs to be done to the content of your site. To see all your pages with to do information, open the \'Site Reports\' window on the left and select \'To Do\'</p>'; $lang['en_US']['SiteTree']['TOPLEVEL'] = 'Site Content (Top Level)'; $lang['en_US']['SiteTree']['TOPLEVELCREATORGROUPS'] = 'Top level creators'; $lang['en_US']['SiteTree']['ToDo'] = 'Todo Notes'; $lang['en_US']['SiteTree']['URL'] = 'URL'; $lang['en_US']['SiteTree']['URLSegment'] = array( 'URL Segment', PR_MEDIUM, 'URL for this page' ); $lang['en_US']['SiteTree']['VALIDATIONURLSEGMENT1'] = 'Another page is using that URL. URL must be unique for each page'; $lang['en_US']['SiteTree']['VALIDATIONURLSEGMENT2'] = 'URLs can only be made up of letters, digits and hyphens.'; $lang['en_US']['SiteTree']['VIEWERGROUPS'] = 'Viewer Groups'; $lang['en_US']['SiteTree']['VIEW_ALL_DESCRIPTION'] = 'View any page'; $lang['en_US']['SiteTree']['VIEW_ALL_HELP'] = 'Ability to view any page on the site, regardless of the settings on the Access tab. Requires the "Access to Site Content" permission'; $lang['en_US']['SiteTree']['VIEW_DRAFT_CONTENT'] = 'View draft content'; $lang['en_US']['SiteTree']['VIEW_DRAFT_CONTENT_HELP'] = 'Applies to viewing pages outside of the CMS in draft mode. Useful for external collaborators without CMS access.'; $lang['en_US']['SiteTree']['Viewers'] = 'Viewers Groups'; $lang['en_US']['SiteTree']['has_one_Parent'] = array( 'Parent Page', PR_MEDIUM, 'The parent page in the site hierarchy' ); $lang['en_US']['SiteTree']['many_many_BackLinkTracking'] = 'Backlink Tracking'; $lang['en_US']['SiteTree']['many_many_ImageTracking'] = 'Image Tracking'; $lang['en_US']['SiteTree']['many_many_LinkTracking'] = 'Link Tracking'; $lang['en_US']['TableField']['ISREQUIRED'] = 'In %s \'%s\' is required.'; $lang['en_US']['TableField.ss']['ADD'] = 'Add a new row'; $lang['en_US']['TableField.ss']['ADDITEM'] = 'Add %s'; $lang['en_US']['TableField.ss']['CSVEXPORT'] = 'Export to CSV'; $lang['en_US']['TableListField']['CSVEXPORT'] = 'Export to CSV'; $lang['en_US']['TableListField']['PRINT'] = 'Print'; $lang['en_US']['TableListField']['SELECT'] = 'Select:'; $lang['en_US']['TableListField.ss']['NOITEMSFOUND'] = 'No items found'; $lang['en_US']['TableListField.ss']['SORTASC'] = 'Sort in ascending order'; $lang['en_US']['TableListField.ss']['SORTDESC'] = 'Sort in descending order'; $lang['en_US']['TableListField_PageControls.ss']['DISPLAYING'] = 'Displaying'; $lang['en_US']['TableListField_PageControls.ss']['OF'] = 'of'; $lang['en_US']['TableListField_PageControls.ss']['TO'] = 'to'; $lang['en_US']['TableListField_PageControls.ss']['VIEWFIRST'] = 'View first'; $lang['en_US']['TableListField_PageControls.ss']['VIEWLAST'] = 'View last'; $lang['en_US']['TableListField_PageControls.ss']['VIEWNEXT'] = 'View next'; $lang['en_US']['TableListField_PageControls.ss']['VIEWPREVIOUS'] = 'View previous'; $lang['en_US']['TimeField']['VALIDATEFORMAT'] = 'Please enter a valid time format (%s)'; $lang['en_US']['ToggleCompositeField.ss']['HIDE'] = 'Hide'; $lang['en_US']['ToggleCompositeField.ss']['SHOW'] = 'Show'; $lang['en_US']['ToggleField']['LESS'] = 'less'; $lang['en_US']['ToggleField']['MORE'] = 'more'; $lang['en_US']['Translatable']['CREATE'] = 'Create new translation'; $lang['en_US']['Translatable']['CREATEBUTTON'] = 'Create'; $lang['en_US']['Translatable']['EXISTING'] = 'Existing translations:'; $lang['en_US']['Translatable']['NEWLANGUAGE'] = 'New language'; $lang['en_US']['Translatable']['NOTICENEWPAGE'] = 'Please save this page before creating a translation'; $lang['en_US']['Translatable']['TRANSLATEALLPERMISSION'] = 'Translate into all available languages'; $lang['en_US']['Translatable']['TRANSLATEPERMISSION'] = array( 'Translate %s', PR_MEDIUM, 'Translate pages into a language' ); $lang['en_US']['Translatable']['TRANSLATIONS'] = 'Translations'; $lang['en_US']['TreeSelectorField']['CANCEL'] = 'cancel'; $lang['en_US']['TreeSelectorField']['SAVE'] = 'save'; $lang['en_US']['Versioned']['has_many_Versions'] = array( 'Versions', PR_MEDIUM, 'Past Versions of this page' ); $lang['en_US']['VirtualPage']['CHOOSE'] = 'Choose a page to link to'; $lang['en_US']['VirtualPage']['EDITCONTENT'] = 'click here to edit the content'; $lang['en_US']['VirtualPage']['HEADER'] = 'This is a virtual page'; $lang['en_US']['VirtualPage']['PLURALNAME'] = array( 'Virtual Pags', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['VirtualPage']['SINGULARNAME'] = array( 'Virtual Page', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['Widget']['PLURALNAME'] = array( 'Widgets', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['Widget']['SINGULARNAME'] = array( 'Widget', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); $lang['en_US']['WidgetArea']['PLURALNAME'] = array( 'Widget Areas', 50, 'Pural name of the object, used in dropdowns and to generally identify a collection of this object in the interface' ); $lang['en_US']['WidgetArea']['SINGULARNAME'] = array( 'Widget Area', 50, 'Singular name of the object, used in dropdowns and to generally identify a single object in the interface' ); ?>
{ "content_hash": "f97bdb5c61d97312b07bca0a38d8c3c0", "timestamp": "", "source": "github", "line_count": 960, "max_line_length": 357, "avg_line_length": 53.471875, "alnum_prop": 0.6749264605614322, "repo_name": "michaelbirks/lawdiff", "id": "72b427977d26bfda9577cbdabb84d4baaf2baf03", "size": "51333", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sapphire/lang/en_US.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "5134781" }, { "name": "PHP", "bytes": "7227115" }, { "name": "Ruby", "bytes": "6447" }, { "name": "Scheme", "bytes": "71765" } ], "symlink_target": "" }
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="description"> <meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon"> <link rel="icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon"> <title>OpenTl.Schema - API - RequestInstallStickerSet.Stickerset Property</title> <link href="/OpenTl.Schema/assets/css/mermaid.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/highlight.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/bootstrap/bootstrap.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/adminlte/AdminLTE.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/theme/theme.css" rel="stylesheet"> <link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="/OpenTl.Schema/assets/css/override.css" rel="stylesheet"> <script src="/OpenTl.Schema/assets/js/jquery-2.2.3.min.js"></script> <script src="/OpenTl.Schema/assets/js/bootstrap.min.js"></script> <script src="/OpenTl.Schema/assets/js/app.min.js"></script> <script src="/OpenTl.Schema/assets/js/highlight.pack.js"></script> <script src="/OpenTl.Schema/assets/js/jquery.slimscroll.min.js"></script> <script src="/OpenTl.Schema/assets/js/jquery.sticky-kit.min.js"></script> <script src="/OpenTl.Schema/assets/js/mermaid.min.js"></script> <!--[if lt IE 9]> <script src="/OpenTl.Schema/assets/js/html5shiv.min.js"></script> <script src="/OpenTl.Schema/assets/js/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition wyam layout-boxed "> <div class="top-banner"></div> <div class="wrapper with-container"> <!-- Header --> <header class="main-header"> <a href="/OpenTl.Schema/" class="logo"> <span>OpenTl.Schema</span> </a> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle visible-xs-block" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-right"></i> </a> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-down"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="/OpenTl.Schema/about.html">About This Project</a></li> <li class="active"><a href="/OpenTl.Schema/api">API</a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- Navbar Right Menu --> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar "> <section class="infobar" data-spy="affix" data-offset-top="60" data-offset-bottom="200"> <div id="infobar-headings"><h6>On This Page</h6><p><a href="#Syntax">Syntax</a></p> <p><a href="#Attributes">Attributes</a></p> <p><a href="#Value">Value</a></p> <hr class="infobar-hidden"> </div> </section> <section class="sidebar"> <script src="/OpenTl.Schema/assets/js/lunr.min.js"></script> <script src="/OpenTl.Schema/assets/js/searchIndex.js"></script> <div class="sidebar-form"> <div class="input-group"> <input type="text" name="search" id="search" class="form-control" placeholder="Search Types..."> <span class="input-group-btn"> <button class="btn btn-flat"><i class="fa fa-search"></i></button> </span> </div> </div> <div id="search-results"> </div> <script> function runSearch(query){ $("#search-results").empty(); if( query.length < 2 ){ return; } var results = searchModule.search("*" + query + "*"); var listHtml = "<ul class='sidebar-menu'>"; listHtml += "<li class='header'>Type Results</li>"; if(results.length == 0 ){ listHtml += "<li>No results found</li>"; } else { for(var i = 0; i < results.length; ++i){ var res = results[i]; listHtml += "<li><a href='" + res.url + "'>" + htmlEscape(res.title) + "</a></li>"; } } listHtml += "</ul>"; $("#search-results").append(listHtml); } $(document).ready(function(){ $("#search").on('input propertychange paste', function() { runSearch($("#search").val()); }); }); function htmlEscape(html) { return document.createElement('div') .appendChild(document.createTextNode(html)) .parentNode .innerHTML; } </script> <hr> <ul class="sidebar-menu"> <li class="header">Namespace</li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages">OpenTl<wbr>.Schema<wbr>.Messages</a></li> <li class="header">Type</li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestInstallStickerSet">Request<wbr>Install<wbr>Sticker<wbr>Set</a></li> <li role="separator" class="divider"></li> <li class="header">Property Members</li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestInstallStickerSet/C3016945.html">Archived</a></li> <li class="selected"><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestInstallStickerSet/AD3F42E4.html">Stickerset</a></li> </ul> </section> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <section class="content-header"> <h3><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestInstallStickerSet">Request<wbr>Install<wbr>Sticker<wbr>Set</a>.</h3> <h1>Stickerset <small>Property</small></h1> </section> <section class="content"> <div class="panel panel-default"> <div class="panel-body"> <dl class="dl-horizontal"> <dt>Namespace</dt> <dd><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages">OpenTl<wbr>.Schema<wbr>.Messages</a></dd> <dt>Containing Type</dt> <dd><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestInstallStickerSet">Request<wbr>Install<wbr>Sticker<wbr>Set</a></dd> </dl> </div> </div> <h1 id="Syntax">Syntax</h1> <pre><code>[SerializationOrder(0)] public IInputStickerSet Stickerset { get; set; }</code></pre> <h1 id="Attributes">Attributes</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover two-cols"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody><tr> <td>Serialization<wbr>Order<wbr>Attribute</td> <td></td> </tr> </tbody></table> </div> </div> <h1 id="Value">Value</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover two-cols"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody><tr> <td><a href="/OpenTl.Schema/api/OpenTl.Schema/IInputStickerSet">IInputStickerSet</a></td> <td></td> </tr> </tbody></table> </div> </div> </section> </div> <!-- Footer --> <footer class="main-footer"> </footer> </div> <div class="wrapper bottom-wrapper"> <footer class="bottom-footer"> Generated by <a href="https://wyam.io">Wyam</a> </footer> </div> <a href="javascript:" id="return-to-top"><i class="fa fa-chevron-up"></i></a> <script> // Close the sidebar if we select an anchor link $(".main-sidebar a[href^='#']:not('.expand')").click(function(){ $(document.body).removeClass('sidebar-open'); }); $(document).load(function() { mermaid.initialize( { flowchart: { htmlLabels: false, useMaxWidth:false } }); mermaid.init(undefined, ".mermaid") $('svg').addClass('img-responsive'); $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); hljs.initHighlightingOnLoad(); // Back to top $(window).scroll(function() { if ($(this).scrollTop() >= 200) { // If page is scrolled more than 50px $('#return-to-top').fadeIn(1000); // Fade in the arrow } else { $('#return-to-top').fadeOut(1000); // Else fade out the arrow } }); $('#return-to-top').click(function() { // When arrow is clicked $('body,html').animate({ scrollTop : 0 // Scroll to top of body }, 500); }); </script> </body></html>
{ "content_hash": "82c899e73fa7a8d65e266dc025cb2a33", "timestamp": "", "source": "github", "line_count": 278, "max_line_length": 148, "avg_line_length": 39.589928057553955, "alnum_prop": 0.5088133745229875, "repo_name": "OpenTl/OpenTl.Schema", "id": "69c75c14995d6390ad613cb856c26d7a1ceaeca8", "size": "11008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/OpenTl.Schema.Messages/RequestInstallStickerSet/AD3F42E4.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "810786" }, { "name": "F#", "bytes": "19501" }, { "name": "PowerShell", "bytes": "1288" } ], "symlink_target": "" }
#include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/common/time.h> //fps calculations #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/visualization/image_viewer.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/console/parse.h> #include <pcl/visualization/mouse_event.h> #include <vtkImageViewer.h> #include <vtkImageImport.h> #include <vector> #include <string> using namespace std; #define SHOW_FPS 1 #if SHOW_FPS #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ double now = pcl::getTime (); \ ++count; \ if (now - last >= 1.0) \ { \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) #else #define FPS_CALC(_WHAT_) \ do \ { \ }while(false) #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointType> class SimpleOpenNIViewer { public: typedef pcl::PointCloud<PointType> Cloud; typedef typename Cloud::ConstPtr CloudConstPtr; SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber) : cloud_viewer_ ("PCL OpenNI Viewer") , grabber_ (grabber) #if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4)) , image_viewer_ ("PCL image viewer") #endif { } void cloud_callback (const CloudConstPtr& cloud) { FPS_CALC ("cloud callback"); boost::mutex::scoped_lock lock (cloud_mutex_); cloud_ = cloud; } #if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4)) void image_callback (const boost::shared_ptr<openni_wrapper::Image>& image) { FPS_CALC ("image callback"); boost::mutex::scoped_lock lock (image_mutex_); image_ = image; } boost::shared_ptr<openni_wrapper::Image> getLatestImage () { boost::mutex::scoped_lock lock(image_mutex_); boost::shared_ptr<openni_wrapper::Image> temp_image; temp_image.swap (image_); return (temp_image); } #endif void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void* cookie) { string* message = (string*)cookie; cout << (*message) << " :: "; if (event.getKeyCode()) cout << "the key \'" << event.getKeyCode() << "\' (" << (int)event.getKeyCode() << ") was"; else cout << "the special key \'" << event.getKeySym() << "\' was"; if (event.keyDown()) cout << " pressed" << endl; else cout << " released" << endl; } void mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie) { string* message = (string*) cookie; if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton) { cout << (*message) << " :: " << mouse_event.getX () << " , " << mouse_event.getY () << endl; } } /** * @brief swaps the pointer to the point cloud with Null pointer and returns the cloud pointer * @return boost shared pointer to point cloud */ CloudConstPtr getLatestCloud () { //lock while we swap our cloud and reset it. boost::mutex::scoped_lock lock(cloud_mutex_); CloudConstPtr temp_cloud; temp_cloud.swap (cloud_); //here we set cloud_ to null, so that //it is safe to set it again from our //callback return (temp_cloud); } /** * @brief starts the main loop */ void run () { //pcl::Grabber* interface = new pcl::OpenNIGrabber(device_id_, pcl::OpenNIGrabber::OpenNI_QQVGA_30Hz, pcl::OpenNIGrabber::OpenNI_VGA_30Hz); string mouseMsg3D("Mouse coordinates in PCL Visualizer"); string keyMsg3D("Key event for PCL Visualizer"); cloud_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, (void*)(&mouseMsg3D)); cloud_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, (void*)(&keyMsg3D)); boost::function<void (const CloudConstPtr&) > cloud_cb = boost::bind (&SimpleOpenNIViewer::cloud_callback, this, _1); boost::signals2::connection cloud_connection = grabber_.registerCallback (cloud_cb); #if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4)) boost::signals2::connection image_connection; if (grabber_.providesCallback<void (const boost::shared_ptr<openni_wrapper::Image>&)>()) { string mouseMsg2D("Mouse coordinates in image viewer"); string keyMsg2D("Key event for image viewer"); image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, (void*)(&mouseMsg2D)); image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, (void*)(&keyMsg2D)); boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1); image_connection = grabber_.registerCallback (image_cb); } unsigned char* rgb_data = 0; unsigned rgb_data_size = 0; #endif grabber_.start (); while (!cloud_viewer_.wasStopped(1)) { if (cloud_) { FPS_CALC ("drawing cloud"); //the call to get() sets the cloud_ to null; cloud_viewer_.showCloud (getLatestCloud ()); } #if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4)) if (image_) { boost::shared_ptr<openni_wrapper::Image> image = getLatestImage (); if (image->getEncoding() == openni_wrapper::Image::RGB) { image_viewer_.showRGBImage(image->getMetaData().Data(), image->getWidth(), image->getHeight()); } else { if (rgb_data_size < image->getWidth() * image->getHeight()) { rgb_data_size = image->getWidth() * image->getHeight(); rgb_data = new unsigned char [rgb_data_size * 3]; } image->fillRGB (image->getWidth(), image->getHeight(), rgb_data); image_viewer_.showRGBImage(rgb_data, image->getWidth(), image->getHeight()); } // This will crash: image_viewer_.spinOnce (10); } #endif std::cout << __LINE__ << std::endl; } std::cout << __LINE__ << std::endl; grabber_.stop(); cloud_connection.disconnect(); #if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4)) image_connection.disconnect(); if (rgb_data) delete[] rgb_data; #endif } pcl::visualization::CloudViewer cloud_viewer_; pcl::OpenNIGrabber& grabber_; boost::mutex cloud_mutex_; CloudConstPtr cloud_; #if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4)) boost::mutex image_mutex_; boost::shared_ptr<openni_wrapper::Image> image_; pcl::visualization::ImageViewer image_viewer_; #endif }; void usage(char ** argv) { cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-depthmode <mode>] [-imagemode <mode>] [-xyz] | -l [<device_id>]| -h | --help)]" << endl; cout << argv[0] << " -h | --help : shows this help" << endl; cout << argv[0] << " -l : list all available devices" << endl; cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl; cout << " device_id may be #1, #2, ... for the first, second etc device in the list" #ifndef _WIN32 << " or" << endl << " bus@address for the device connected to a specific usb-bus / address combination or" << endl << " <serial-number>" #endif << endl; cout << endl; cout << "examples:" << endl; cout << argv[0] << " \"#1\"" << endl; cout << " uses the first device." << endl; cout << argv[0] << " \"./temp/test.oni\"" << endl; cout << " uses the oni-player device to play back oni file given by path." << endl; cout << argv[0] << " -l" << endl; cout << " lists all available devices." << endl; cout << argv[0] << " -l \"#2\"" << endl; cout << " lists all available modes for the second device" << endl; #ifndef _WIN32 cout << argv[0] << " A00361800903049A" << endl; cout << " uses the device with the serial number \'A00361800903049A\'." << endl; cout << argv[0] << " 1@16" << endl; cout << " uses the device on address 16 at USB bus 1." << endl; #endif return; } int main(int argc, char ** argv) { std::string device_id(""); pcl::OpenNIGrabber::Mode depth_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode; pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode; bool xyz = false; if (argc >= 2) { device_id = argv[1]; if (device_id == "--help" || device_id == "-h") { usage(argv); return 0; } else if (device_id == "-l") { if (argc >= 3) { pcl::OpenNIGrabber grabber(argv[2]); boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice(); cout << "Supported depth modes for device: " << device->getVendorName() << " , " << device->getProductName() << endl; std::vector<std::pair<int, XnMapOutputMode > > modes = grabber.getAvailableDepthModes(); for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it) { cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl; } if (device->hasImageStream ()) { cout << endl << "Supported image modes for device: " << device->getVendorName() << " , " << device->getProductName() << endl; modes = grabber.getAvailableImageModes(); for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it) { cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl; } } } else { openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance(); if (driver.getNumberDevices() > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices(); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName(deviceIdx) << ", product: " << driver.getProductName(deviceIdx) << ", connected: " << (int) driver.getBus(deviceIdx) << " @ " << (int) driver.getAddress(deviceIdx) << ", serial number: \'" << driver.getSerialNumber(deviceIdx) << "\'" << endl; } } else cout << "No devices connected." << endl; cout <<"Virtual Devices available: ONI player" << endl; } return 0; } } else { openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance(); if (driver.getNumberDevices() > 0) cout << "Device Id not set, using first device." << endl; } unsigned mode; if (pcl::console::parse(argc, argv, "-depthmode", mode) != -1) depth_mode = (pcl::OpenNIGrabber::Mode) mode; if (pcl::console::parse(argc, argv, "-imagemode", mode) != -1) image_mode = (pcl::OpenNIGrabber::Mode) mode; if (pcl::console::find_argument(argc, argv, "-xyz") != -1) xyz = true; pcl::OpenNIGrabber grabber (device_id, depth_mode, image_mode); if (xyz) // only if xyz flag is set, since grabber provides at least XYZ and XYZI pointclouds { SimpleOpenNIViewer<pcl::PointXYZ> v (grabber); v.run (); } else if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ()) { SimpleOpenNIViewer<pcl::PointXYZRGBA> v (grabber); v.run (); } else { SimpleOpenNIViewer<pcl::PointXYZI> v (grabber); v.run (); } return (0); }
{ "content_hash": "342a37e58b1e10fb445d37e1abc14a60", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 192, "avg_line_length": 35.53779069767442, "alnum_prop": 0.5784867075664621, "repo_name": "ros-perception/pcl-fuerte", "id": "2882749e0abb98429daa9d0aaa47d9d367199616", "size": "14092", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "visualization/tools/openni_viewer_simple.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "184877" }, { "name": "C++", "bytes": "7041631" }, { "name": "Python", "bytes": "14431" } ], "symlink_target": "" }
CREATE PROCEDURE T4SQL.META_CREATE_WORKITEM_TRIGGER ( @inWorkitem_Table NVARCHAR(128) ) AS SET NOCOUNT ON; DECLARE @tDdlSql NVARCHAR(1024), @tSchema NVARCHAR(64); IF NOT EXISTS ( SELECT 1 FROM sys.triggers T WHERE T.parent_id = OBJECT_ID(@inWorkitem_Table, N'U') AND T.type = 'TR' AND T.parent_class = 1 ) BEGIN SET @tSchema = PARSENAME(@inWorkitem_Table, 2); IF @tSchema IS NULL SET @tSchema = N'' ELSE SET @tSchema = @tSchema + N'.'; SET @tDdlSql = N'CREATE TRIGGER ' + @tSchema + 'TRG_' + PARSENAME(@inWorkitem_Table, 1) + N'_IU ON ' + @inWorkitem_Table + N' AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @tWorkitems AS T4SQL.TT_WORKITEMS; INSERT INTO @tWorkitems (WORKITEM_NAME, TEMPLATE_CLASS) SELECT I.WORKITEM_NAME, I.TEMPLATE_NAME FROM inserted I; EXEC T4SQL.META_COPY_PROPERTY_DEFAULT @@PROCID, @tWorkitems; END;'; EXECUTE (@tDdlSql); END; ---------------------------------------------------------------------------------------------------- -- -- Copyright 2013 Abel Cheng -- This source code is subject to terms and conditions of the Apache License, Version 2.0. -- See http://www.apache.org/licenses/LICENSE-2.0. -- All other rights reserved. -- You must not remove this notice, or any other, from this software. -- -- Original Author: Abel Cheng <abelcys@gmail.com> -- Created Date: April 20, 2013, 11:44:31 PM -- Primary Host: http://t4sql.codeplex.com -- Change Log: -- Author Date Comment -- -- -- -- -- (Keep code clean rather than complicated code plus long comments.) -- ----------------------------------------------------------------------------------------------------
{ "content_hash": "6eb6941e16390f344a760ac20f5adafa", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 100, "avg_line_length": 27.140625, "alnum_prop": 0.5785837651122625, "repo_name": "DataBooster/T4SQL", "id": "8c85c93babca77cf66ad24dc0ceca8a40c422d08", "size": "1739", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "T4SQLTemplateLibrary/Databases/SqlServer/Schema Objects/Schemas/T4SQL/Programmability/Stored Procedures/T4SQL.META_CREATE_WORKITEM_TRIGGER.proc.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "125" }, { "name": "C#", "bytes": "455650" }, { "name": "HTML", "bytes": "23165" }, { "name": "PLSQL", "bytes": "56328" }, { "name": "PowerShell", "bytes": "408" }, { "name": "SQLPL", "bytes": "26089" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4b062e8ded1f559e8b986aeff718f914", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "4a2fe4f524230f5741894194d581d7ca862e766d", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Convolvulaceae/Convolvulus/Convolvulus cissoides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Rhino.Mocks; using SS.FTPDownloader.Objects.Media; using SS.FTPDownloader.Utilities; // ReSharper disable once CheckNamespace namespace SS.FTPDownloader.UnitTests.Objects.TvEpisodeTests { [TestClass] public class FileNameParsingTests { [TestMethod] public void TvEpisodesWithSceneFileNameFormattingAreCorrectlyParsed() { //Arrange var fileName = "The.Big.Bang.Theory.S04E03.The.Zazzy.Substitution.BluRay.1080p.Remux.AVC.DTS-HDMA.5.1-BluHD.mkv"; var expectedResults = new { FileName = "The.Big.Bang.Theory.S04E03.The.Zazzy.Substitution.BluRay.1080p.Remux.AVC.DTS-HDMA.5.1-BluHD.mkv", ShowName = "The Big Bang Theory", Extension = ".mkv", Episode = "03", EpisodeRange = "", Season = "04" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.EpisodeRange, obj.EpisodeRange); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesWithAnXSeasonEpisodeSeparatorAreCorrectlyParsed() { //Arrange var fileName = "doctor_who_2005.8x08.mummy_on_the_orient_express.720p_hdtv_x264-fov.mkv"; var expectedResults = new { FileName = "doctor_who_2005.8x08.mummy_on_the_orient_express.720p_hdtv_x264-fov.mkv", ShowName = "Doctor Who 2005", Extension = ".mkv", Episode = "08", EpisodeRange = "", Season = "08" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.EpisodeRange, obj.EpisodeRange); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesAlreadyInTargetFormattingAreCorrectlyParsed() { //Arrange var fileName = "Doctor Who - S09E16.mkv"; var expectedResults = new { FileName = "Doctor Who - S09E16.mkv", ShowName = "Doctor Who", Extension = ".mkv", Episode = "16", EpisodeRange = "", Season = "09" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.EpisodeRange, obj.EpisodeRange); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesWithSceneFileNameFormattingAndARangeOfEpisodesAreCorrectlyParsed() { //Arrange var fileName = "The.Big.Bang.Theory.S04E03-E05.mkv"; var expectedResults = new { FileName = "The.Big.Bang.Theory.S04E03-E05.mkv", ShowName = "The Big Bang Theory", Extension = ".mkv", Episode = "03", EpisodeRange = "05", Season = "04" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.EpisodeRange, obj.EpisodeRange); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesAlreadyInTargetFormattingAndARangeOfEpisodesAreCorrectlyParsed() { //Arrange var fileName = "Doctor Who - S09E06-E09.mkv"; var expectedResults = new { FileName = "Doctor Who - S09E06-E09.mkv", ShowName = "Doctor Who", Extension = ".mkv", Episode = "06", EpisodeRange = "09", Season = "09" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.EpisodeRange, obj.EpisodeRange); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesWithSpelledOutSeasonAndEpisodeAreCorrectlyParsed() { //Arrange var fileName = "Farscape Season 01 Episode 01 - Through the Eye of the Needle TSV.mkv"; var expectedResults = new { FileName = "Farscape Season 01 Episode 01 - Through the Eye of the Needle TSV.mkv", ShowName = "Farscape", Extension = ".mkv", Episode = "01", Season = "01" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesWithAnXSeasonEpisodeSeperatorAndRangeOfEpisodesAreCorrectlyParsed() { //Arrange var fileName = "las.vegas-05x01-02.avi"; var expectedResults = new { FileName = "las.vegas-05x01-02.avi", ShowName = "Las Vegas", Extension = ".avi", Episode = "01", EpisodeRange = "02", Season = "05" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.EpisodeRange, obj.EpisodeRange); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesWithAnXSeasonEpisodeSeperatorAndRangeOfEpisodesAreCorrectlyParsed2() { //Arrange var fileName = "Rocko's Modern Life - S01E03-E04 - Leap Frogs + Bedfellows HDTV-720p.mkv"; var expectedResults = new { FileName = "Rocko's Modern Life - S01E03-E04 - Leap Frogs + Bedfellows HDTV-720p.mkv", ShowName = "Rocko's Modern Life", Extension = ".mkv", Episode = "03", EpisodeRange = "04", Season = "01", DisplayName = "Rocko's Modern Life - S01E03-E04" }; var factory = new MediaFactory(); //Act var obj = factory.CreateMediaObject(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, ((TvEpisode) obj).Episode); Assert.AreEqual(expectedResults.EpisodeRange, ((TvEpisode)obj).EpisodeRange); Assert.AreEqual(expectedResults.Season, ((TvEpisode)obj).Season); Assert.AreEqual(expectedResults.DisplayName, obj.DisplayName); } [TestMethod] public void TvEpisodesWithNoSeasonEpisodeSeperatorAreCorrectlyParsed() { //Arrange var fileName = "Las Vegas 304 - Whatever Happened to Seymour Magoon.avi"; var expectedResults = new { FileName = "Las Vegas 304 - Whatever Happened to Seymour Magoon.avi", ShowName = "Las Vegas", Extension = ".avi", Episode = "04", //EpisodeRange = "02", Season = "03" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.Season, obj.Season); } [TestMethod] public void TvEpisodesWithSeasonButNoEpisodeIdentifierAreCorrectlyParsed() { //Arrange var fileName = "The Simpsons Season 24 - 10.mp4"; var expectedResults = new { FileName = "The Simpsons Season 24 - 10.mp4", ShowName = "The Simpsons", Extension = ".mp4", Episode = "10", //EpisodeRange = "02", Season = "24" }; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResults.FileName, obj.FileLocation); Assert.AreEqual(expectedResults.ShowName, obj.Name); Assert.AreEqual(expectedResults.Extension, obj.Extension); Assert.AreEqual(expectedResults.Episode, obj.Episode); Assert.AreEqual(expectedResults.Season, obj.Season); } } [TestClass] public class FileDetectionTests { [TestMethod] public void TvShowsWithSceneFileNameAreDetectedAsTvEpisodes() { //Arrange var fileName = "The.Big.Bang.Theory.S04E03.The.Zazzy.Substitution.BluRay.1080p.Remux.AVC.DTS-HDMA.5.1-BluHD.mkv"; var factory = new MediaFactory(); //Act var result = factory.CreateMediaObject(fileName, true); //Assert Assert.IsInstanceOfType(result, typeof(TvEpisode)); } [TestMethod] public void MoviesWithSceneFileNamesAreNotDetectedAsTvEpisodes() { //Arrange var fileName = "Transformers.Age.Of.Extinction.2014.1080p.DVDR.NTSC-LPD.mkv"; var factory = new MediaFactory(); //Act var result = factory.CreateMediaObject(fileName, true); //Assert Assert.IsNotInstanceOfType(result, typeof(TvEpisode)); } } [TestClass] public class FileMovingTests { [TestMethod] public void TvEpisodeIsMovedCorrectlyBasedOnFileName() { //Arrange var fileUtility = MockRepository.GenerateMock<IFileUtilities>(); var episode = new TvEpisode("Show Name - S01E02.avi", true); fileUtility.Expect(x => x.Move(episode.FileLocation, @"D:\Video\\TV\Show Name\Season 01\Show Name - S01E02.avi")); //Act episode.Process(fileUtility); //Assert //fileUtility.VerifyAllExpectations(); } [TestMethod] public void TvEpisodeMoveLocationProperlyAppendsRangeIfItExists() { //Arrange var fileName = "Doctor Who - S09E06-E09.mkv"; var expectedResult = "\\TV\\Doctor Who\\Season 09\\Doctor Who - S09E06-E09.mkv"; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResult, obj.MoveLocation); } [TestMethod] public void TvEpisodeMoveLocationIsTheCorrectPath() { //Arrange var fileName = "Doctor Who - S09E06.mkv"; var expectedResult = "\\TV\\Doctor Who\\Season 09\\Doctor Who - S09E06.mkv"; //Act var obj = new TvEpisode(fileName, true); //Assert Assert.AreEqual(expectedResult, obj.MoveLocation); } } [TestClass] public class FileRenamingTests { [TestMethod] public void TvEpisodesAreRenamedAccordingToRenameList() { //Arrange var episode = new TvEpisode("Show Name - S01E02.avi", true); const string expectedShowName = "New Show"; //Act var result = episode.GetName(s => s == "Show Name" ? expectedShowName : s); //Assert Assert.AreEqual(expectedShowName, result); } } [TestClass] public class FolderCreationTests { [TestMethod] public void TvEpisodeAttemptsToMakeCorrectFolderPaths() { //Arrange var fileUtility = MockRepository.GenerateMock<IFileUtilities>(); var episode = new TvEpisode("Show Name - S01E02.avi", true); fileUtility.Expect(x => x.MakeDirs(@"D:\Video\\TV\Show Name\Season 01\Show Name - S01E02.avi")); //Act episode.Process(fileUtility); //Assert //fileUtility.VerifyAllExpectations(); } } }
{ "content_hash": "3ce4f2c6b2723002ee68029830a97d96", "timestamp": "", "source": "github", "line_count": 415, "max_line_length": 117, "avg_line_length": 28.09879518072289, "alnum_prop": 0.7103164394134294, "repo_name": "kingofzeal/SS.FTPDownloader", "id": "338a41c8a3faee905c167bce832344a4fd5828b2", "size": "11663", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SS.FTPDownloader.UnitTests/Objects/TvEpisodeTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "162886" } ], "symlink_target": "" }
package com.google.gerrit.server.change; import com.google.gerrit.extensions.registration.DynamicMap; import com.google.gerrit.extensions.restapi.ChildCollection; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.RestView; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton class ChangeEdits implements ChildCollection<ChangeResource, ChangeEditResource> { private final DynamicMap<RestView<ChangeEditResource>> views; @Inject ChangeEdits(DynamicMap<RestView<ChangeEditResource>> views) { this.views = views; } @Override public DynamicMap<RestView<ChangeEditResource>> views() { return views; } @Override public RestView<ChangeResource> list() { throw new IllegalStateException("not yet implemented"); } @Override public ChangeEditResource parse(ChangeResource change, IdString id) { throw new IllegalStateException("not yet implemented"); } }
{ "content_hash": "4f6dcc328a26f108225f45e2fce9f817", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 71, "avg_line_length": 28.61764705882353, "alnum_prop": 0.7821171634121274, "repo_name": "midnightradio/gerrit", "id": "55834da0dafcad64fabe6bf3adfd949f2770d7df", "size": "1582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gerrit-server/src/main/java/com/google/gerrit/server/change/ChangeEdits.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53403" }, { "name": "GAP", "bytes": "4285" }, { "name": "Go", "bytes": "1865" }, { "name": "Java", "bytes": "8144236" }, { "name": "JavaScript", "bytes": "2306" }, { "name": "Perl", "bytes": "9943" }, { "name": "Prolog", "bytes": "17712" }, { "name": "Python", "bytes": "12549" }, { "name": "Shell", "bytes": "38586" } ], "symlink_target": "" }
using namespace BloombergLP; using namespace bsl; // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // The component under test implements a concurrent FIFO queue container // requiring a single consumer. The primary manipulators are the methods for // adding elements ('pushBack') and emptying the queue ('removeAll'). The // provided basic accessors are the methods for obtaining the allocator // ('allocator') and the number of elements in the queue ('numElements'). The // manipulator 'popFront' will be used extensively to verify the value of // resultant queues. The basic functionality of the queue will be verified // initially with a single thread of execution, and then concurrency concerns // will be addressed. Effort is made to use only the primary manipulators, // basic accessors, and 'popFront' whenever possible, thus making every test // case independent. // // Note that the move-semantics testing types are not universally supported. // Move-only type is supported in C++11 mode. Allocating move-only type is // supported in C++11 mode. 'IncorrectlyMatchingMoveConstructorTestType' works // in C++03 mode. // // Global Concerns: //: o The test driver is robust w.r.t. reuse in other, similar components. //: o ACCESSOR methods are declared 'const'. //: o CREATOR & MANIPULATOR pointer/reference parameters are declared 'const'. //: o No memory is ever allocated from the global allocator. //: o Any allocated memory is always from the object allocator. //: o An object's value is independent of the allocator used to supply memory. //: o Injected exceptions are safely propagated during memory allocation. //: o Precondition violations are detected in appropriate build modes. // // Global Assumptions: //: o All explicit memory allocations are presumed to use the global, default, //: or object allocator. //: o ACCESSOR methods are 'const' thread-safe. // ---------------------------------------------------------------------------- // [ 2] SingleConsumerQueue(bslma::Allocator *basicAllocator = 0); // [ 5] SingleConsumerQueue(capacity, *bA = 0); // [ 2] ~SingleConsumerQueue(); // [ 2] int popFront(TYPE *value); // [ 2] int pushBack(const TYPE& value); // [10] int pushBack(bslmf::MovableRef<TYPE> value); // [ 2] void removeAll(); // [ 8] int tryPopFront(TYPE *value); // [ 7] int tryPushBack(const TYPE& value); // [10] int tryPushBack(bslmf::MovableRef<TYPE> value); // [ 6] void disablePopFront(); // [ 6] void disablePushBack(); // [ 6] void enablePopFront(); // [ 6] void enablePushBack(); // [ 4] bool isEmpty() const; // [ 4] bool isFull() const; // [ 6] bool isPopFrontDisabled() const; // [ 6] bool isPushBackDisabled() const; // [ 4] bsl::size_t numElements() const; // [ 9] int waitUntilEmpty() const; // [ 4] bslma::Allocator *allocator() const; // ---------------------------------------------------------------------------- // [ 1] BREATHING TEST // [13] USAGE EXAMPLE // [ 3] Obj& gg(Obj *object, const char *spec); // [ 3] int ggg(Obj *object, const char *spec); // [ 2] CONCERN: 0 == e_SUCCESS // [10] CONCERN: 'popFront' and 'tryPopFront' honor move-semantics // [11] CONCERN: template requirements // [12] CONCERN: ordering guarantee // ---------------------------------------------------------------------------- // ============================================================================ // STANDARD BDE ASSERT TEST MACRO // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(int c, const char *s, int i) { if (c) { cout << "Error " << __FILE__ << "(" << i << "): " << s << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) ++testStatus; } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // GLOBAL MACROS FOR TESTING // ---------------------------------------------------------------------------- #if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES) \ && defined(BSLS_COMPILERFEATURES_SUPPORT_ALIAS_TEMPLATES) # define BSLMF_MOVABLEREF_USES_RVALUE_REFERENCES // This macro indicates whether the component uses C++11 r-value references // to implement 'bslmf::MovableRef<TYPE>'. It will evaluate to 'false' for // C++03 implementations and to 'true' for proper C++11 implementations. // For partial C++11 implementations it may evaluate to 'false' because // both r-value reference and alias templates need to be supported. #endif // ============================================================================ // GLOBAL STRUCTS/FUNCTIONS FOR TESTING // ---------------------------------------------------------------------------- // ==================== // AllocExceptionHelper // ==================== class AllocExceptionHelper { // DATA void *d_memory; bslma::Allocator *d_allocator_p; public: // CREATORS AllocExceptionHelper(bslma::Allocator *allocator) : d_allocator_p(allocator) { d_memory = d_allocator_p->allocate(1); } AllocExceptionHelper(const AllocExceptionHelper& obj, bslma::Allocator *allocator) : d_allocator_p(allocator) { (void)obj; d_memory = d_allocator_p->allocate(1); } ~AllocExceptionHelper() { d_allocator_p->deallocate(d_memory); } // MANIPULATORS AllocExceptionHelper& operator=(const AllocExceptionHelper& rhs) { (void)rhs; void *memory = d_allocator_p->allocate(1); d_allocator_p->deallocate(d_memory); d_memory = memory; return *this; } }; // ========== // MoveTester // ========== class MoveTester { // DATA bool d_moved; int *d_moveCounter_p; int d_value; // NOT IMPLEMENTED MoveTester(const MoveTester& other); MoveTester& operator=(const MoveTester& other); public: // CREATORS explicit MoveTester(int value, int *moveCounter = 0); // Construct a new 'MoveTester' object with the specified 'value'. // Optionally specify a 'moveCounter' that, if specified, will be // incremented when this object is moved from. explicit MoveTester(bslmf::MovableRef<MoveTester> other); // Move-construct a new 'MoveTester' object from the specified 'other'. // MANIPULATORS MoveTester& operator=(bslmf::MovableRef<MoveTester> other); // Move-assign the value of the specified 'other' object to this one. // Set 'isMoved' to 'true', and if non-null value is specified at // construction time also set '*d_moveCounter_p' to 'true' void reset(); // Reset 'isMoved' to false. // ACCESSORS bool isMoved() const; // Return the value of the moved non-salient attribute. int value() const; // Return the value of this object. }; // ---------- // MoveTester // ---------- // CREATORS MoveTester::MoveTester(int value, int *moveCounter) : d_moved(false) , d_moveCounter_p(moveCounter) , d_value(value) { } MoveTester::MoveTester(bslmf::MovableRef<MoveTester> other) { typedef bslmf::MovableRefUtil MoveUtil; d_value = MoveUtil::access(other).d_value; d_moved = false; d_moveCounter_p = MoveUtil::access(other).d_moveCounter_p; MoveUtil::access(other).d_moved = true; if (MoveUtil::access(other).d_moveCounter_p) { ++(*MoveUtil::access(other).d_moveCounter_p); } } // MANIPULATORS MoveTester& MoveTester::operator=(bslmf::MovableRef<MoveTester> other) { typedef bslmf::MovableRefUtil MoveUtil; d_value = MoveUtil::access(other).d_value; MoveUtil::access(other).d_moved = true; if (MoveUtil::access(other).d_moveCounter_p) { ++(*MoveUtil::access(other).d_moveCounter_p); } return *this; } // ACCESSORS bool MoveTester::isMoved() const { return d_moved; } int MoveTester::value() const { return d_value; } // ================================================ // class IncorrectlyMatchingMoveConstructorTestType // ================================================ class IncorrectlyMatchingMoveConstructorTestType { // This class is convertible from any type that has a 'data' method // returning a 'int' value. It is used to facilitate testing that the // implementation of 'bdlcc::SingleConsumerQueue' does not pass a // 'bslmf::MovableRef<T>' object to a class whose interface does not // support it (in C++03 mode). // DATA int d_data; // value not meaningful public: // CREATORS IncorrectlyMatchingMoveConstructorTestType(); // Create a 'IncorrectlyMatchingMoveConstructorTestType' object having // the default value. explicit IncorrectlyMatchingMoveConstructorTestType(int data); // Create a 'IncorrectlyMatchingMoveConstructorTestType' object having // the specified 'data' value. IncorrectlyMatchingMoveConstructorTestType( const IncorrectlyMatchingMoveConstructorTestType& original); // Create a 'IncorrectlyMatchingMoveConstructorTestType' object having // the same value as the specified 'original' object. template <class TYPE> IncorrectlyMatchingMoveConstructorTestType(const TYPE& other); // IMPLICIT // Create a 'IncorrectlyMatchingMoveConstructorTestType' object having // the same value as the specified 'other' object of (template // parameter) 'TYPE'. // MANIPULATORS IncorrectlyMatchingMoveConstructorTestType& operator=( const IncorrectlyMatchingMoveConstructorTestType& rhs); // Assign to this object the value of the specified 'rhs' object, and // return a non-'const' reference to this object. template <class TYPE> IncorrectlyMatchingMoveConstructorTestType& operator=(const TYPE& rhs); // Assign to this object the value of the specified 'rhs' object of // (template parameter) 'TYPE', and return a non-'const' reference to // this object. // ACCESSORS int data() const; // Return the (meaningless) value held by this object. }; // ------------------------------------------------ // class IncorrectlyMatchingMoveConstructorTestType // ------------------------------------------------ // CREATORS IncorrectlyMatchingMoveConstructorTestType:: IncorrectlyMatchingMoveConstructorTestType() : d_data(0) { } IncorrectlyMatchingMoveConstructorTestType:: IncorrectlyMatchingMoveConstructorTestType(int data) : d_data(data) { } IncorrectlyMatchingMoveConstructorTestType:: IncorrectlyMatchingMoveConstructorTestType( const IncorrectlyMatchingMoveConstructorTestType& original) : d_data(original.d_data) { } template <class TYPE> IncorrectlyMatchingMoveConstructorTestType:: IncorrectlyMatchingMoveConstructorTestType(const TYPE& other) : d_data(other.data()) { } // MANIPULATORS IncorrectlyMatchingMoveConstructorTestType& IncorrectlyMatchingMoveConstructorTestType::operator=( const IncorrectlyMatchingMoveConstructorTestType& rhs) { d_data = rhs.d_data; return *this; } template <class TYPE> IncorrectlyMatchingMoveConstructorTestType& IncorrectlyMatchingMoveConstructorTestType::operator=(const TYPE& rhs) { d_data = rhs.data(); return *this; } // ACCESSORS int IncorrectlyMatchingMoveConstructorTestType::data() const { return d_data; } // --------------------------------- // class TemplateRequirementTestType // --------------------------------- class TemplateRequirementTestType { int *d_arg_p; public: TemplateRequirementTestType(int *arg1) : d_arg_p(arg1) { ++(*d_arg_p); } TemplateRequirementTestType(const TemplateRequirementTestType& rhs) : d_arg_p(rhs.d_arg_p) { ++(*d_arg_p); } TemplateRequirementTestType& operator=( const TemplateRequirementTestType& rhs) { --(*d_arg_p); d_arg_p = rhs.d_arg_p; ++(*d_arg_p); return *this; } ~TemplateRequirementTestType() { --(*d_arg_p); } }; // ============================================================================ // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING // ---------------------------------------------------------------------------- typedef bdlcc::SingleConsumerQueue<int> Obj; typedef bdlcc::SingleConsumerQueue<bsl::string> AllocObj; const int e_SUCCESS = Obj::e_SUCCESS; const int e_EMPTY = Obj::e_EMPTY; const int e_DISABLED = Obj::e_DISABLED; // ============================================================================ // GLOBAL METHODS FOR TESTING // ---------------------------------------------------------------------------- static bsls::AtomicInt s_continue; extern "C" void *deferredDisablePopFront(void *arg) { Obj& mX = *static_cast<Obj *>(arg); bslmt::ThreadUtil::microSleep(1000000); mX.disablePopFront(); return 0; } static bsls::TimeInterval s_deferredPopFrontInterval; extern "C" void *deferredPopFront(void *arg) { s_deferredPopFrontInterval = bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME); Obj& mX = *static_cast<Obj *>(arg); bslmt::ThreadUtil::microSleep(1000000); Obj::value_type value; mX.popFront(&value); s_deferredPopFrontInterval = bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME) - s_deferredPopFrontInterval; return 0; } struct OrderingValue { bsls::Types::Uint64 d_pushThreadId; bsls::Types::Uint64 d_sequenceNumber; }; typedef bdlcc::SingleConsumerQueue<OrderingValue> OrderingObj; struct OrderingPopData { OrderingObj *d_obj_p; bsl::unordered_map<bsls::Types::Uint64, bsls::Types::Uint64> d_sequenceNumber; bool d_isStrongTest; }; extern "C" void *orderingPop(void *arg) { OrderingPopData *data = static_cast<OrderingPopData *>(arg); OrderingObj& mX = *data->d_obj_p; OrderingObj::value_type value; while (1 < s_continue) { if (0 == mX.popFront(&value)) { bsls::Types::Uint64 pushThreadId = value.d_pushThreadId; bsls::Types::Uint64 sequenceNumber = value.d_sequenceNumber; bsls::Types::Uint64& lastSequenceNumber = data->d_sequenceNumber[pushThreadId]; if (data->d_isStrongTest) { ASSERTV(pushThreadId, lastSequenceNumber, sequenceNumber, lastSequenceNumber + 1 == sequenceNumber); } else { ASSERTV(pushThreadId, lastSequenceNumber, sequenceNumber, lastSequenceNumber < sequenceNumber); } lastSequenceNumber = sequenceNumber; } } return 0; } extern "C" void *orderingPush(void *arg) { OrderingObj& mX = *static_cast<OrderingObj *>(arg); OrderingObj::value_type value; value.d_pushThreadId = bslmt::ThreadUtil::selfIdAsUint64(); value.d_sequenceNumber = 1; while (2 < s_continue) { if (0 == mX.pushBack(value)) { value.d_sequenceNumber += 1; } } return 0; } extern "C" void *orderingState(void *arg) { OrderingObj& mX = *static_cast<OrderingObj *>(arg); int count = 0; while (3 < s_continue) { bslmt::ThreadUtil::microSleep(100000); if (3 == count % 10) { mX.disablePopFront(); } else if (4 == count % 10) { mX.enablePopFront(); } else if (8 == count % 10) { mX.disablePushBack(); } else if (9 == count % 10) { mX.enablePushBack(); } ++count; } return 0; } static char s_watchdogText[128]; void setWatchdogText(const char *value) { memcpy(s_watchdogText, value, strlen(value) + 1); } extern "C" void *watchdog(void *) { const int MAX = 100; // one iteration is a decisecond int count = 0; while (s_continue) { bslmt::ThreadUtil::microSleep(100000); ++count; ASSERTV(s_watchdogText, count < MAX); if (MAX == count && s_continue) { abort(); } } return 0; } void orderingGuaranteeTest(const int numPushThread, const int numPopThread) { bslmt::ThreadUtil::Handle watchdogHandle; bslmt::ThreadUtil::Handle stateHandle; bsl::vector<bslmt::ThreadUtil::Handle> pushHandle(numPushThread); bsl::vector<bslmt::ThreadUtil::Handle> popHandle(numPopThread); bsl::vector<OrderingPopData> orderingPopData(numPopThread); s_continue = 4; OrderingObj mX; const OrderingObj& X = mX; setWatchdogText("ordering guarantee"); bslmt::ThreadUtil::create(&watchdogHandle, watchdog, 0); bslmt::ThreadUtil::create(&stateHandle, orderingState, &mX); { for (int i = 0; i < numPushThread; ++i) { bslmt::ThreadUtil::create(&pushHandle[i], orderingPush, &mX); } for (int i = 0; i < numPopThread; ++i) { orderingPopData[i].d_obj_p = &mX; orderingPopData[i].d_isStrongTest = ( 1 == numPushThread && 1 == numPopThread); bslmt::ThreadUtil::create(&popHandle[i], orderingPop, &orderingPopData[i]); } } bslmt::ThreadUtil::microSleep(1000000); s_continue = 3; setWatchdogText("ordering guarantee: join state"); bslmt::ThreadUtil::join(stateHandle); mX.enablePopFront(); mX.enablePushBack(); bslmt::ThreadUtil::microSleep(1000000); s_continue = 2; mX.disablePushBack(); setWatchdogText("ordering guarantee: join push"); for (int i = 0; i < numPushThread; ++i){ bslmt::ThreadUtil::join(pushHandle[i]); } setWatchdogText("ordering guarantee: wait until empty"); int rv = X.waitUntilEmpty(); ASSERT(0 == rv); ASSERT(0 == X.numElements()); s_continue = 1; mX.disablePopFront(); setWatchdogText("ordering guarantee: join pop"); for (int i = 0; i < numPopThread; ++i){ bslmt::ThreadUtil::join(popHandle[i]); } s_continue = 0; setWatchdogText("ordering guarantee: join watchdog"); bslmt::ThreadUtil::join(watchdogHandle); } // ============================================================================ // GENERATOR FUNCTIONS 'gg' AND 'ggg' FOR TESTING // ---------------------------------------------------------------------------- // The following functions interpret the given 'spec' in order from left to // right to configure the object according to a custom language. // // LANGUAGE SPECIFICATION: // ----------------------- // // <SPEC> ::= <EMPTY> | <LIST> // // <EMPTY> ::= // // <LIST> ::= <ITEM> | <ITEM><LIST> // // <ITEM> ::= <ELEMENT> | '~' // // <ELEMENT> ::= 'a' | 'b' | 'c' | 'd' | 'e' int getValue(int *value, char specChar, int verboseFlag); // Place into the specified 'value' the value corresponding to the // specified 'specChar' and display errors to 'cerr' if the specified // 'verboseFlag' is set. Return 0 if operation successful, return non-zero // otherwise. enum { e_SUCCESS_PUSHBACK = -1, e_SUCCESS_REMOVEALL = -2 }; int getValue(int *value, char specChar, int verboseFlag) { static int values[] = { 0, 1, 2, 3, 4 }; if ('~' == specChar) { return e_SUCCESS_REMOVEALL; // RETURN } if ('a' <= specChar && 'e' >= specChar) { *value = values[specChar - 'a']; return e_SUCCESS_PUSHBACK; // RETURN } if (verboseFlag) { cerr << "\t\tERROR!" << endl; cerr << specChar << " not recognized." << endl; } return 1; } template <class OBJ> int ggg(OBJ *object, const char *spec, int verboseFlag = 1) // Configure the specified 'object' according to the specified 'spec', // using only the primary manipulator functions 'pushBack' and 'removeAll'. // Optionally specify a zero 'verboseFlag' to suppress 'spec' syntax error // messages. Return the index of the first invalid character, and a // negative value otherwise. Note that this function is used to implement // 'gg' as well as allow for verification of syntax error detection. { enum { e_SUCCESS = -1 }; typename OBJ::value_type v; for (int i = 0; spec[i]; ++i) { int rv = getValue(&v, spec[i], verboseFlag); if (rv > -1) { return i; // RETURN } else if (e_SUCCESS_PUSHBACK == rv) { object->pushBack(v); } else if (e_SUCCESS_REMOVEALL == rv) { object->removeAll(); } } return e_SUCCESS; } template <class OBJ> OBJ& gg(OBJ *object, const char *spec) // Return, by reference, the specified 'object' with its value adjusted // according to the specified 'spec'. { ASSERT(ggg(object, spec) < 0); return *object; } // ============================================================================ // USAGE EXAMPLE // ---------------------------------------------------------------------------- ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: A Simple Thread Pool ///- - - - - - - - - - - - - - - - // In the following example a 'bdlcc::SingleConsumerQueue' is used to // communicate between multiple "producer" threads and a single "consumer" // thread. The "producers" will push work requests onto the queue, and the // "consumer" will iteratively take a work request from the queue and service // the request. // // First, we define a utility classes that handles a simple "work item": //.. struct my_WorkData { // Work data... }; //.. // Next, we provide a simple function to service an individual work item. The // details are unimportant for this example: //.. void myDoWork(const my_WorkData& data) { // do some stuff... (void)data; } //.. // Then, we define a 'myProducer' function that will push elements onto the // queue until the queue is disabled. Note that the call to // 'queue->pushFront(&item)' will never block: //.. void myProducer(bdlcc::SingleConsumerQueue<my_WorkData> *queue) { while (1) { my_WorkData item; if (queue->pushBack(item)) { return; // RETURN } } } //.. // Finally, we define a 'myConsumer' function that serves multiple roles: it // creates the 'bdlcc::SingleConsumerQueue', starts the producer threads, and // then dequeues and processes work items. After completing an amount of work // items, the queue is disabled for enqueueing, the producer threads are joined // and the consumer uses 'tryPopFront' until the queue is empty. //.. void myConsumer(int numThreads) { enum { k_NUM_WORK_ITEMS = 1000 }; bdlcc::SingleConsumerQueue<my_WorkData> queue; bslmt::ThreadGroup producerThreads; producerThreads.addThreads(bdlf::BindUtil::bind(&myProducer, &queue), numThreads); my_WorkData item; for (int i = 0; i < k_NUM_WORK_ITEMS; ++i) { queue.popFront(&item); myDoWork(item); } queue.disablePushBack(); producerThreads.joinAll(); while (0 == queue.tryPopFront(&item)) { myDoWork(item); } ASSERT(queue.isEmpty()); } //.. // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; bool verbose = argc > 2; bool veryVerbose = argc > 3; bool veryVeryVerbose = argc > 4; bool veryVeryVeryVerbose = argc > 5; cout << "TEST " << __FILE__ << " CASE " << test << endl; // CONCERN: In no case does memory come from the global allocator. bslma::TestAllocator globalAllocator("global", veryVeryVeryVerbose); bslma::Default::setGlobalAllocator(&globalAllocator); bslma::TestAllocator defaultAllocator("default", veryVeryVeryVerbose); ASSERT(0 == bslma::Default::setDefaultAllocator(&defaultAllocator)); switch (test) { case 0: // Zero is always the leading case. case 13: { // -------------------------------------------------------------------- // USAGE EXAMPLE // Extracted from component header file. // // Concerns: //: 1 The usage example provided in the component header file compiles, //: links, and runs as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, remove //: leading comment characters, and replace 'assert' with 'ASSERT'. //: (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << endl << "USAGE EXAMPLE" << endl << "=============" << endl; bslmt::ThreadUtil::Handle watchdogHandle; s_continue = 1; bslmt::ThreadUtil::create(&watchdogHandle, watchdog, const_cast<char *>("usage example")); enum { k_NUM_THREADS = 4 }; myConsumer(k_NUM_THREADS); s_continue = 0; bslmt::ThreadUtil::join(watchdogHandle); } break; case 12: { // --------------------------------------------------------- // Ordering Guarantee Test // The queue should provide the minimal ordering guarantee for // concurrent queues. Specifically, for the set of elements enqueued // by a particular thread and dequeued by a particular thread, the // order in which the elements of this set are dequeued must match // the order these elements were enqueued. // // Concerns: //: 1 If the queue has a single consumer and a single consumer, the //: strong form of the ordering guarantee is provided. //: //: 2 Under normal operation, the weak form of the ordering guarantee //: is provided. // // Plan: //: 1 Using elements that store a sequence number, ensure the dequeued //: elements' sequence number increases by one. (C-1) //: //: 2 Using elements that store a sequence number, ensure the dequeued //: elements' sequence number for the source thread is increasing. //: (C-2) // // Testing: // CONCERN: ordering guarantee // --------------------------------------------------------- if (verbose) cout << endl << "Ordering Guarantee Test" << endl << "=======================" << endl; orderingGuaranteeTest(1, 1); // SPSC orderingGuaranteeTest(4, 1); // MPSC } break; case 11: { // --------------------------------------------------------- // Template Requirements Test // The queue should work for types that have no default // constructor and a 1-arg copy constructor. // // Concerns: //: 1 The queue should work for types that have no default //: constructor and a 1-arg copy constructor. // // Plan: //: 1 Create and exercise a queue using 'TemplateRequirementTestType' //: (C-1) // // Testing: // CONCERN: template requirements // --------------------------------------------------------- if (verbose) cout << endl << "Template Requirements Test" << endl << "==========================" << endl; bdlcc::SingleConsumerQueue<TemplateRequirementTestType> queue(10); int count = 0; { TemplateRequirementTestType t(&count); queue.pushBack(t); TemplateRequirementTestType t2(&count); queue.popFront(&t2); } ASSERT(0 == count); } break; case 10: { // -------------------------------------------------------------------- // Moving Tests // Ensure move-semantics are honored. Note that the testing types // are not universally supported. Move-only type is supported in // C++11 mode. Allocating move-only type is supported in C++11 mode. // 'IncorrectlyMatchingMoveConstructorTestType' works in C++03 mode. // // Concerns: //: 1 The manipulators 'pushBack', 'tryPushBack' 'popFront', and //: 'tryPopFront' honor move-semantics. // // Plan: //: 1 After pushing back a value, verify the value is in moved-from //: state. After popping a value, verify the global moved-from //: counter has increased. (C-1) // // Testing: // int pushBack(bslmf::MovableRef<TYPE> value); // int tryPushBack(bslmf::MovableRef<TYPE> value); // CONCERN: 'popFront' and 'tryPopFront' honor move-semantics // -------------------------------------------------------------------- if (verbose) cout << endl << "Moving Tests" << endl << "============" << endl; typedef bslmf::MovableRefUtil MoveUtil; if (veryVerbose) cout << "Move-only type" << endl; #ifdef BSLMF_MOVABLEREF_USES_RVALUE_REFERENCES // Move-only types are not supported in C++03 mode, only C++11 and // higher. See internal bug report 99039150. { bslma::TestAllocator ta(veryVeryVerbose); bdlcc::SingleConsumerQueue<MoveTester> queue(42, &ta); int moveCtr = 0; queue.pushBack(MoveTester(1, &moveCtr)); ASSERT(1 == moveCtr); moveCtr = 1; MoveTester moveTester2(2, &moveCtr); queue.pushBack(MoveUtil::move(moveTester2)); ASSERT(moveTester2.isMoved()); ASSERT(queue.tryPushBack(MoveTester(3, &moveCtr)) == 0); ASSERT(3 == moveCtr); moveCtr = 3; MoveTester moveTester4(4, &moveCtr); ASSERT(queue.tryPushBack(MoveUtil::move(moveTester4)) == 0); ASSERT(moveTester4.isMoved()); ASSERT(4 == moveCtr); // Test 'popFront', 'tryPopFront' MoveTester popped(42); queue.popFront(&popped); ASSERT(5 == moveCtr); ASSERT(queue.tryPopFront(&popped) == 0); ASSERT(6 == moveCtr); } if (veryVerbose) cout << "Move-only allocating type" << endl; { typedef bsltf::MoveOnlyAllocTestType ValueType; bslma::TestAllocator ta(veryVeryVerbose); bdlcc::SingleConsumerQueue<ValueType> queue(42, &ta); bslma::TestAllocatorMonitor tam(&ta); queue.pushBack(ValueType(1, &ta)); ASSERT(tam.isInUseUp()); tam.reset(); ValueType popped1(&ta); queue.popFront(&popped1); ASSERT(tam.isInUseSame()); ASSERT(popped1.data() == 1); ASSERT(popped1.allocator() == &ta); tam.reset(); ValueType value2(2, &ta); tam.reset(); queue.pushBack(MoveUtil::move(value2)); ASSERT(tam.isInUseSame()); ValueType popped2(&ta); tam.reset(); queue.popFront(&popped2); ASSERT(tam.isInUseDown()); ASSERT(popped2.data() == 2); ASSERT(popped2.allocator() == &ta); ASSERT(queue.tryPushBack(ValueType(3, &ta)) == 0); ASSERT(tam.isInUseSame()); tam.reset(); ValueType popped3(&ta); ASSERT(queue.tryPopFront(&popped3) == 0); ASSERT(tam.isInUseSame()); ASSERT(popped3.data() == 3); ASSERT(popped3.allocator() == &ta); tam.reset(); ValueType value4(4, &ta); tam.reset(); ASSERT(queue.tryPushBack(MoveUtil::move(value4)) == 0); ASSERT(tam.isInUseSame()); ValueType popped4(&ta); queue.popFront(&popped4); ASSERT(tam.isInUseSame()); ASSERT(popped4.data() == 4); ASSERT(popped4.allocator() == &ta); // Test with different allocator for the value bslma::TestAllocator tb(veryVeryVerbose); bslma::TestAllocatorMonitor tbm(&tb); ASSERT(queue.tryPushBack(ValueType(5, &tb)) == 0); ASSERT(tbm.isInUseSame()); tam.reset(); tbm.reset(); ValueType popped5(&tb); ASSERT(queue.tryPopFront(&popped5) == 0); ASSERT(tam.isInUseDown()); // the element in the queue is deleted ASSERT(popped5.data() == 5); ASSERT(popped5.allocator() == &tb); tam.reset(); ValueType value6(6, &ta); tam.reset(); ASSERT(queue.tryPushBack(MoveUtil::move(value6)) == 0); ASSERT(tam.isInUseSame()); ValueType popped6(&ta); queue.popFront(&popped6); ASSERT(tam.isInUseSame()); ASSERT(popped6.data() == 6); ASSERT(popped6.allocator() == &ta); } #endif if (veryVerbose) cout << "Movable allocating type" << endl; { typedef bsltf::MovableAllocTestType ValueType; bslma::TestAllocator ta(veryVeryVerbose); bdlcc::SingleConsumerQueue<ValueType> queue(42, &ta); bslma::TestAllocatorMonitor tam(&ta); #ifdef BSLMF_MOVABLEREF_USES_RVALUE_REFERENCES queue.pushBack(ValueType(1, &ta)); ASSERT(tam.isInUseUp()); tam.reset(); ValueType popped1(&ta); queue.popFront(&popped1); ASSERT(tam.isInUseSame()); ASSERT(popped1.data() == 1); ASSERT(popped1.allocator() == &ta); tam.reset(); #endif ValueType value2(2, &ta); tam.reset(); queue.pushBack(MoveUtil::move(value2)); ASSERT(tam.isInUseSame()); ValueType popped2(&ta); tam.reset(); queue.popFront(&popped2); ASSERT(tam.isInUseDown()); ASSERT(popped2.data() == 2); ASSERT(popped2.allocator() == &ta); #ifdef BSLMF_MOVABLEREF_USES_RVALUE_REFERENCES ASSERT(queue.tryPushBack(ValueType(3, &ta)) == 0); ASSERT(tam.isInUseSame()); tam.reset(); ValueType popped3(&ta); ASSERT(queue.tryPopFront(&popped3) == 0); ASSERT(tam.isInUseSame()); ASSERT(popped3.data() == 3); ASSERT(popped3.allocator() == &ta); tam.reset(); #endif ValueType value4(4, &ta); tam.reset(); ASSERT(queue.tryPushBack(MoveUtil::move(value4)) == 0); ASSERT(tam.isInUseSame()); ValueType popped4(&ta); queue.popFront(&popped4); ASSERT(tam.isInUseSame()); ASSERT(popped4.data() == 4); ASSERT(popped4.allocator() == &ta); // Test with different allocator for the value bslma::TestAllocator tb(veryVeryVerbose); bslma::TestAllocatorMonitor tbm(&tb); ASSERT(queue.tryPushBack(ValueType(5, &tb)) == 0); ASSERT(tbm.isInUseSame()); tam.reset(); tbm.reset(); ValueType popped5(&tb); ASSERT(queue.tryPopFront(&popped5) == 0); ASSERT(tam.isInUseDown()); // the element in the queue is deleted ASSERT(popped5.data() == 5); ASSERT(popped5.allocator() == &tb); tam.reset(); ValueType value6(6, &ta); tam.reset(); ASSERT(queue.tryPushBack(MoveUtil::move(value6)) == 0); ASSERT(tam.isInUseSame()); ValueType popped6(&ta); queue.popFront(&popped6); ASSERT(tam.isInUseSame()); ASSERT(popped6.data() == 6); ASSERT(popped6.allocator() == &ta); } if (veryVerbose) cout << "IncorrectlyMatchingMoveConstructorTestType" << endl; { typedef IncorrectlyMatchingMoveConstructorTestType ValueType; bslma::TestAllocator ta(veryVeryVerbose); bdlcc::SingleConsumerQueue<ValueType> queue(42, &ta); bslma::TestAllocatorMonitor tam(&ta); #ifdef BSLMF_MOVABLEREF_USES_RVALUE_REFERENCES queue.pushBack(ValueType(1)); ASSERT(tam.isInUseSame()); tam.reset(); ValueType popped1; queue.popFront(&popped1); ASSERT(tam.isInUseSame()); ASSERT(popped1.data() == 1); tam.reset(); #endif ValueType value2(2); tam.reset(); queue.pushBack(value2); ASSERT(tam.isInUseSame()); ValueType popped2; queue.popFront(&popped2); ASSERT(tam.isInUseSame()); ASSERT(popped2.data() == 2); #ifdef BSLMF_MOVABLEREF_USES_RVALUE_REFERENCES ASSERT(queue.tryPushBack(ValueType(3)) == 0); ASSERT(tam.isInUseSame()); tam.reset(); ValueType popped3; ASSERT(queue.tryPopFront(&popped3) == 0); ASSERT(tam.isInUseSame()); ASSERT(popped3.data() == 3); tam.reset(); #endif ValueType value4(4); tam.reset(); ASSERT(queue.tryPushBack(value4) == 0); ASSERT(tam.isInUseSame()); ValueType popped4; queue.popFront(&popped4); ASSERT(tam.isInUseSame()); ASSERT(popped4.data() == 4); } } break; case 9: { // -------------------------------------------------------------------- // TESTING 'waitUntilEmpty' // Ensure the accessor functions as expected. // // Concerns: //: 1 The method 'waitUntilEmpty' returns at the appropriate time with //: the expected value. //: //: 2 The accessor method is declared 'const'. //: //: 3 The accessor does not allocate any memory. // // Plan: //: 1 Create objects and set their state using 'pushBack'. Schedule a //: deferred 'popFront' or 'disablePopFront' on a created thread. //: Invoke 'waitUntilEmpty', verify when the accessor returns and //: the returned value. (C-1) //: //: 2 The accessor will only be accessed from a 'const' reference to //: the created object. (C-2) //: //: 3 The default allocator will be used for all created objects //: (excluding those used to test 'allocator') and the number of //: allocation will be verified to ensure that no memory was //: allocated during use of the accessor. (C-3) // // Testing: // int waitUntilEmpty(); // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING 'waitUntilEmpty'" << endl << "========================" << endl; if (verbose) cout << "\nTesting 'waitUntilEmpty'." << endl; { bslmt::ThreadUtil::Handle watchdogHandle; s_continue = 1; bslmt::ThreadUtil::create(&watchdogHandle, watchdog, const_cast<char *>("wait until empty")); Obj mX; const Obj& X = mX; bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); int rv = X.waitUntilEmpty(); ASSERT(e_SUCCESS == rv); ASSERT(allocations == defaultAllocator.numAllocations()); s_continue = 0; bslmt::ThreadUtil::join(watchdogHandle); } { bslmt::ThreadUtil::Handle watchdogHandle; s_continue = 1; bslmt::ThreadUtil::create(&watchdogHandle, watchdog, const_cast<char *>("wait until empty")); Obj mX; const Obj& X = mX; bslmt::ThreadUtil::Handle handle; bslmt::ThreadUtil::create(&handle, deferredPopFront, &mX); mX.pushBack(0); bsls::TimeInterval interval = bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME); bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); int rv = X.waitUntilEmpty(); ASSERT(e_SUCCESS == rv); ASSERT(allocations == defaultAllocator.numAllocations()); interval = bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME) - interval; ASSERT( bsls::TimeInterval(0.8) <= interval && bsls::TimeInterval(1.5) >= interval); bslmt::ThreadUtil::join(handle); s_continue = 0; bslmt::ThreadUtil::join(watchdogHandle); } { bslmt::ThreadUtil::Handle watchdogHandle; s_continue = 1; bslmt::ThreadUtil::create(&watchdogHandle, watchdog, const_cast<char *>("wait until empty")); Obj mX; const Obj& X = mX; bslmt::ThreadUtil::Handle handle; bslmt::ThreadUtil::create(&handle, deferredDisablePopFront, &mX); mX.pushBack(0); bsls::TimeInterval interval = bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME); bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); int rv = X.waitUntilEmpty(); ASSERT(e_DISABLED == rv); ASSERT(allocations == defaultAllocator.numAllocations()); interval = bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME) - interval; ASSERT( s_deferredPopFrontInterval.totalSecondsAsDouble() * 0.8 <= interval.totalSecondsAsDouble() && s_deferredPopFrontInterval.totalSecondsAsDouble() * 1.5 >= interval.totalSecondsAsDouble()); bslmt::ThreadUtil::join(handle); s_continue = 0; bslmt::ThreadUtil::join(watchdogHandle); } } break; case 8: { // -------------------------------------------------------------------- // TESTING 'tryPopFront' // Ensure the manipulator functions as expected. // // Concerns: //: 1 The method 'tryPopFront' produces the expected value, does not //: affect allocated memory, and is exception neutral with respect to //: memory allocation. //: //: 2 The method 'tryPopFront' does not block, the argument is not //: modified, and the return value appropriately indicates whether //: the method failed to pop an element. //: //: 3 Memory is not leaked by any method and the destructor properly //: deallocates the residual allocated memory. // // Plan: //: 1 Create objects using the 'bslma::TestAllocator', use 'pushBack' //: to obtain various states, use 'tryPopFront', verify the returned //: value, and that objects have a reduced length but unchanged //: capacity. Also vary the test allocator's allocation limit to //: verify behavior in the presence of exceptions. (C-1) //: //: 2 Use 'tryPopFront' on empty objects, verify the argument is //: unmodified and the return value indicates failure. //: //: 3 Use a supplied 'bslma::TestAllocator' that goes out-of-scope //: at the conclusion of each test to ensure all memory is returned //: to the allocator. (C-3) // // Testing: // int tryPopFront(TYPE *value); // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING 'tryPopFront'" << endl << "=====================" << endl; if (verbose) cout << "\nTesting 'tryPopFront'." << endl; { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); Obj mX(&sa); const Obj& X = mX; int value; int rv; value = 7; rv = mX.tryPopFront(&value); ASSERT(e_EMPTY == rv); ASSERT( 0 == X.numElements()); ASSERT( 7 == value); value = 3; rv = mX.tryPopFront(&value); ASSERT(e_EMPTY == rv); ASSERT( 0 == X.numElements()); ASSERT( 3 == value); mX.pushBack(0); mX.pushBack(1); mX.pushBack(2); ASSERT(3 == X.numElements()); bsls::Types::Int64 na = sa.numAllocations(); bsls::Types::Int64 nd = sa.numDeallocations(); rv = mX.tryPopFront(&value); ASSERT(e_SUCCESS == rv); ASSERT( 2 == X.numElements()); ASSERT( 0 == value); ASSERT( na == sa.numAllocations()); ASSERT( nd == sa.numDeallocations()); rv = mX.tryPopFront(&value); ASSERT(e_SUCCESS == rv); ASSERT( 1 == X.numElements()); ASSERT( 1 == value); ASSERT( na == sa.numAllocations()); ASSERT( nd == sa.numDeallocations()); rv = mX.tryPopFront(&value); ASSERT(e_SUCCESS == rv); ASSERT( 0 == X.numElements()); ASSERT( 2 == value); ASSERT( na == sa.numAllocations()); ASSERT( nd == sa.numDeallocations()); rv = mX.tryPopFront(&value); ASSERT(e_EMPTY == rv); ASSERT( 0 == X.numElements()); ASSERT( 2 == value); ASSERT( na == sa.numAllocations()); ASSERT( nd == sa.numDeallocations()); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); ASSERT( 3 == X.numElements()); ASSERT(na == sa.numAllocations()); ASSERT(nd == sa.numDeallocations()); ASSERT(allocations == defaultAllocator.numAllocations()); } #ifdef BDE_BUILD_TARGET_EXC { bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); bdlcc::SingleConsumerQueue<AllocExceptionHelper> mX(&sa); const bdlcc::SingleConsumerQueue<AllocExceptionHelper>& X = mX; AllocExceptionHelper value(&sa); bsls::Types::Int64 na = sa.numAllocations(); bsls::Types::Int64 nd = sa.numDeallocations(); mX.pushBack(value); mX.pushBack(value); ASSERT( 2 == X.numElements()); ASSERT(na + 3 == sa.numAllocations()); ASSERT(nd == sa.numDeallocations()); int numException = 0; sa.setAllocationLimit(0); try { mX.tryPopFront(&value); } catch (BloombergLP::bslma::TestAllocatorException& e) { ++numException; } sa.setAllocationLimit(-1); ASSERT(1 == numException); ASSERT(1 == X.numElements()); // The test allocator increments the number of allocations and then // throws the exception. ASSERT(na + 4 == sa.numAllocations()); ASSERT(nd + 1 == sa.numDeallocations()); mX.tryPopFront(&value); ASSERT(na + 5 == sa.numAllocations()); ASSERT(nd + 3 == sa.numDeallocations()); ASSERT(0 == X.numElements()); mX.pushBack(value); ASSERT(1 == X.numElements()); // Since the queue is empty, only the element should have // allocated. ASSERT(na + 6 == sa.numAllocations()); ASSERT(nd + 3 == sa.numDeallocations()); } #endif } break; case 7: { // -------------------------------------------------------------------- // TESTING 'tryPushBack' // Ensure the manipulators forwards correctly. // // Concerns: //: 1 The manipulators forward their argument to 'pushBack' correctly. //: //: 2 The return value is propogated. // // Plan: //: 1 Create an object and use 'tryPushBack' to modify the object's //: value. Verify the state of the object using the basic accessors //: and 'popFront'. (C-1) //: //: 2 Verify the return value of 'tryPushBack' before and after use of //: 'disablePushBack'. (C-2) // // Testing: // int tryPushBack(const TYPE& value); // int tryPushBack(bslmf::MovableRef<TYPE> value); // -------------------------------------------------------------------- if (verbose) cout << endl << "TESTING 'tryPushBack'" << endl << "=====================" << endl; if (verbose) cout << "\nTesting 'tryPushBack(const TYPE&)'." << endl; { Obj mX; const Obj& X = mX; ASSERT(0 == X.numElements()); int rv; rv = mX.tryPushBack(0); ASSERT(e_SUCCESS == rv); ASSERT( 1 == X.numElements()); rv = mX.tryPushBack(1); ASSERT(e_SUCCESS == rv); ASSERT( 2 == X.numElements()); int value; mX.popFront(&value); ASSERT(0 == value); mX.popFront(&value); ASSERT(1 == value); mX.disablePushBack(); rv = mX.tryPushBack(0); ASSERT(e_DISABLED == rv); ASSERT( 0 == X.numElements()); } if (verbose) { cout << "\nTesting 'tryPushBack(bslmf::MovableRef<TYPE>)'." << endl; } #ifdef BSLMF_MOVABLEREF_USES_RVALUE_REFERENCES { bdlcc::SingleConsumerQueue<MoveTester> mX; const bdlcc::SingleConsumerQueue<MoveTester>& X = mX; ASSERT(0 == X.numElements()); int rv; int moveCtr = 0; rv = mX.tryPushBack(MoveTester(0, &moveCtr)); ASSERT(e_SUCCESS == rv); ASSERT( 1 == X.numElements()); ASSERT( 1 == moveCtr); rv = mX.tryPushBack(MoveTester(1, &moveCtr)); ASSERT(e_SUCCESS == rv); ASSERT( 2 == X.numElements()); ASSERT( 2 == moveCtr); MoveTester value(-1); mX.popFront(&value); ASSERT(0 == value.value()); ASSERT(3 == moveCtr); mX.popFront(&value); ASSERT(1 == value.value()); ASSERT(4 == moveCtr); mX.disablePushBack(); rv = mX.tryPushBack(MoveTester(0, &moveCtr)); ASSERT(e_DISABLED == rv); ASSERT( 0 == X.numElements()); ASSERT( 4 == moveCtr); } #endif } break; case 6: { // -------------------------------------------------------------------- // ENABLE/DISABLE ENQUEUE/DEQUEUE // Ensure the manipulators and associated accessors for enabling and // disabling enqueueing and dequeueing work as expected. // // Concerns: //: 1 Each manipulator appropriated changes the state of the object. //: //: 2 Each accessor returns the value of the corresponding attribute of //: the object. //: //: 3 Each accessor method is declared 'const'. //: //: 4 No accessor allocates any memory. //: //: 5 The behavior of the associated enqueueing and dequeueing methods //: is correctly modified. //: //: 6 Blocked threads are released as appropriate. // // Plan: //: 1 Create an object and directly modify the state. Verify the state //: changes through use of the accessors. (C-1,2) //: //: 2 The accessors will only be accessed from a 'const' reference to //: the created object. (C-3) //: //: 3 The default allocator will be used for all created objects //: (excluding those used to test 'allocator') and the number of //: allocation will be verified to ensure that no memory was //: allocated during use of the accessors. (C-4) //: //: 4 Create an object and directly verify the effect on the methods //: 'waitUntilEmpty', 'popFront', and 'pushBack', as well as their //: return values. (C-5) //: //: 5 Create objects and cause threads to block on the 'waitUntilEmpty' //: and 'popFront' methods. Verify the threads are released, with //: appropriate return value, upon disabling the relevant //: functionality. (C-6) // // Testing: // void disablePopFront(); // void disablePushBack(); // void enablePopFront(); // void enablePushBack(); // bool isPopFrontDisabled() const; // bool isPushBackDisabled() const; // -------------------------------------------------------------------- if (verbose) cout << endl << "ENABLE/DISABLE ENQUEUE/DEQUEUE" << endl << "==============================" << endl; if (verbose) cout << "\nTesting basic functionality." << endl; { Obj mX; const Obj& X = mX; ASSERT(&defaultAllocator == X.allocator()); bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); ASSERT(!X.isPopFrontDisabled()); ASSERT(!X.isPushBackDisabled()); mX.disablePopFront(); ASSERT( X.isPopFrontDisabled()); ASSERT(!X.isPushBackDisabled()); mX.disablePushBack(); ASSERT( X.isPopFrontDisabled()); ASSERT( X.isPushBackDisabled()); mX.enablePopFront(); ASSERT(!X.isPopFrontDisabled()); ASSERT( X.isPushBackDisabled()); mX.enablePushBack(); ASSERT(!X.isPopFrontDisabled()); ASSERT(!X.isPushBackDisabled()); ASSERT(defaultAllocator.numAllocations() == allocations); } if (verbose) cout << "\nTesting effect on other methods." << endl; { Obj mX; const Obj& X = mX; int rv; rv = mX.pushBack(0); ASSERT(e_SUCCESS == rv); ASSERT( 1 == X.numElements()); mX.disablePopFront(); mX.disablePushBack(); rv = X.waitUntilEmpty(); ASSERT(e_DISABLED == rv); ASSERT( 1 == X.numElements()); int value = 7; rv = mX.popFront(&value); ASSERT(e_DISABLED == rv); ASSERT( 7 == value); ASSERT( 1 == X.numElements()); rv = mX.pushBack(0); ASSERT(e_DISABLED == rv); ASSERT( 1 == X.numElements()); } } break; case 5: { // -------------------------------------------------------------------- // INITIAL CAPACITY CONSTRUCTOR // The initial capacity constructor operates as expected. // // Concerns: //: 1 The constructor creates the correct initial value and has the //: internal memory management system hooked up properly so that //: *all* internally allocated memory draws from the same //: user-supplied allocator whenever one is specified. //: //: 2 An allocation excepetion during construction results in a valid //: object. //: //: 3 Memory is not leaked by the constructor and the destructor //: properly deallocates the residual allocated memory. // // Plan: //: 1 Create an object using the constructor with and without passing //: in an allocator, verify the allocator is stored using the //: 'allocator' accessor, and verifying all allocations are done from //: the allocator by using 'pushBack' to exceed the requested //: capacity. (C-1) //: //: 2 Create objects using the 'bslma::TestAllocator'. Vary the test //: allocator's allocation limit to verify behavior in the presence //: of exceptions. (C-2) //: //: 3 Use a supplied 'bslma::TestAllocator' the goes out-of-scope //: at the conclusion of each test to ensure all memory is returned //: to the allocator. (C-3) // // Testing: // SingleConsumerQueue(capacity, *bA = 0); // -------------------------------------------------------------------- if (verbose) cout << endl << "INITIAL CAPACITY CONSTRUCTOR" << endl << "============================" << endl; if (verbose) cout << "\nTesting with various allocator configurations." << endl; { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); Obj mX(1); const Obj& X = mX; ASSERT(&defaultAllocator == X.allocator()); ASSERT( 0 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT( 1 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT( 2 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT( 3 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); } { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); Obj mX(3, reinterpret_cast<bslma::TestAllocator *>(0)); const Obj& X = mX; ASSERT(&defaultAllocator == X.allocator()); ASSERT( 0 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT( 1 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT( 2 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT( 3 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT( 4 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); } { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); Obj mX(2, &sa); const Obj& X = mX; ASSERT(&sa == X.allocator()); ASSERT( 0 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT( 1 == sa.numAllocations()); mX.pushBack(0); ASSERT( 1 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT( 1 == sa.numAllocations()); mX.pushBack(0); ASSERT( 2 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT( 1 == sa.numAllocations()); mX.pushBack(0); ASSERT( 3 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT( 2 == sa.numAllocations()); } if (verbose) cout << "\nTesting exception behavior." << endl; { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(sa) { Obj mX(10, &sa); const Obj& X = mX; ASSERT(0 == X.numElements()); } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END ASSERT(allocations == defaultAllocator.numAllocations()); } } break; case 4: { // -------------------------------------------------------------------- // BASIC ACCESSORS // Ensure each basic accessor properly interprets object state. // // Concerns: //: 1 Each accessor returns the value of the corresponding attribute of //: the object. //: //: 2 Each accessor method is declared 'const'. //: //: 3 No accessor allocates any memory. // // Plan: //: 1 To test 'allocator', create object with various allocators and //: ensure the returned value matches the supplied allocator. //: //: 2 Use the generator function to produce objects of arbitrary state //: and verify the accessor's return value against expected values. //: (C-1) //: //: 3 The accessors will only be accessed from a 'const' reference to //: the created object. (C-2) //: //: 4 The default allocator will be used for all created objects //: (excluding those used to test 'allocator') and the number of //: allocation will be verified to ensure that no memory was //: allocated during use of the accessors. (C-3) // // Testing: // bslma::Allocator *allocator() const; // bool isEmpty() const; // bool isFull() const; // bsl::size_t numElements() const; // -------------------------------------------------------------------- if (verbose) cout << endl << "BASIC ACCESSORS" << endl << "===============" << endl; if (verbose) cout << "\nTesting 'allocator'." << endl; { Obj mX; const Obj& X = mX; ASSERT(&defaultAllocator == X.allocator()); } { Obj mX(reinterpret_cast<bslma::TestAllocator *>(0)); const Obj& X = mX; ASSERT(&defaultAllocator == X.allocator()); } { bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); Obj mX(&sa); const Obj& X = mX; ASSERT(&sa == X.allocator()); } if (verbose) cout << "\nTesting residual accessors." << endl; { static const struct { int d_lineNum; // source line number const char *d_spec_p; // specification string bsl::size_t d_numElement; // expected length } DATA[] = { //line spec ne //---- ------------------- -- { L_, "", 0 }, { L_, "a", 1 }, { L_, "aa", 2 }, { L_, "aaa", 3 }, { L_, "b", 1 }, { L_, "bb", 2 }, { L_, "bbb", 3 }, { L_, "aaab", 4 }, { L_, "aaba", 4 }, { L_, "abaa", 4 }, { L_, "baaa", 4 }, { L_, "abcabcabc", 9 }, { L_, "cbaabcbac", 9 }, { L_, "a~", 0 }, { L_, "aa~~", 0 }, { L_, "aab~", 0 }, { L_, "aba~a", 1 }, { L_, "aba~ab", 2 }, { L_, "aba~aba", 3 }, { L_, "aba~aba~", 0 }, }; const int NUM_DATA = static_cast<int>(sizeof DATA / sizeof *DATA); for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const char *const SPEC = DATA[ti].d_spec_p; const bsl::size_t NE = DATA[ti].d_numElement; Obj mX; const Obj& X = gg(&mX, SPEC); bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); LOOP_ASSERT(LINE, NE == X.numElements()); LOOP_ASSERT(LINE, (0 == NE) == X.isEmpty()); LOOP_ASSERT(LINE, false == X.isFull()); LOOP_ASSERT(LINE, defaultAllocator.numAllocations() == allocations); } } } break; case 3: { // -------------------------------------------------------------------- // PRIMITIVE GENERATOR FUNCTIONS // Ensure that the generator functions are able to create an object // in any state. // // Concerns: //: 1 Valid syntax produces the expected results. //: //: 2 Invalid syntax is detected and reported. // // Plan: //: 1 Evaluate a series of test strings of increasing complexity to //: set the state of a newly created object and verify the returned //: object using basic accessors and 'popFront'. (C-1) //: //: 2 Evaluate the 'ggg' function with a series of test strings of //: increasing complexity and verify its return value. (C-2) // // Testing: // Obj& gg(Obj *object, const char *spec); // int ggg(Obj *object, const char *spec); // -------------------------------------------------------------------- if (verbose) cout << endl << "PRIMITIVE GENERATOR FUNCTIONS" << endl << "=============================" << endl; if (verbose) cout << "\nTesting generator on valid specs." << endl; { static const struct { int d_lineNum; // source line number const char *d_spec_p; // specification string const char *d_exp_p; // expected value string } DATA[] = { //line spec expected //---- ------------------- -------------- { L_, "", "" }, { L_, "a", "a" }, { L_, "aa", "aa" }, { L_, "aaa", "aaa" }, { L_, "b", "b" }, { L_, "bb", "bb" }, { L_, "bbb", "bbb" }, { L_, "aaab", "aaab" }, { L_, "aaba", "aaba" }, { L_, "abaa", "abaa" }, { L_, "baaa", "baaa" }, { L_, "abcabcabc", "abcabcabc" }, { L_, "cbaabcbac", "cbaabcbac" }, { L_, "a~", "" }, { L_, "aa~~", "" }, { L_, "aab~", "" }, { L_, "aba~a", "a" }, { L_, "aba~ab", "ab" }, { L_, "aba~aba", "aba" }, { L_, "aba~aba~", "" } }; const int NUM_DATA = static_cast<int>(sizeof DATA / sizeof *DATA); for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const char *const SPEC = DATA[ti].d_spec_p; const char *const EXP = DATA[ti].d_exp_p; const bsl::size_t LEN = strlen(EXP); if (veryVerbose) { P_(LINE) P_(SPEC) P(EXP) } Obj mX; const Obj& X = gg(&mX, SPEC); // original spec LOOP_ASSERT(LINE, LEN == X.numElements()); for (bsl::size_t i = 0; i < LEN; i++) { Obj::value_type value; int rv = mX.popFront(&value); ASSERT(e_SUCCESS == rv); if (veryVerbose) { T_ P_(EXP[i]) P(value) } Obj::value_type expValue; getValue(&expValue, EXP[i], 0); LOOP_ASSERT(LINE, expValue == value); } } } if (verbose) cout << "\nTesting generator on invalid specs." << endl; { static const struct { int d_lineNum; // source line number const char *d_spec_p; // specification string int d_index; // offending character index } DATA[] = { //line spec index //---- ------------- ----- { L_, "", -1, }, // control { L_, "a", -1, }, // control { L_, " ", 0, }, { L_, ".", 0, }, { L_, "2", 0, }, { L_, "ab", -1, }, // control { L_, " a", 0, }, { L_, ".a", 0, }, { L_, "2a", 0, }, { L_, "a ", 1, }, { L_, "a.", 1, }, { L_, "a2", 1, }, { L_, "abc", -1, }, // control { L_, " bc", 0, }, { L_, ".bc", 0, }, { L_, "2bc", 0, }, { L_, "b c", 1, }, { L_, "b.c", 1, }, { L_, "b2c", 1, }, { L_, "bc ", 2, }, { L_, "bc.", 2, }, { L_, "bc2", 2, }, }; const int NUM_DATA = static_cast<int>(sizeof DATA / sizeof *DATA); for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const char *const SPEC = DATA[ti].d_spec_p; const int INDEX = DATA[ti].d_index; if (veryVerbose) { P_(SPEC) P(INDEX) } { Obj mX; int result = ggg(&mX, SPEC, veryVerbose); LOOP_ASSERT(LINE, INDEX == result); } } } } break; case 2: { // -------------------------------------------------------------------- // PRIMARY MANIPULATORS TEST // The basic concern is that the default constructor, the destructor, // 'popFront', and the primary manipulators: // - pushBack // - removeAll // operate as expected. // // Concerns: //: 1 The default constructor creates the correct initial value and has //: the internal memory management system hooked up properly so that //: *all* internally allocated memory draws from the same //: user-supplied allocator whenever one is specified. //: //: 2 The method 'pushBack' produces the expected value, increases //: capacity as needed, and is exception neutral with respect to //: memory allocation. //: //: 3 The method 'removeAll' produces the expected value (empty) and //: does not affect allocated memory. //: //: 4 The method 'popFront' produces the expected value, does not //: affect allocated memory, and is exception neutral with respect to //: memory allocation. //: //: 5 Memory is not leaked by any method and the destructor properly //: deallocates the residual allocated memory. // // Plan: //: 1 Create an object using the default constructor with and without //: passing in an allocator, verify the allocator is stored using the //: (untested) 'allocator' accessor, and verifying all allocations //: are done from the allocator in future tests. //: //: 2 Create objects using the //: 'bslma::TestAllocator', use the 'pushBack' method with various //: values, and the (untested) accessors to verify the value of the //: object and that allocation occurred when expected. Also vary the //: test allocator's allocation limit to verify behavior in the //: presence of exceptions. (C-1,2) //: //: 3 Create objects using the 'bslma::TestAllocator', use 'pushBack' //: to obtain various states, use 'removeAll', verify the objects are //: empty, then repopulate the objects and ensure no allocation //: occurs. (C-3) //: //: 4 Create objects using the 'bslma::TestAllocator', use 'pushBack' //: to obtain various states, use 'popFront', verify the objects have //: a reduced length but unchanged capacity. Also vary the test //: allocator's allocation limit to verify behavior in the presence //: of exceptions. (C-4) //: //: 5 Use a supplied 'bslma::TestAllocator' that goes out-of-scope //: at the conclusion of each test to ensure all memory is returned //: to the allocator. (C-5) // // Testing: // SingleConsumerQueue(bslma::Allocator *basicAllocator = 0); // ~SingleConsumerQueue(); // int pushBack(const TYPE& value); // int popFront(TYPE *value); // void removeAll(); // CONCERN: 0 == e_SUCCESS // -------------------------------------------------------------------- if (verbose) cout << endl << "PRIMARY MANIPULATORS TEST" << endl << "=========================" << endl; ASSERT(0 == Obj::e_SUCCESS); bsl::string longString; { longString = "abc"; for (bsl::size_t i = 0; i < sizeof(bsl::string); ++i) { longString += " "; } } if (verbose) cout << "\nTesting with various allocator configurations." << endl; { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); Obj mX; const Obj& X = mX; ASSERT(&defaultAllocator == X.allocator()); ASSERT(0 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT(1 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT(2 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT(3 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); } { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); Obj mX(reinterpret_cast<bslma::TestAllocator *>(0)); const Obj& X = mX; ASSERT(&defaultAllocator == X.allocator()); ASSERT(0 == X.numElements()); ASSERT(allocations + 1 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT(1 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT(2 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); mX.pushBack(0); ASSERT(3 == X.numElements()); ASSERT(allocations + 2 == defaultAllocator.numAllocations()); } { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); Obj mX(&sa); const Obj& X = mX; ASSERT(&sa == X.allocator()); ASSERT(0 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(1 == sa.numAllocations()); mX.pushBack(0); ASSERT(1 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(2 == sa.numAllocations()); mX.pushBack(0); ASSERT(2 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(2 == sa.numAllocations()); mX.pushBack(0); ASSERT(3 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(2 == sa.numAllocations()); } { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); AllocObj mX(&sa); const AllocObj& X = mX; ASSERT(&sa == X.allocator()); ASSERT(0 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(1 == sa.numAllocations()); mX.pushBack(longString); ASSERT(1 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(3 == sa.numAllocations()); mX.pushBack(longString); ASSERT(2 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(4 == sa.numAllocations()); mX.pushBack(longString); ASSERT(3 == X.numElements()); ASSERT(allocations == defaultAllocator.numAllocations()); ASSERT(5 == sa.numAllocations()); } if (verbose) cout << "\nTesting 'pushBack'." << endl; { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(sa) { Obj mX(&sa); const Obj& X = mX; ASSERT(0 == X.numElements()); for (int i = 1; i <= 10; ++i) { mX.pushBack(i); ASSERT(static_cast<bsl::size_t>(i) == X.numElements()); } } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END ASSERT(allocations == defaultAllocator.numAllocations()); } { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); BSLMA_TESTALLOCATOR_EXCEPTION_TEST_BEGIN(sa) { AllocObj mX(&sa); const AllocObj& X = mX; ASSERT(0 == X.numElements()); for (int i = 1; i <= 10; ++i) { mX.pushBack(longString); ASSERT(static_cast<bsl::size_t>(i) == X.numElements()); } } BSLMA_TESTALLOCATOR_EXCEPTION_TEST_END ASSERT(allocations == defaultAllocator.numAllocations()); } if (verbose) cout << "\nTesting 'removeAll'." << endl; { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); Obj mX(&sa); const Obj& X = mX; mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); ASSERT( 9 == X.numElements()); bsls::Types::Int64 na = sa.numAllocations(); bsls::Types::Int64 nd = sa.numDeallocations(); mX.removeAll(); ASSERT( 0 == X.numElements()); ASSERT(na == sa.numAllocations()); ASSERT(nd == sa.numDeallocations()); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); ASSERT( 9 == X.numElements()); ASSERT(na == sa.numAllocations()); ASSERT(nd == sa.numDeallocations()); ASSERT(allocations == defaultAllocator.numAllocations()); } if (verbose) cout << "\nTesting 'popFront'." << endl; { bsls::Types::Int64 allocations = defaultAllocator.numAllocations(); bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); Obj mX(&sa); const Obj& X = mX; mX.pushBack(0); mX.pushBack(1); mX.pushBack(2); mX.pushBack(3); mX.pushBack(4); mX.pushBack(5); mX.pushBack(6); mX.pushBack(7); mX.pushBack(8); ASSERT( 9 == X.numElements()); bsls::Types::Int64 na = sa.numAllocations(); bsls::Types::Int64 nd = sa.numDeallocations(); int value; int rv; rv = mX.popFront(&value); ASSERT(e_SUCCESS == rv); ASSERT( 8 == X.numElements()); ASSERT( 0 == value); ASSERT( na == sa.numAllocations()); ASSERT( nd == sa.numDeallocations()); rv = mX.popFront(&value); ASSERT(e_SUCCESS == rv); ASSERT( 7 == X.numElements()); ASSERT( 1 == value); ASSERT( na == sa.numAllocations()); ASSERT( nd == sa.numDeallocations()); rv = mX.popFront(&value); ASSERT(e_SUCCESS == rv); ASSERT( 6 == X.numElements()); ASSERT( 2 == value); ASSERT( na == sa.numAllocations()); ASSERT( nd == sa.numDeallocations()); mX.pushBack(0); mX.pushBack(0); mX.pushBack(0); ASSERT( 9 == X.numElements()); ASSERT(na == sa.numAllocations()); ASSERT(nd == sa.numDeallocations()); ASSERT(allocations == defaultAllocator.numAllocations()); } #ifdef BDE_BUILD_TARGET_EXC { bslma::TestAllocator sa("supplied", veryVeryVeryVerbose); bdlcc::SingleConsumerQueue<AllocExceptionHelper> mX(&sa); const bdlcc::SingleConsumerQueue<AllocExceptionHelper>& X = mX; AllocExceptionHelper value(&sa); bsls::Types::Int64 na = sa.numAllocations(); bsls::Types::Int64 nd = sa.numDeallocations(); mX.pushBack(value); mX.pushBack(value); ASSERT( 2 == X.numElements()); ASSERT(na + 3 == sa.numAllocations()); ASSERT(nd == sa.numDeallocations()); int numException = 0; sa.setAllocationLimit(0); try { mX.popFront(&value); } catch (BloombergLP::bslma::TestAllocatorException& e) { ++numException; } sa.setAllocationLimit(-1); ASSERT(1 == numException); // The test allocator increments the number of allocations and then // throws the exception. ASSERT( 1 == X.numElements()); ASSERT(na + 4 == sa.numAllocations()); ASSERT(nd + 1 == sa.numDeallocations()); mX.popFront(&value); ASSERT(na + 5 == sa.numAllocations()); ASSERT(nd + 3 == sa.numDeallocations()); ASSERT(0 == X.numElements()); mX.pushBack(value); ASSERT(1 == X.numElements()); // Since the queue is empty, only the element should have // allocated. ASSERT(na + 6 == sa.numAllocations()); ASSERT(nd + 3 == sa.numDeallocations()); } #endif } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // This case exercises (but does not fully test) basic functionality. // // Concerns: //: 1 The class is sufficiently functional to enable comprehensive //: testing in subsequent test cases. // // Plan: //: 1 Instantiate an object and verify basic functionality. (C-1) // // Testing: // BREATHING TEST // -------------------------------------------------------------------- if (verbose) cout << endl << "BREATHING TEST" << endl << "==============" << endl; Obj mX; const Obj& X = mX; ASSERT(0 == X.numElements()); mX.pushBack(1); ASSERT(1 == X.numElements()); mX.pushBack(2); ASSERT(2 == X.numElements()); mX.pushBack(3); ASSERT(3 == X.numElements()); int v; mX.popFront(&v); ASSERT(1 == v); ASSERT(2 == X.numElements()); mX.popFront(&v); ASSERT(2 == v); ASSERT(1 == X.numElements()); mX.popFront(&v); ASSERT(3 == v); ASSERT(0 == X.numElements()); } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } // CONCERN: In no case does memory come from the global allocator. LOOP_ASSERT(globalAllocator.numBlocksTotal(), 0 == globalAllocator.numBlocksTotal()); if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2019 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
{ "content_hash": "874ee6916a54866ef87130ff297af3d8", "timestamp": "", "source": "github", "line_count": 2600, "max_line_length": 79, "avg_line_length": 34.95076923076923, "alnum_prop": 0.4973149044810283, "repo_name": "bloomberg/bde", "id": "488bb4c5950f1aa0e682e3f0b66b80ff036308ea", "size": "91774", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "groups/bdl/bdlcc/bdlcc_singleconsumerqueue.t.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "34049" }, { "name": "C++", "bytes": "125637725" }, { "name": "CMake", "bytes": "10148" }, { "name": "Makefile", "bytes": "6304" }, { "name": "Perl", "bytes": "385392" }, { "name": "Python", "bytes": "20929" }, { "name": "Roff", "bytes": "65678" }, { "name": "Shell", "bytes": "12076" } ], "symlink_target": "" }
#ifndef _EFI_BS_SERIAL_STATUS_CODE_LIB_H_ #define _EFI_BS_SERIAL_STATUS_CODE_LIB_H_ // // Statements that include other files // #include "Tiano.h" // // Initialization function // VOID EFIAPI BsSerialInitializeStatusCode ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) ; // // Status code reporting function // EFI_STATUS EFIAPI BsSerialReportStatusCode ( IN EFI_STATUS_CODE_TYPE CodeType, IN EFI_STATUS_CODE_VALUE Value, IN UINT32 Instance, IN EFI_GUID * CallerId, IN EFI_STATUS_CODE_DATA * Data OPTIONAL ) ; #endif
{ "content_hash": "080334478810d25ef6275660e2fe7257", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 45, "avg_line_length": 17.02777777777778, "alnum_prop": 0.6557911908646004, "repo_name": "bitcrystal/edk", "id": "88a64872f194a6b66935fd0e7239d5637979bcfa", "size": "1472", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Sample/Platform/Generic/RuntimeDxe/StatusCode/Lib/Include/BsSerialStatusCodeLib.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "959602" }, { "name": "Batchfile", "bytes": "60476" }, { "name": "C", "bytes": "18423335" }, { "name": "C++", "bytes": "938859" }, { "name": "GAP", "bytes": "256118" }, { "name": "Makefile", "bytes": "172033" }, { "name": "Objective-C", "bytes": "2896732" } ], "symlink_target": "" }