answer
stringlengths
15
1.25M
#include "ppapi/thunk/common.h" #include "base/bind.h" #include "base/message_loop.h" #include "ppapi/c/pp_errors.h" namespace ppapi { namespace thunk { int32_t MayForceCallback(<API key> callback, int32_t result) { if (result == <API key>) return result; if (callback.func == NULL || (callback.flags & <API key>) != 0) return result; // TODO(polina): make this work off the main thread as well // (At this point this should not be an issue because PPAPI is only supported // on the main thread). MessageLoop::current()->PostTask(FROM_HERE, base::Bind( callback.func, callback.user_data, result)); return <API key>; } } // namespace thunk } // namespace ppapi
static const char LIBPROJ_ID[] = "Id"; #define PROJ_LIB__ #include <lib_proj.h> PROJ_HEAD(putp2, "Putnins P2") "\n\tPCyl., Sph."; #define C_x 1.89490 #define C_y 1.71848 #define C_p 0.6141848493043784 #define EPS 1e-10 #define NITER 10 #define PI_DIV_3 1.0471975511965977 FORWARD(s_forward); /* spheroid */ double p, c, s, V; int i; (void) P; /* avoid warning */ p = C_p * sin(lp.phi); s = lp.phi * lp.phi; lp.phi *= 0.615709 + s * ( 0.00909953 + s * 0.0046292 ); for (i = NITER; i ; --i) { c = cos(lp.phi); s = sin(lp.phi); lp.phi -= V = (lp.phi + s * (c - 1.) - p) / (1. + c * (c - 1.) - s * s); if (fabs(V) < EPS) break; } if (!i) lp.phi = lp.phi < 0 ? - PI_DIV_3 : PI_DIV_3; xy.x = C_x * lp.lam * (cos(lp.phi) - 0.5); xy.y = C_y * sin(lp.phi); return (xy); } INVERSE(s_inverse); /* spheroid */ double c; (void) P; /* avoid warning */ lp.phi = proj_asin(xy.y / C_y); lp.lam = xy.x / (C_x * ((c = cos(lp.phi)) - 0.5)); lp.phi = proj_asin((lp.phi + sin(lp.phi) * (c - 1.)) / C_p); return (lp); } FREEUP; if (P) free(P); } ENTRY0(putp2) P->es = 0.; P->inv = s_inverse; P->fwd = s_forward; ENDENTRY(P) /* ** Log: proj_putp2.c ** Revision 3.1 2006/01/11 01:38:18 gie ** Initial ** */
# modification, are permitted provided that the following conditions are # met: # the distribution. # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import functools import IECore import Gaffer import GafferUI # Public methods ## May be called to connect the DotUI functionality to an application # instance. This isn't done automatically because some applications # may have graphs for which it doesn't make sense to use Dots. Typically # this function would be called from an application startup file. def connect( applicationRoot ) : applicationRoot.__dotUIConnected = True # Metadata Gaffer.Metadata.<API key>( Gaffer.Dot, """A utility node which can be used for organising large graphs.""", ) Gaffer.Metadata.registerNodeValue( Gaffer.Dot, "nodeGadget:minWidth", 0.0 ) Gaffer.Metadata.registerNodeValue( Gaffer.Dot, "nodeGadget:padding", 0.5 ) # NodeGraph menus def __insertDot( menu, destinationPlug ) : nodeGraph = menu.ancestor( GafferUI.NodeGraph ) gadgetWidget = nodeGraph.graphGadgetWidget() graphGadget = nodeGraph.graphGadget() with Gaffer.UndoContext( destinationPlug.ancestor( Gaffer.ScriptNode ) ) : node = Gaffer.Dot() graphGadget.getRoot().addChild( node ) node.setup( destinationPlug ) node["in"].setInput( destinationPlug.getInput() ) destinationPlug.setInput( node["out"] ) menuPosition = menu.popupPosition( relativeTo = gadgetWidget ) position = gadgetWidget.getViewportGadget().rasterToGadgetSpace( IECore.V2f( menuPosition.x, menuPosition.y ), gadget = graphGadget ).p0 graphGadget.setNodePosition( node, IECore.V2f( position.x, position.y ) ) def <API key>( nodeGraph, destinationPlug, menuDefinition ) : applicationRoot = nodeGraph.scriptNode().ancestor( Gaffer.ApplicationRoot ) connected = False with IECore.IgnoredExceptions( AttributeError ) : connected = applicationRoot.__dotUIConnected if not connected : return if len( menuDefinition.items() ) : menuDefinition.append( "/DotDivider", { "divider" : True } ) menuDefinition.append( "/Insert Dot", { "command" : functools.partial( __insertDot, destinationPlug = destinationPlug ), "active" : not destinationPlug.getFlags( Gaffer.Plug.Flags.ReadOnly ), } ) <API key> = GafferUI.NodeGraph.<API key>().connect( <API key> ) # PlugValueWidget registrations GafferUI.PlugValueWidget.registerCreator( Gaffer.Dot, "in", None ) GafferUI.PlugValueWidget.registerCreator( Gaffer.Dot, "out", None )
package org.agmip.functions; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import static org.agmip.common.Functions.*; import org.agmip.common.Functions.CompareMode; import org.agmip.util.MapUtil; import static org.agmip.util.MapUtil.*; import org.agmip.util.MapUtil.BucketEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provide static functions for weather data handling * * @author Meng zhang */ public class WeatherHelper { private static final Logger LOG = LoggerFactory.getLogger(WeatherHelper.class); /** * Calculate the AMP (annual amplitude of mean monthly temperature oC) and * TAV (Annual average ambient temperature oC) * * @param data The data map * * @return A {@code HashMap} contains {@code TAV} and {@code TAMP}, the key * is their ICASA variable name */ public static HashMap<String, String> getTavAndAmp(HashMap data) { HashMap<String, String> results = new HashMap<String, String>(); HashMap<Integer, MonthlyAvg> tyear = new HashMap<Integer, MonthlyAvg>(); MonthlyAvg tmonth; MonthlyAvg tavAllYears; ArrayList<String> tampAllYears; String tav; String tamp; ArrayList<HashMap<String, String>> dailyArr = getDailyData(data); // Load daily data for (int i = 0; i < dailyArr.size(); i++) { String date; int year; int month; String tmax; String tmin; String tavgDaily; HashMap<String, String> dailyData = dailyArr.get(i); date = getValueOr(dailyData, "w_date", "").trim(); if (date.equals("")) { LOG.warn("There is daily data do not having a valid date"); continue; } else { Calendar cal = Calendar.getInstance(); cal.setTime(<API key>(date)); year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); tmonth = tyear.get(year); if (tmonth == null) { tmonth = new MonthlyAvg(); tyear.put(year, tmonth); } } tmax = getValueOr(dailyData, "tmax", "").trim(); tmin = getValueOr(dailyData, "tmin", "").trim(); tavgDaily = average(tmax, tmin); if (tavgDaily != null) { tmonth.add(month, tavgDaily); } } // Calculate daily data tavAllYears = new MonthlyAvg(); tampAllYears = new ArrayList(); for (Iterator<Integer> it = tyear.keySet().iterator(); it.hasNext();) { int year = it.next(); tmonth = tyear.get(year); String[] tavgs = tmonth.getAllAvg(); // TAV for (int month = 0; month < tavgs.length; month++) { tavAllYears.add(month, tavgs[month]); } // TAMP String tampt = substract(max(tavgs), min(tavgs)); if (tampt != null) { tampAllYears.add(tampt); } } tav = average(2, removeNull(tavAllYears.getAllAvg())); tamp = average(2, tampAllYears.toArray(new String[0])); if (tav != null) { results.put("tav", tav); } if (tamp != null) { results.put("tamp", tamp); } return results; } /** * Calculate the monthly average for each month */ private static class MonthlyAvg { private int[] days = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; private String[] avg = new String[12]; public void add(int month, String val) { if (val == null) { return; } if (this.avg[month] == null) { this.avg[month] = val; days[month] = 1; } else { this.avg[month] = sum(this.avg[month], val); days[month]++; } } public String getAvg(int month) { if (days[month] <= 0) { return null; } else { return divide(avg[month], days[month] + ""); } } public String[] getAllAvg() { String[] ret = new String[days.length]; for (int i = 0; i < days.length; i++) { ret[i] = getAvg(i); } return ret; } } /** * Get weather daily data array from data holder. * * @param data The experiment data holder * @return The weather daily data array */ protected static ArrayList getDailyData(HashMap data) { if (data.containsKey("weather") || !data.containsKey("dailyWeather")) { return MapUtil.getBucket(data, "weather").getDataList(); } else { return new BucketEntry(data).getDataList(); } } /** * Get weather station data set from data holder. * * @param data The experiment data holder * @return The weather station data set */ protected static HashMap getWthData(HashMap data) { if (data.containsKey("weather")) { return getObjectOr(data, "weather", new HashMap()); } else { return data; } } /** * Calculate the reference evapotranspiration (ETo) by means of the * FAO-Penman Monteith equation. * * @param data The data map * * @return An {@code ArrayList} of {@code ETo} for daily weather record. */ public static HashMap<String, ArrayList<String>> getEto(HashMap data) { HashMap<String, ArrayList<String>> results = new HashMap<String, ArrayList<String>>(); HashMap wthData = getWthData(data); ArrayList<HashMap<String, String>> dailyArr = getDailyData(data); // Step 1. Atmospheric pressure (P) [kPa] String wst_elev = getValueOr(wthData, "wst_elev", ""); if (wst_elev.equals("")) { return results; } String P = multiply("101.3", pow(divide(substract("293", product("0.0065", wst_elev)), "293"), "5.26")); String gamma = product("0.664742", "0.001", P); // Eq.17 (Step 8) // latitude [rad] String wst_lat = getValueOr(wthData, "wst_lat", ""); String phi = divide(product(wst_lat, Math.PI + ""), "180"); // Get other potentially necessary meta data from Ace data set String psyvnt = getValueOr(wthData, "psyvnt", "").trim(); String aPsy = ""; if (psyvnt.equals("Forced")) { aPsy = "0.000662"; } else if (psyvnt.equals("Natural")) { aPsy = "0.00800"; } String rPsy = multiply(aPsy, P); String amth = getValueOr(wthData, "amth", "0.25"); String bmth = getValueOr(wthData, "bmth", "0.50"); // Calculate daily ETO ArrayList<String> etoArr = new ArrayList<String>(); for (int i = 0; i < dailyArr.size(); i++) { HashMap<String, String> dailyData = dailyArr.get(i); // Get daily TMAX and TMIN String tMin = getValueOr(dailyData, "tmin", "").trim(); String tMax = getValueOr(dailyData, "tmax", "").trim(); if (tMin.equals("") || tMax.equals("")) { etoArr.add(null); continue; } String tMean = average(tMin, tMax); // Step 4. Saturation vapour pressure (es) String e_tMax = multiply("0.6108", exp(divide(multiply("17.27", tMax), sum(tMax, "237.3")))); String e_tMin = multiply("0.6108", exp(divide(multiply("17.27", tMin), sum(tMin, "237.3")))); String es = average(e_tMax, e_tMin); String slope = divide(product("4098", "0.6108", exp(divide(multiply("17.27", tMean), sum(tMean, "237.3")))), pow(sum(tMean, "237.3"), "2")); // Step 6. Actual vapour pressure (ea) [kPa] String ea; String alt1; String alt2; // Method 1 IF VPRSD is available in the ACE data base if (!(alt1 = getValueOr(dailyData, "vprsd", "").trim()).equals("")) { // ea = VPRSD ea = alt1; } // Method 2 IF TDEW is available in the ACE data base else if (!(alt1 = getValueOr(dailyData, "tdew", "").trim()).equals("")) { // derive ea from the given dew point temperature ea = multiply("0.6108", exp(divide(multiply("17.27", alt1), sum(alt1, "237.3")))); } // Method 3 IF RHMND and RHMXD are available in the ACE data base else if (!(alt1 = getValueOr(dailyData, "rhmxd", "").trim()).equals("") && !(alt2 = getValueOr(dailyData, "rhmnd", getValueOr(dailyData, "rhumd", "")).trim()).equals("")) { // ea from the given maximum and minimum Relative Humidity ea = average(product(e_tMin, alt1, "0.01"), product(e_tMax, alt2, "0.01")); } // Method 4 IF TDRY, TWET and PSYVNT are available in the ACE data base else if (!(alt1 = getValueOr(dailyData, "tdry", "").trim()).equals("") && !(alt2 = getValueOr(dailyData, "twet", "").trim()).equals("") && rPsy != null) { // derive ea from the psychrometric data String e_tWet = multiply("0.6108", exp(divide(multiply("17.27", alt2), sum(alt2, "237.3")))); ea = substract(e_tWet, multiply(rPsy, substract(alt1, alt2))); } // Method 5 use Tmin as an approximation of Tdew else { ea = e_tMin; } // Step 7. Vapour pressure difference (es - ea) String vpDiff = substract(es, ea); // Step 8. Extra terrestrial radiation (Ra) and daylight hours (N) Date w_date = <API key>(getValueOr(dailyData, "w_date", "")); if (w_date == null) { etoArr.add(null); continue; } Calendar cal = Calendar.getInstance(); cal.setTime((w_date)); String J = cal.get(Calendar.DAY_OF_YEAR) + ""; String dr = sum("1", multiply("0.033", cos(product("2", divide(Math.PI + "", "365"), J)))); String delta = multiply("0.409", sin(substract(product("2", divide(Math.PI + "", "365"), J), "1.39"))); String omegas = acos(product("-1", tan(phi), tan(delta))); String ra = divide(product("1440", "0.0820", dr, sum(product(omegas, sin(phi), sin(delta)), product(cos(phi), cos(delta), sin(omegas)))), Math.PI + ""); // TODO String N = divide(multiply("24", omegas), Math.PI + ""); // Step 9. Solar radiation (Rs) String rs; // Method 1. IF SRAD is available in the ACE data base if (!(alt1 = getValueOr(dailyData, "srad", "").trim()).equals("")) { rs = alt1; } // Method 2. IF SUNH is available in the ACE data base else if (!(alt1 = getValueOr(dailyData, "sunh", "").trim()).equals("")) { rs = multiply(sum(amth, divide(multiply(bmth, alt1), N)), ra); } // Method 3. LSE use Tmin and Tmax to estimate Rs by means of the Hargreaves equation else { rs = product(getKrsValue(wthData), sqrt(substract(tMax, tMin)), ra); } // Step 10. Clear-Sky solar radiation (Rso) String rso = multiply(sum("0.75", product("2e-5", wst_elev)), ra); // Step 11. Net solar radiation (Rns) String rns = multiply(substract("1", "0.23"), rs); // Step 12. Net long wave radiation (Rnl) String rnl = product("4.903e-9", average(pow(sum(tMax, "273.16"), "4"), pow(sum(tMin, "273.16"), "4")), substract("0.34", multiply("0.14", sqrt(ea))), substract(divide(multiply("1.35", rs), rso), "0.35")); // Step 13. Net radiation (Rn) String rn = substract(rns, rnl); // Step 14. Wind speed at 2 meter above ground level (u2) // Method 1. WIND is given in the ACE data base String u2; if (!(alt1 = getValueOr(dailyData, "wind", "").trim()).equals("")) { String uz = divide(multiply("1000", alt1), "86400", 4); // CASE 1. Reference height for wind speed measurement (WNDHT) is 2 meter if (compare(alt2 = getValueOr(wthData, "wndht", "").trim(), "2", CompareMode.EQUAL)) { u2 = uz; } // CASE 2. Reference height for wind speed measurement (WNDHT) is NOT 2 meter else { u2 = divide(multiply(uz, "4.87"), log(substract(multiply("67.8", alt2), "5.42"))); } } else { u2 = "2"; } // Step 15. Reference evapotranspiration (ETo) String eto = divide( sum(product("0.408", slope, rn), divide(product(gamma, "900", u2, vpDiff), sum(tMean, "273"))), sum(slope, multiply(gamma, sum("1", multiply("0.34", u2))))); etoArr.add(round(eto, 2)); } results.put("eto", etoArr); return results; } private static String getKrsValue(HashMap data) { // TODO waiting for GIS system imported return "0.16"; // or "0.19"; } }
package org.locationtech.geogig.geotools.cli.porcelain; import java.io.IOException; import org.geotools.data.DataStore; import org.locationtech.geogig.api.ProgressListener; import org.locationtech.geogig.cli.CLICommand; import org.locationtech.geogig.cli.<API key>; import org.locationtech.geogig.cli.GeogigCLI; import org.locationtech.geogig.cli.annotation.<API key>; import org.locationtech.geogig.geotools.plumbing.GeoToolsOpException; import org.locationtech.geogig.geotools.plumbing.ImportOp; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; /** * Imports one or more tables from a PostGIS database. * * PostGIS CLI proxy for {@link ImportOp} * * @see ImportOp */ @<API key> @Parameters(commandNames = "import", commandDescription = "Import PostGIS database") public class PGImport extends AbstractPGCommand implements CLICommand { /** * If this is set, only this table will be imported. */ @Parameter(names = { "--table", "-t" }, description = "Table to import.") public String table = ""; /** * If this is set, all tables will be imported. */ @Parameter(names = "--all", description = "Import all tables.") public boolean all = false; /** * do not overwrite or delete features */ @Parameter(names = { "--add" }, description = "Do not replace or delete features in the destitnation path") boolean add; /** * Use origin feature type */ @Parameter(names = { "--force-featuretype" }, description = "Use origin feature type even if it does not match the default destination featuretype") boolean forceFeatureType; /** * Set the path default feature type to the the feature type of imported features, and modify * existing features to match it */ @Parameter(names = { "--alter" }, description = "Set the path default feature type to the the feature type of imported features, and modify existing features to match it") boolean alter; /** * Destination path to add features to. Only allowed when importing a single table */ @Parameter(names = { "-d", "--dest" }, description = "Path to import to") String destTable; /** * The attribute to use to create the feature Id */ @Parameter(names = { "--fid-attrib" }, description = "Use the specified attribute to create the feature Id") String fidAttribute; /** * Executes the import command using the provided options. */ @Override protected void runInternal(GeogigCLI cli) throws IOException { DataStore dataStore = getDataStore(); try { cli.getConsole().println("Importing from database " + commonArgs.database); ProgressListener progressListener = cli.getProgressListener(); cli.getGeogig().command(ImportOp.class).setAll(all).setTable(table).setAlter(alter) .setDestinationPath(destTable).setOverwrite(!add).setDataStore(dataStore) .<API key>(!forceFeatureType).setFidAttribute(fidAttribute) .setProgressListener(progressListener).call(); cli.getConsole().println("Import successful."); } catch (GeoToolsOpException e) { switch (e.statusCode) { case TABLE_NOT_DEFINED: throw new <API key>( "No tables specified for import. Specify --all or --table <table>.", e); case <API key>: throw new <API key>( "Specify --all or --table <table>, both cannot be set.", e); case NO_FEATURES_FOUND: throw new <API key>("No features were found in the database.", e); case TABLE_NOT_FOUND: throw new <API key>("Could not find the specified table.", e); case UNABLE_TO_GET_NAMES: throw new <API key>("Unable to get feature types from the database.", e); case <API key>: throw new <API key>("Unable to get features from the database.", e); case UNABLE_TO_INSERT: throw new <API key>( "Unable to insert features into the working tree.", e); case <API key>: throw new <API key>( "Alter cannot be used with --all option and more than one table.", e); case <API key>: throw new <API key>( "The feature type of the data to import does not match the feature type of the destination tree and cannot be imported\n" + "USe the --force-featuretype switch to import using the original featuretype and crete a mixed type tree", e); default: throw new <API key>("Import failed with exception: " + e.statusCode.name(), e); } } finally { dataStore.dispose(); cli.getConsole().flush(); } } }
<?php /** * Description of <API key> */ class <API key> extends \OmegaUp\Test\ControllerTestCase { /** * A PHPUnit data provider for libinteractive details. * $emptyRequest, $missingParameters * @return list<array{0: bool, 1: list<string>, 2: array<string, string>}> */ public function <API key>(): array { return [ [true, [], []], [false, [], ['name' => 'wrong name']], [false, ['name'], []], [false, ['os'], []], [false, ['idl'], []], [false, ['language'], []], ]; } /** * Test should return error when some parameters are not provided * * @param list<string> $missingParameters * @param array<string, string> $wrongParameters * * @dataProvider <API key> */ public function <API key>( bool $isEmptyRequest, array $missingParameters, array $wrongParameters ) { $language = 'c'; $os = 'unix'; $name = 'file_name'; $idl = "interface Main {\n};\n\ninterface sums {\nint sums(int a, int b);\n};"; $error = null; $<API key> = [ 'language' => $language, 'os' => $os, 'name' => $name, 'idl' => $idl, ]; $parameters = $isEmptyRequest ? [] : $<API key>; foreach ($missingParameters as $missingParameter) { unset($parameters[$missingParameter]); } foreach ($wrongParameters as $index => $wrongParameter) { $parameters[$index] = $wrongParameter; } $response = \OmegaUp\Controllers\Problem::<API key>( new \OmegaUp\Request($parameters) )['templateProperties']['payload']; if ($isEmptyRequest) { $<API key>['name'] = null; $<API key>['idl'] = null; } else { if (isset($wrongParameters['name'])) { $error = [ 'description' => \OmegaUp\Translations::getInstance()->get( '<API key>' ), 'field' => 'name', ]; $<API key>['name'] = $wrongParameters['name']; } elseif (!empty($missingParameters)) { $field = null; foreach ($missingParameters as $missingParameter) { $<API key>[$missingParameter] = null; $field = $missingParameter; } $error = [ 'description' => \OmegaUp\Translations::getInstance()->get( 'parameterInvalid' ), 'field' => $field, ]; } } $this->assertEquals( $response['language'], $<API key>['language'] ); $this->assertEquals($response['os'], $<API key>['os']); $this->assertEquals( $response['name'], $<API key>['name'] ); $this->assertEquals($response['idl'], $<API key>['idl']); if (!empty($missingParameters)) { $this->assertEquals($response['error'], $error); } } }
CodeMirror.validate = (function() { var GUTTER_ID = "<API key>"; var SEVERITIES = /^(?:error|warning)$/; function showTooltip(e, content) { var tt = document.createElement("div"); tt.className = "<API key>"; tt.appendChild(content.cloneNode(true)); document.body.appendChild(tt); function position(e) { if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position); tt.style.top = (e.clientY - tt.offsetHeight - 5) + "px"; tt.style.left = (e.clientX + 5) + "px"; } CodeMirror.on(document, "mousemove", position); position(e); tt.style.opacity = 1; return tt; } function rm(elt) { if (elt.parentNode) elt.parentNode.removeChild(elt); } function hideTooltip(tt) { if (!tt.parentNode) return; if (tt.style.opacity == null) rm(tt); tt.style.opacity = 0; setTimeout(function() { rm(tt); }, 600); } function LintState(cm, options, hasGutter) { this.marked = []; this.options = options; this.timeout = null; this.hasGutter = hasGutter; this.onMouseOver = function(e) { onMouseOver(cm, e); }; } function parseOptions(options) { if (options instanceof Function) return {getAnnotations: options}; else if (!options || !options.getAnnotations) throw new Error("Required option 'getAnnotations' missing (lint addon)"); return options; } function clearMarks(cm) { var state = cm._lintState; if (state.hasGutter) cm.clearGutter(GUTTER_ID); for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); state.marked.length = 0; } function makeMarker(labels, severity, multiple) { var marker = document.createElement("div"), inner = marker; marker.className = "<API key>-" + severity; if (multiple) { inner = marker.appendChild(document.createElement("div")); inner.className = "<API key>"; } var tooltip; CodeMirror.on(inner, "mouseover", function(e) { tooltip = showTooltip(e, labels); }); CodeMirror.on(inner, "mouseout", function() { if (tooltip) hideTooltip(tooltip); }); return marker; } function getMaxSeverity(a, b) { if (a == "error") return a; else return b; } function groupByLine(annotations) { var lines = []; for (var i = 0; i < annotations.length; ++i) { var ann = annotations[i], line = ann.from.line; (lines[line] || (lines[line] = [])).push(ann); } return lines; } function annotationTooltip(ann) { var severity = ann.severity; if (!SEVERITIES.test(severity)) severity = "error"; var tip = document.createElement("div"); tip.className = "<API key>-" + severity; tip.appendChild(document.createTextNode(ann.message)); return tip; } function startLinting(cm) { var state = cm._lintState, options = state.options; if (options.async) options.getAnnotations(cm, updateLinting, options); else updateLinting(cm, options.getAnnotations(cm.getValue())); } function updateLinting(cm, <API key>) { clearMarks(cm); var state = cm._lintState, options = state.options; var annotations = groupByLine(<API key>); for (var line = 0; line < annotations.length; ++line) { var anns = annotations[line]; if (!anns) continue; var maxSeverity = null; var tipLabel = state.hasGutter && document.<API key>(); for (var i = 0; i < anns.length; ++i) { var ann = anns[i]; var severity = ann.severity; if (!SEVERITIES.test(severity)) severity = "error"; maxSeverity = getMaxSeverity(maxSeverity, severity); if (options.formatAnnotation) ann = options.formatAnnotation(ann); if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann)); if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, { className: "<API key>-" + severity, __annotation: ann })); } if (state.hasGutter) cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1)); } if (options.onUpdateLinting) options.onUpdateLinting(<API key>, annotations, cm); } function onChange(cm) { var state = cm._lintState; clearTimeout(state.timeout); state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500); } function popupSpanTooltip(ann, e) { var tooltip = showTooltip(e, annotationTooltip(ann)); var target = e.target || e.srcElement; CodeMirror.on(target, "mouseout", hide); function hide() { CodeMirror.off(target, "mouseout", hide); hideTooltip(tooltip); } } // When the mouseover fires, the cursor might not actually be over // the character itself yet. These pairs of x,y offsets are used to // probe a few nearby points when no suitable marked range is found. var nearby = [0, 0, 0, 5, 0, -5, 5, 0, -5, 0]; function onMouseOver(cm, e) { if (!/\<API key>-/.test((e.target || e.srcElement).className)) return; for (var i = 0; i < nearby.length; i += 2) { var spans = cm.findMarksAt(cm.coordsChar({left: e.clientX + nearby[i], top: e.clientY + nearby[i + 1]})); for (var j = 0; j < spans.length; ++j) { var span = spans[j], ann = span.__annotation; if (ann) return popupSpanTooltip(ann, e); } } } CodeMirror.defineOption("lintWith", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { clearMarks(cm); cm.off("change", onChange); CodeMirror.off(cm.getWrapperElement(), "mouseover", cm._lintState.onMouseOver); delete cm._lintState; } if (val) { var gutters = cm.getOption("gutters"), hasLintGutter = false; for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true; var state = cm._lintState = new LintState(cm, parseOptions(val), hasLintGutter); cm.on("change", onChange); CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); startLinting(cm); } }); })();
## Setup ## Global Dependencies Install * [node.js](http://nodejs.org) * [GitHub Client](http://mac.github.com/) (with Git Terminal option) * [Safari](http: Project Setup $ git clone https://github.com/ForceDotComLabs/<API key>.git $ cd <API key> $ npm install Run a local node server: $ node proxy.js You can now launch the [Sample App](http://localhost:9000/index.html). It will go through the OAuth flow to obtain user session and render data. Copyright (c) 2014, salesforce.com, inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.lightcrafts.media.jai.iterator; import com.lightcrafts.media.jai.util.PropertyUtil; class JaiI18N { static String packageName = "com.lightcrafts.media.jai.iterator"; public static String getString(String key) { return PropertyUtil.getString(packageName, key); } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.free.label.xml Template File: source-sinks-53c.tmpl.c */ /* * @description * CWE: 690 Unchecked Return Value To NULL Pointer * BadSource: malloc Allocate data using malloc() * Sinks: * GoodSink: Check to see if the data allocation failed and if not, use data * BadSink : Don't check for NULL and use data * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD /* bad function declaration */ void <API key>(wchar_t * data); void <API key>(wchar_t * data) { <API key>(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G uses the BadSource with the GoodSink */ void <API key>(wchar_t * data); void <API key>(wchar_t * data) { <API key>(data); } #endif /* OMITGOOD */
<?php namespace LaneWeChat\Core\Aes; /** * SHA1 class * * . */ class SHA1 { /** * SHA1 * @param string $token * @param string $timestamp * @param string $nonce * @param string $encrypt */ public function getSHA1($token, $timestamp, $nonce, $encrypt_msg) { try { $array = array($encrypt_msg, $token, $timestamp, $nonce); sort($array, SORT_STRING); $str = implode($array); return array(ErrorCode::$OK, sha1($str)); } catch (\Exception $e) { //print $e . "\n"; return array(ErrorCode::$<API key>, null); } } } ?>
cr.define('options', function() { /** @const */ var OptionsPage = options.OptionsPage; /** * Enumeration of possible states during pairing. The value associated with * each state maps to a localized string in the global variable * |loadTimeData|. * @enum {string} */ var PAIRING = { STARTUP: '<API key>', ENTER_PIN_CODE: '<API key>', ENTER_PASSKEY: '<API key>', REMOTE_PIN_CODE: '<API key>', REMOTE_PASSKEY: '<API key>', CONFIRM_PASSKEY: '<API key>', CONNECT_FAILED: '<API key>', CANCELED: '<API key>', DISMISSED: '<API key>', // pairing dismissed(succeeded or // canceled). }; /** * List of IDs for conditionally visible elements in the dialog. * @type {Array.<string>} * @const */ var ELEMENTS = ['<API key>', '<API key>', '<API key>', '<API key>', '<API key>', '<API key>', '<API key>', '<API key>']; /** * Encapsulated handling of the Bluetooth device pairing page. * @constructor */ function BluetoothPairing() { OptionsPage.call(this, 'bluetoothPairing', loadTimeData.getString('<API key>'), 'bluetooth-pairing'); } cr.addSingletonGetter(BluetoothPairing); BluetoothPairing.prototype = { __proto__: OptionsPage.prototype, /** * Description of the bluetooth device. * @type {{name: string, * address: string, * icon: Constants.DEVICE_TYPE, * paired: boolean, * bonded: boolean, * connected: boolean, * pairing: string|undefined, * passkey: number|undefined, * pincode: string|undefined, * entered: number|undefined}} * @private. */ device_: null, /** * Can the dialog be programmatically dismissed. * @type {boolean} */ dismissible_: true, /** @override */ initializePage: function() { OptionsPage.prototype.initializePage.call(this); var self = this; $('<API key>').onclick = function() { OptionsPage.closeOverlay(); }; $('<API key>').onclick = function() { chrome.send('<API key>', [self.device_.address, 'reject']); OptionsPage.closeOverlay(); }; $('<API key>').onclick = function() { var args = [self.device_.address, 'connect']; var passkey = self.device_.passkey; if (passkey) args.push(String(passkey)); else if (!$('<API key>').hidden) args.push($('bluetooth-passkey').value); else if (!$('<API key>').hidden) args.push($('bluetooth-pincode').value); chrome.send('<API key>', args); OptionsPage.closeOverlay(); }; $('<API key>').onclick = function() { chrome.send('<API key>', [self.device_.address, 'accept']); OptionsPage.closeOverlay(); }; $('<API key>').onclick = function() { OptionsPage.closeOverlay(); }; $('bluetooth-passkey').oninput = function() { var inputField = $('bluetooth-passkey'); var value = inputField.value; // Note that using <input type="number"> is insufficient to restrict // the input as it allows negative numbers and does not limit the // number of charactes typed even if a range is set. Furthermore, // it sometimes produces strange repaint artifacts. var filtered = value.replace(/[^0-9]/g, ''); if (filtered != value) inputField.value = filtered; $('<API key>').disabled = inputField.value.length == 0; } $('bluetooth-pincode').oninput = function() { $('<API key>').disabled = $('bluetooth-pincode').value.length == 0; } $('bluetooth-passkey').addEventListener('keydown', this.<API key>.bind(this)); $('bluetooth-pincode').addEventListener('keydown', this.<API key>.bind(this)); }, /** @override */ didClosePage: function() { if (this.device_.pairing != PAIRING.DISMISSED && this.device_.pairing != PAIRING.CONNECT_FAILED) { this.device_.pairing = PAIRING.CANCELED; chrome.send('<API key>', [this.device_.address, 'cancel']); } }, /** * Override to prevent showing the overlay if the Bluetooth device details * have not been specified. Prevents showing an empty dialog if the user * quits and restarts Chrome while in the process of pairing with a device. * @return {boolean} True if the overlay can be displayed. */ canShowPage: function() { return this.device_ && this.device_.address && this.device_.pairing; }, /** * Sets input focus on the passkey or pincode field if appropriate. */ didShowPage: function() { if (!$('bluetooth-pincode').hidden) $('bluetooth-pincode').focus(); else if (!$('bluetooth-passkey').hidden) $('bluetooth-passkey').focus(); }, /** * Configures the overlay for pairing a device. * @param {Object} device Description of the bluetooth device. */ update: function(device) { this.device_ = {}; for (key in device) this.device_[key] = device[key]; // Update the pairing instructions. var instructionsEl = $('<API key>'); this.clearElement_(instructionsEl); this.dismissible_ = ('dismissible' in device) ? device.dismissible : true; var message = loadTimeData.getString(device.pairing); message = message.replace('%1', this.device_.name); instructionsEl.textContent = message; // Update visibility of dialog elements. if (this.device_.passkey) { this.updatePasskey_(); if (this.device_.pairing == PAIRING.CONFIRM_PASSKEY) { // Confirming a match between displayed passkeys. this.displayElements_(['<API key>', '<API key>', '<API key>']); } else { // Remote entering a passkey. this.displayElements_(['<API key>', '<API key>']); } } else if (this.device_.pincode) { this.updatePinCode_(); this.displayElements_(['<API key>', '<API key>']); } else if (this.device_.pairing == PAIRING.ENTER_PIN_CODE) { // Prompting the user to enter a PIN code. this.displayElements_(['<API key>', '<API key>', '<API key>']); $('bluetooth-pincode').value = ''; } else if (this.device_.pairing == PAIRING.ENTER_PASSKEY) { // Prompting the user to enter a passkey. this.displayElements_(['<API key>', '<API key>', '<API key>']); $('bluetooth-passkey').value = ''; } else if (this.device_.pairing == PAIRING.STARTUP) { // Starting the pairing process. this.displayElements_(['<API key>']); } else { // Displaying an error message. this.displayElements_(['<API key>']); } // User is required to enter a passkey or pincode before the connect // button can be enabled. The 'oninput' methods for the input fields // determine when the connect button becomes active. $('<API key>').disabled = true; }, /** * Handles the ENTER key for the passkey or pincode entry field. * @return {Event} a keydown event. * @private */ <API key>: function(event) { /** @const */ var ENTER_KEY_CODE = 13; if (event.keyCode == ENTER_KEY_CODE) { var button = $('<API key>'); if (!button.hidden) button.click(); } }, /** * Updates the visibility of elements in the dialog. * @param {Array.<string>} list List of conditionally visible elements that * are to be made visible. * @private */ displayElements_: function(list) { var enabled = {}; for (var i = 0; i < list.length; i++) { var key = list[i]; enabled[key] = true; } for (var i = 0; i < ELEMENTS.length; i++) { var key = ELEMENTS[i]; $(key).hidden = !enabled[key]; } }, /** * Removes all children from an element. * @param {!Element} element Target element to clear. */ clearElement_: function(element) { var child = element.firstChild; while (child) { element.removeChild(child); child = element.firstChild; } }, /** * Formats an element for displaying the passkey. */ updatePasskey_: function() { var passkeyEl = $('<API key>'); var keyClass = this.device_.pairing == PAIRING.REMOTE_PASSKEY ? '<API key>' : '<API key>'; this.clearElement_(passkeyEl); var key = String(this.device_.passkey); var progress = this.device_.entered | 0; for (var i = 0; i < key.length; i++) { var keyEl = document.createElement('span'); keyEl.textContent = key.charAt(i); keyEl.className = keyClass; if (i < progress) keyEl.classList.add('key-typed'); passkeyEl.appendChild(keyEl); } if (this.device_.pairing == PAIRING.REMOTE_PASSKEY) { // Add enter key. var label = loadTimeData.getString('bluetoothEnterKey'); var keyEl = document.createElement('span'); keyEl.textContent = label; keyEl.className = keyClass; keyEl.id = 'bluetooth-enter-key'; passkeyEl.appendChild(keyEl); } passkeyEl.hidden = false; }, /** * Formats an element for displaying the PIN code. */ updatePinCode_: function() { var passkeyEl = $('<API key>'); var keyClass = this.device_.pairing == PAIRING.REMOTE_PIN_CODE ? '<API key>' : '<API key>'; this.clearElement_(passkeyEl); var key = String(this.device_.pincode); for (var i = 0; i < key.length; i++) { var keyEl = document.createElement('span'); keyEl.textContent = key.charAt(i); keyEl.className = keyClass; keyEl.classList.add('key-pin'); passkeyEl.appendChild(keyEl); } if (this.device_.pairing == PAIRING.REMOTE_PIN_CODE) { // Add enter key. var label = loadTimeData.getString('bluetoothEnterKey'); var keyEl = document.createElement('span'); keyEl.textContent = label; keyEl.className = keyClass; keyEl.classList.add('key-pin'); keyEl.id = 'bluetooth-enter-key'; passkeyEl.appendChild(keyEl); } passkeyEl.hidden = false; }, }; /** * Configures the device pairing instructions and displays the pairing * overlay. * @param {Object} device Description of the Bluetooth device. */ BluetoothPairing.showDialog = function(device) { BluetoothPairing.getInstance().update(device); OptionsPage.showPageByName('bluetoothPairing', false); }; /** * Displays a message from the Bluetooth adapter. * @param {{string: label, * string: address} data Data for constructing the message. */ BluetoothPairing.showMessage = function(data) { var name = data.address; if (name.length == 0) return; var dialog = BluetoothPairing.getInstance(); if (name == dialog.device_.address && dialog.device_.pairing == PAIRING.CANCELED) { // Do not show any error message after cancelation of the pairing. return; } var list = $('<API key>'); if (list) { var index = list.find(name); if (index == undefined) { list = $('<API key>'); index = list.find(name); } if (index != undefined) { var entry = list.dataModel.item(index); if (entry && entry.name) name = entry.name; } } BluetoothPairing.showDialog({name: name, address: data.address, pairing: data.label, dismissible: false}); }; /** * Closes the Bluetooth pairing dialog. */ BluetoothPairing.dismissDialog = function() { var overlay = OptionsPage.<API key>(); var dialog = BluetoothPairing.getInstance(); if (overlay == dialog && dialog.dismissible_) { dialog.device_.pairing = PAIRING.DISMISSED; OptionsPage.closeOverlay(); } }; // Export return { BluetoothPairing: BluetoothPairing }; });
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.label.xml Template File: sources-sink-81_bad.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Full path and file name * Sinks: open * BadSink : Open the file named in data using open() * Flow Variant: 81 Data flow: data passed in a parameter to a virtual method called via a reference * * */ #ifndef OMITBAD #include "std_testcase.h" #include "<API key>.h" #ifdef _WIN32 #define OPEN _wopen #define CLOSE _close #else #include <unistd.h> #define OPEN open #define CLOSE close #endif namespace <API key> { void <API key>::action(wchar_t * data) const { { int fileDesc; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE); if (fileDesc != -1) { CLOSE(fileDesc); } } } } #endif /* OMITBAD */
<?template TSearch (q, results, appendName) ?> <html> <head> <link rel="stylesheet" href="${Conf.static}/css/sing-browse.css" type="text/css" /> </head> <body> <table id="btable"> <thead> <tr id="browseheader"> <td> <div id="browseheadertop"> <div id="searchbox"><form method="post" action="/search/"><input type="text" name="q" value="${q}"/></form></div> Search </div> <div id="browsepath"> <a href="${Conf.static}/home.html">Home</a> &gt; <a href="/search/">Search</a> </div> </td> </tr> </thead> <tbody> <tr id="browsecontent"> <td> <div id="bcd1"> <div id="bcd2"> <form method="post" action="/search/"> <input type="text" name="q" value="${q}" /> <input type="submit" value="Search" /> </form> <div t:ifOption="results as { artists, albums, songs, itime, ttime }" t:strip=""> <div t:if="case artists of nil => false | _ => true" t:strip=""> <p>Artists matching "${q}": ${Int.toString (length artists)}</p> <ul class="browselist"> <t:for exp="artists" pattern="{ id, name, mm_mixable, mb_id, numAlbums }">$H{ TListItem.render (id, name, SOME "/browse/artists/", appendName, "artist_id:", "") }</t:for> </ul> </div> <div t:if="case albums of nil => false | _ => true" t:strip=""> <p>Albums matching "${q}": ${Int.toString (length albums)}</p> <ul class="browselist"> <t:for exp="albums" pattern="{ id, name, compilation, artist_id, artist_name, year }">$H{ TListItem.render (id, name, SOME "/browse/albums/", appendName, "album_id:", "") }</t:for> </ul> </div> <div t:if="case songs of nil => false | _ => true"> <p>Songs matching "${q}": ${Int.toString (length songs)}</p> <ul class="browselist"> <li t:for="{ id, tracknum, title, album, artists, lossless } in songs"> <a href="javascript:top.Sing.ctl.add('track_id:${id}')" class="addbutton"> </a><a href="javascript:top.Sing.ctl.play('track_id:${id}')" class="playbutton"> </a> <a href="/browse/song/${id}/">${title}</a> <t:ifOption exp="album" pattern="{id = aId, title = aTitle}"> from <a t:if="appendName" href="/browse/albums/${Int.toString aId}/${WebUtil.urlencode aTitle}/">${aTitle}</a> <a t:if="not appendName" href="/browse/albums/${Int.toString aId}/">${aTitle}</a> </t:ifOption> <t:case exp="artists"> <t:of pattern="nil" /> <t:of pattern="_"> by <t:case exp="appendName"> <t:of pattern="true"><t:for exp="artists" pattern="{ id, name }" sep=", "><a href="/browse/artists/${Int.toString id}/${WebUtil.urlencode name}/">${name}</a></t:for></t:of> <t:of pattern="false"><t:for exp="artists" pattern="{ id, name }" sep=", "><a href="/browse/artists/${Int.toString id}/">${name}</a></t:for></t:of> </t:case> </t:of> </t:case> <t:case exp="lossless"> <t:of pattern="SOME 1"> &#10029; </t:of> <t:of pattern="_" /> </t:case> </li> </ul> </div> <div t:if="case (artists, albums, songs) of (nil, nil, nil) => true | _ => false"> No search results. </div> <p> Time: ${Real.toString ((Time.toReal itime) * 1000.0)} ms index, ${Real.toString ((Time.toReal ttime) * 1000.0)} ms total </p> </div> </div> </div> </td> </tr> </tbody> </table> </body> </html>
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: <html xmlns="http: <head> <title>Docs for page AntiFloodPlugin.php</title> <link rel="stylesheet" href="../../media/stylesheet.css" /> <script src="../../media/lib/classTree.js"></script> <link id="<API key>" type="text/css" rel="stylesheet" href="../../media/lib/tab.webfx.css" /> <script type="text/javascript" src="../../media/lib/tabpane.js"></script> <script language="javascript" type="text/javascript" src="../../media/lib/ua.js"></script> <script language="javascript" type="text/javascript"> var imgPlus = new Image(); var imgMinus = new Image(); imgPlus.src = "../../media/images/plus.gif"; imgMinus.src = "../../media/images/minus.gif"; function showNode(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; var oImg = document.layers["img" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; var oImg = document.all["img" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); var oImg = document.getElementById("img" + Node); break; } oImg.src = imgMinus.src; oTable.style.display = "block"; } function hideNode(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; var oImg = document.layers["img" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; var oImg = document.all["img" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); var oImg = document.getElementById("img" + Node); break; } oImg.src = imgPlus.src; oTable.style.display = "none"; } function nodeIsVisible(Node){ switch(navigator.family){ case 'nn4': // Nav 4.x code fork... var oTable = document.layers["span" + Node]; break; case 'ie4': // IE 4/5 code fork... var oTable = document.all["span" + Node]; break; case 'gecko': // Standards Compliant code fork... var oTable = document.getElementById("span" + Node); break; } return (oTable && oTable.style.display == "block"); } function <API key>(Node){ if (nodeIsVisible(Node)){ hideNode(Node); }else{ showNode(Node); } } </script> <!-- template designed by Julien Damon based on PHPEdit's generated templates, and tweaked by Greg Beaver --> <body bgcolor="#ffffff" > <h2>File: /vendors/swiftMailer/classes/Swift/Plugins/AntiFloodPlugin.php</h2> <div class="tab-pane" id="tabPane1"> <script type="text/javascript"> tp1 = new WebFXTabPane( document.getElementById( "tabPane1" ) ); </script> <div class="tab-page" id="Description"> <h2 class="tab">Description</h2> <ul> </ul> <A NAME='classes_summary'></A> <h3>Classes defined in this file</h3> <TABLE CELLPADDING='3' CELLSPACING='0' WIDTH='100%' CLASS="border"> <THEAD> <TR><TD STYLE="width:20%"><h4>CLASS NAME</h4></TD><TD STYLE="width: 80%"><h4>DESCRIPTION</h4></TD></TR> </THEAD> <TBODY> <TR BGCOLOR='white' CLASS='TableRowColor'> <TD><a href="../../Swift/Plugins/<API key>.html"><API key></a></TD> <TD>Reduces network flooding when sending large amounts of mail.</TD> </TR> </TBODY> </TABLE> </div> <script type="text/javascript">tp1.addTabPage( document.getElementById( "Description" ) );</script> <div class="tab-page" id="tabPage1"> <h2 class="tab">Include/Require Statements</h2> <script type="text/javascript">tp1.addTabPage( document.getElementById( "tabPage1" ) );</script> </div> <div class="tab-page" id="tabPage2"> <h2 class="tab">Global Variables</h2> <script type="text/javascript">tp1.addTabPage( document.getElementById( "tabPage2" ) );</script> </div> <div class="tab-page" id="tabPage3"> <A NAME='constant_detail'></A> <h2 class="tab">Constants</h2> <script type="text/javascript">tp1.addTabPage( document.getElementById( "tabPage3" ) );</script> </div> <div class="tab-page" id="tabPage4"> <h2 class="tab">Functions</h2> <script type="text/javascript">tp1.addTabPage( document.getElementById( "tabPage4" ) );</script> </div> </div> <script type="text/javascript"> //<![CDATA[ setupAllTabs(); </script> <div id="credit"> <hr /> Documentation generated on Fri, 12 Nov 2010 20:45:11 +0000 by <a href="http: </div> </body> </html>
import pytest import pandas.util.testing as tm @pytest.fixture def datetime_series(): """ Fixture for Series of floats with DatetimeIndex """ s = tm.makeTimeSeries() s.name = "ts" return s @pytest.fixture def string_series(): """ Fixture for Series of floats with Index of unique strings """ s = tm.makeStringSeries() s.name = "series" return s @pytest.fixture def object_series(): """ Fixture for Series of dtype datetime64[ns] with Index of unique strings """ s = tm.makeObjectSeries() s.name = "objects" return s
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.label.xml Template File: sources-sink-08.tmpl.c */ /* * @description * CWE: 90 LDAP Injection * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Use a fixed string * Sink: * BadSink : data concatenated into LDAP search, which could result in LDAP Injection * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse()) * * */ #include "std_testcase.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #include <Winldap.h> #pragma comment(lib, "wldap32") /* The two function below always return the same value, so a tool * should be able to identify that calls to the functions will always * return a fixed value. */ static int staticReturnsTrue() { return 1; } static int staticReturnsFalse() { return 0; } #ifndef OMITBAD void <API key>() { wchar_t * data; wchar_t dataBuffer[256] = L""; data = dataBuffer; if(staticReturnsTrue()) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (256 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */ static void goodG2B1() { wchar_t * data; wchar_t dataBuffer[256] = L""; data = dataBuffer; if(staticReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a fixed file name */ wcscat(data, L"Doe, XXXXX"); } { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; wchar_t dataBuffer[256] = L""; data = dataBuffer; if(staticReturnsTrue()) { /* FIX: Use a fixed file name */ wcscat(data, L"Doe, XXXXX"); } { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } void <API key>() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
describe('Navigation links', () => { it('should render the expected forum and news links.', () => { cy.visit('/learn'); cy.get('.toggle-button-nav').should('be.visible'); cy.get('.toggle-button-nav').click(); cy.get('.nav-list') .contains('Forum') .should('have.attr', 'href', 'https://forum.freecodecamp.org/'); cy.get('.nav-list') .contains('News') .should('have.attr', 'href', 'https://freecodecamp.org/news/'); }); });
/** * @file maple_mini.cpp * @author Marti Bolivar <mbolivar@leaflabs.com> * @brief Maple Mini board file. */ #ifdef BOARD_maple_mini #include "maple_mini.h" #include "gpio.h" #include "timer.h" #include "wirish_debug.h" #include "wirish_types.h" /* Since we want the Serial Wire/JTAG pins as GPIOs, disable both SW * and JTAG debug support */ void boardInit(void) { disableDebugPorts(); } extern const stm32_pin_info PIN_MAP[BOARD_NR_GPIO_PINS] = { /* Top header */ {GPIOB, NULL, NULL, 11, 0, ADCx}, /* D0/PB11 */ {GPIOB, NULL, NULL, 10, 0, ADCx}, /* D1/PB10 */ {GPIOB, NULL, NULL, 2, 0, ADCx}, /* D2/PB2 */ {GPIOB, TIMER3, ADC1, 0, 3, 8}, /* D3/PB0 */ {GPIOA, TIMER3, ADC1, 7, 2, 7}, /* D4/PA7 */ {GPIOA, TIMER3, ADC1, 6, 1, 6}, /* D5/PA6 */ {GPIOA, NULL, ADC1, 5, 0, 5}, /* D6/PA5 */ {GPIOA, NULL, ADC1, 4, 0, 4}, /* D7/PA4 */ {GPIOA, TIMER2, ADC1, 3, 4, 3}, /* D8/PA3 */ {GPIOA, TIMER2, ADC1, 2, 3, 2}, /* D9/PA2 */ {GPIOA, TIMER2, ADC1, 1, 2, 1}, /* D10/PA1 */ {GPIOA, TIMER2, ADC1, 0, 1, 0}, /* D11/PA0 */ {GPIOC, NULL, NULL, 15, 0, ADCx}, /* D12/PC15 */ {GPIOC, NULL, NULL, 14, 0, ADCx}, /* D13/PC14 */ {GPIOC, NULL, NULL, 13, 0, ADCx}, /* D14/PC13 */ /* Bottom header */ {GPIOB, TIMER4, NULL, 7, 2, ADCx}, /* D15/PB7 */ {GPIOB, TIMER4, NULL, 6, 1, ADCx}, /* D16/PB6 */ {GPIOB, NULL, NULL, 5, 0, ADCx}, /* D17/PB5 */ {GPIOB, NULL, NULL, 4, 0, ADCx}, /* D18/PB4 */ {GPIOB, NULL, NULL, 3, 0, ADCx}, /* D19/PB3 */ {GPIOA, NULL, NULL, 15, 0, ADCx}, /* D20/PA15 */ {GPIOA, NULL, NULL, 14, 0, ADCx}, /* D21/PA14 */ {GPIOA, NULL, NULL, 13, 0, ADCx}, /* D22/PA13 */ {GPIOA, NULL, NULL, 12, 0, ADCx}, /* D23/PA12 */ {GPIOA, TIMER1, NULL, 11, 4, ADCx}, /* D24/PA11 */ {GPIOA, TIMER1, NULL, 10, 3, ADCx}, /* D25/PA10 */ {GPIOA, TIMER1, NULL, 9, 2, ADCx}, /* D26/PA9 */ {GPIOA, TIMER1, NULL, 8, 1, ADCx}, /* D27/PA8 */ {GPIOB, NULL, NULL, 15, 0, ADCx}, /* D28/PB15 */ {GPIOB, NULL, NULL, 14, 0, ADCx}, /* D29/PB14 */ {GPIOB, NULL, NULL, 13, 0, ADCx}, /* D30/PB13 */ {GPIOB, NULL, NULL, 12, 0, ADCx}, /* D31/PB12 */ {GPIOB, TIMER4, NULL, 8, 3, ADCx}, /* D32/PB8 */ {GPIOB, TIMER3, ADC1, 1, 4, 9}, /* D33/PB1 */ }; extern const uint8 boardPWMPins[BOARD_NR_PWM_PINS] __FLASH__ = { 3, 4, 5, 8, 9, 10, 11, 15, 16, 25, 26, 27 }; extern const uint8 boardADCPins[BOARD_NR_ADC_PINS] __FLASH__ = { 3, 4, 5, 6, 7, 8, 9, 10, 11 }; #define USB_DP 23 #define USB_DM 24 extern const uint8 boardUsedPins[BOARD_NR_USED_PINS] __FLASH__ = { BOARD_LED_PIN, BOARD_BUTTON_PIN, USB_DP, USB_DM }; #endif
using OrchardCore.ContentFields.Fields; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Metadata.Models; namespace OrchardCore.ContentFields.ViewModels { public class <API key> { public TextField Field { get; set; } public ContentPart Part { get; set; } public <API key> PartFieldDefinition { get; set; } } }
// Tideland Go Library - Loop - Errors package loop // IMPORTS import ( "github.com/tideland/golib/errors" ) // CONSTANTS // Error codes of the loop package. const ( ErrLoopPanicked = iota + 1 ErrHandlingFailed <API key> ErrKilledBySentinel ) var errorMessages = errors.Messages{ ErrLoopPanicked: "loop panicked: %v", ErrHandlingFailed: "error handling for %q failed", <API key>: "cannot restart unstopped %q", ErrKilledBySentinel: "%q killed by sentinel", } // TESTING // <API key> allows to check, if a loop or // sentinel has been stopped due to internal reasons or // after the error of another loop or sentinel. func <API key>(err error) bool { return errors.IsError(err, ErrKilledBySentinel) } // EOF
// modification, are permitted provided that the following conditions // are met: // and/or other materials provided with the distribution. // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. #if !SILVERLIGHT namespace NLog.LayoutRenderers { using System.Text; using Config; using Internal; <summary> Application setting. </summary> <remarks> Use this layout renderer to insert the value of an application setting stored in the application's App.config or Web.config file. </remarks> <code lang="NLog Layout Renderer"> ${appsetting:name=mysetting:default=mydefault} - produces "mydefault" if no appsetting </code> [LayoutRenderer("appsetting")] public class <API key> : LayoutRenderer { private <API key> <API key> = new <API key>(); <summary> The AppSetting name. </summary> [RequiredParameter] [DefaultParameter] public string Name { get; set; } <summary> The AppSetting name (Easier documentation and improves consistency) </summary> public string Item { get => Name; set => Name = value; } <summary> The default value to render if the AppSetting value is null. </summary> public string Default { get; set; } internal <API key> <API key> { get => <API key>; set => <API key> = value; } <summary> Renders the specified application setting or default value and appends it to the specified <see cref="StringBuilder" />. </summary> <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (Name == null) return; string value = AppSettingValue; if (value == null && Default != null) value = Default; if (string.IsNullOrEmpty(value) == false) builder.Append(value); } private bool <API key>; private string _appSettingValue; private string AppSettingValue { get { if (<API key> == false) { _appSettingValue = <API key>.AppSettings[Name]; <API key> = true; } return _appSettingValue; } } } } #endif
;(function($n2){ "use strict"; // If OpenLayers is not included, do not process further if( typeof OpenLayers === 'undefined' ) return; /** * Class: OpenLayers.Format.Couch * A parser to read/write CouchDb documents. Create a new instance with the * <OpenLayers.Format.Couch> constructor. * * Inherits from: * - <OpenLayers.Format> */ OpenLayers.Format.Couch = OpenLayers.Class(OpenLayers.Format, { /** * Projection that the database uses for the given geometry */ dbProj: null, /** * Constructor: OpenLayers.Format.Couch * Create a new parser for JSON. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ initialize: function(options) { OpenLayers.Format.prototype.initialize.apply(this, [options]); this.dbProj = new OpenLayers.Projection('EPSG:4326'); }, /** * APIMethod: read * Accepts a CouchDb response and returns an array of features. * * Parameters: * response - {Array} CouchDb documents * * Returns: * {Object} An object, array, string, or number . */ read: function(docs) { try { var results = []; for(var i=0,e=docs.length; i<e; ++i) { var doc = docs[i]; var id = null; var geom = null; if( doc._id ) { id = doc._id; }; if( doc.nunaliit_geom.wkt ) { geom = OpenLayers.Geometry.fromWKT(doc.nunaliit_geom.wkt); if( geom ){ if( !$n2.olUtils.isValidGeom(geom) ) { geom = null; }; }; if( !geom ){ $n2.log('Invalid WKT('+doc._id+'): '+doc.nunaliit_geom.wkt); }; }; if( id && geom ) { var f = new OpenLayers.Feature.Vector(geom,doc); f.fid = id; f.n2GeomProj = this.dbProj; results.push(f); } else { $n2.log('Invalid feature',doc); }; }; return results; } catch(e) { $n2.log('Error during CouchDB format read',e); } return null; }, /** * APIMethod: write * Serialize an object. * * Parameters: * features - {Array} Features to be serialized. * * Returns: * {Array} Documents to be sent to CouchDb. */ write: function(features) { var result = []; for(var i=0,e=features.length; i<e; ++i) { var f = features[i]; var data = f.data; if( null == data ) { data = {}; }; // Add FID if( f.fid ) { data._id = f.fid; }; // Update geometry var geom = f.geometry; var mapProjection = f.layer.map.getProjectionObject(); if( f.layer.projection && mapProjection && f.layer.projection.getCode() != mapProjection.getCode() ) { geom = geom.clone(); geom.transform(mapProjection, f.layer.projection); }; if( !data.nunaliit_geom ) data.nunaliit_geom = { nunaliit_type: 'geometry' }; data.nunaliit_geom.wkt = geom.toString(); var bbox = geom.getBounds(); data.nunaliit_geom.bbox = [bbox.left,bbox.bottom,bbox.right,bbox.top]; if( data.nunaliit_geom.simplified ){ delete data.nunaliit_geom.simplified; }; result.push( data ); }; return result; }, CLASS_NAME: "OpenLayers.Format.Couch" }); /** * Class: OpenLayers.Protocol.Couch * A basic protocol for accessing vector layers from couchDb. Create a new instance with the * <OpenLayers.Protocol.Couch> constructor. * * Inherits from: * - <OpenLayers.Protocol> */ OpenLayers.Protocol.Couch = OpenLayers.Class(OpenLayers.Protocol, { /** * Property: documentSource * {Object} Instance of DocumentSource to access map geometries. */ documentSource: null, /** * Property: layerName * {String} Name of layer associated with seeked features. Null if all geometries * are to be accepted. */ layerName: null, /** * Property: callback * {Object} Function to be called when the <read>, <create>, * <update>, <delete> or <commit> operation completes, read-only, * set through the options passed to the constructor. */ callback: null, /** * Property: scope * {Object} Callback execution scope, read-only, set through the * options passed to the constructor. */ scope: null, /** * Property: notifications * {Object} Set of functions to call to report on bubsy status */ notifications: null, /** * Property: wildcarded. * {Boolean} If true percent signs are added around values * read from LIKE filters, for example if the protocol * read method is passed a LIKE filter whose property * is "foo" and whose value is "bar" the string * "foo__ilike=%bar%" will be sent in the query string; * defaults to false. */ wildcarded: false, /** * Constructor: OpenLayers.Protocol.Couch * A class for giving layers generic HTTP protocol. * * Parameters: * options - {Object} Optional object whose properties will be set on the * instance. * * Valid options include: * view - {String} Name of couchDb view, including design url. * format - {<OpenLayers.Format>} * callback - {Function} * scope - {Object} */ initialize: function(options) { options = options || {}; // Install default format if( !options.format ) { options.format = new OpenLayers.Format.Couch(); }; options.projection = new OpenLayers.Projection('EPSG:4326'); OpenLayers.Protocol.prototype.initialize.apply(this, arguments); }, /** * APIMethod: destroy * Clean up the protocol. */ destroy: function() { OpenLayers.Protocol.prototype.destroy.apply(this); }, /** * APIMethod: read * Construct a request for reading new features. * * Parameters: * options - {Object} Optional object for configuring the request. * This object is modified and should not be reused. * * Valid options: * view - {String} Name of couchDb view, including design url. * filter - {<OpenLayers.Filter>} Filter to get serialized as a * query string. * * Returns: * {<OpenLayers.Protocol.Response>} A response object, whose "priv" property * references the HTTP request, this object is also passed to the * callback function when the request completes, its "features" property * is then populated with the the features received from the server. */ read: function(options) { var _this = this; if( this.notifications && this.notifications.readStart ){ this.notifications.readStart(); }; // Obtain layer var layer = options.object; OpenLayers.Protocol.prototype.read.apply(this, arguments); options = OpenLayers.Util.applyDefaults(options, this.options); var resp = new OpenLayers.Protocol.Response({requestType: 'read'}); // Add BBOX tiling var bounds = this.getBboxFromFilter(options.filter); var fids = this.getFidsFromFilter(options.filter); var layerName = ('string' === typeof(options.layerName) ? options.layerName : null); var projectionCode = null; var mapProjection = null; if( layer && layer.map ){ mapProjection = layer.map.getProjectionObject(); projectionCode = mapProjection.getCode(); }; this.documentSource.<API key>({ docIds: fids ,layerId: layerName ,bbox: bounds ,projectionCode: projectionCode ,onSuccess: function(docs){ _this.handleRead(resp, options, docs); } ,onError: function(errorMsg){ $n2.log(errorMsg); if( _this.notifications && _this.notifications.readEnd ){ _this.notifications.readEnd(); }; } }); return resp; }, /** * Method: handleRead * Individual callbacks are created for read, create and update, should * a subclass need to override each one separately. * * Parameters: * resp - {<OpenLayers.Protocol.Response>} The response object to pass to * the user callback. * options - {Object} The user options passed to the read call. */ handleRead: function(resp, options, docs) { var _this = this; if(options.callback) { resp.features = this.format.read(docs); // Sorting now saves on rendering a re-sorting later $n2.olUtils.sortFeatures(resp.features); resp.code = OpenLayers.Protocol.Response.SUCCESS; options.callback.call(options.scope, resp); window.setTimeout(function(){ if( _this.notifications && _this.notifications.readEnd ){ _this.notifications.readEnd(); }; },0); }; }, /** * APIMethod: create * Construct a request for writing newly created features. * * Parameters: * features - {Array({<OpenLayers.Feature.Vector>})} or * {<OpenLayers.Feature.Vector>} * options - {Object} Optional object for configuring the request. * This object is modified and should not be reused. * * Returns: * {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response> * object, whose "priv" property references the HTTP request, this * object is also passed to the callback function when the request * completes, its "features" property is then populated with the * the features received from the server. */ create: function(features, options) { options = OpenLayers.Util.applyDefaults(options, this.options); var documents = this.format.write(features); // Apply layer name, if needed if( options.layerName ) { for(var i=0,e=documents.length; i<e; ++i) { var doc = documents[i]; if( !doc.nunaliit_layers ) { doc.nunaliit_layers = []; }; if( jQuery.inArray(options.layerName, doc.nunaliit_layers) < 0 ) { doc.nunaliit_layers.push(options.layerName); }; }; }; var resp = new OpenLayers.Protocol.Response({ reqFeatures: features, requestType: "create" }); var _this = this; this.db.bulkDocuments(documents,{ onSuccess: function(docIds){ _this.handleCreate(resp, options, docIds); } ,onError: function(errorMsg){ $n2.reportError(errorMsg); } }); return resp; }, /** * Method: handleCreate * Called when the request issued by <create> is complete. May be overridden * by subclasses. * * Parameters: * resp - {<OpenLayers.Protocol.Response>} The response object to pass to * any user callback. * options - {Object} The user options passed to the create call. */ handleCreate: function(resp, options, docIds) { // Update features with FIDs and _rev var features = resp.reqFeatures; var insertedFeatures = []; if( features.length != docIds.length ) { // There is an error $n2.reportError($n2.ERROR_NO_SUPRESS, 'Invalid feature bulk create'); } else { for(var i=0,e=docIds.length; i<e; ++i) { var f = features[i]; var d = docIds[i]; if( d.error ) { if( d.reason ) { $n2.reportError($n2.ERROR_NO_SUPRESS, d.error+' : '+d.reason); } else { $n2.reportError($n2.ERROR_NO_SUPRESS, d.error); }; } else { f.fid = d.id; if( f.data ) { f.data._id = d.id; f.data._rev = d.rev; }; if( f.attribute ) { f.attribute._id = d.id; f.attribute._rev = d.rev; }; insertedFeatures.push(f); }; }; }; // Perform call back, if needed if(options.callback && insertedFeatures.length > 0) { resp.features = insertedFeatures; resp.code = OpenLayers.Protocol.Response.SUCCESS; options.callback.call(options.scope, resp); } }, /** * APIMethod: update * Construct a request updating modified feature. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} * options - {Object} Optional object for configuring the request. * This object is modified and should not be reused. * * Returns: * {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response> * object, whose "priv" property references the HTTP request, this * object is also passed to the callback function when the request * completes, its "features" property is then populated with the * the feature received from the server. */ update: function(feature, options) { options = options || {}; options = OpenLayers.Util.applyDefaults(options, this.options); var documents = this.format.write([feature]); var resp = new OpenLayers.Protocol.Response({ reqFeatures: feature, requestType: "update" }); var _this = this; this.db.updateDocument({ data: documents[0] ,onSuccess: function(docInfo){ _this.handleUpdate(resp, options, docInfo); } ,onError: function(errorMsg){ $n2.reportError(errorMsg); } }); return resp; }, /** * Method: handleUpdate * Called the the request issued by <update> is complete. May be overridden * by subclasses. * * Parameters: * resp - {<OpenLayers.Protocol.Response>} The response object to pass to * any user callback. * options - {Object} The user options passed to the update call. */ handleUpdate: function(resp, options, docInfo) { // Update feature with _rev var feature = resp.reqFeatures; if( feature.data ) { feature.data._rev = docInfo.rev; }; if( feature.attribute ) { feature.attribute._rev = docInfo.rev; }; // Perform call back, if needed if(options.callback) { resp.features = [feature]; resp.code = OpenLayers.Protocol.Response.SUCCESS; options.callback.call(options.scope, resp); } }, /** * APIMethod: delete * Construct a request deleting a removed feature. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} * options - {Object} Optional object for configuring the request. * This object is modified and should not be reused. * * Returns: * {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response> * object, whose "priv" property references the HTTP request, this * object is also passed to the callback function when the request * completes. */ "delete": function(feature, options) { options = options || {}; options = OpenLayers.Util.applyDefaults(options, this.options); var resp = new OpenLayers.Protocol.Response({ reqFeatures: feature, requestType: "delete" }); var _this = this; this.db.deleteDocument({ data: feature.data ,onSuccess: function(docInfo){ _this.handleDelete(resp, options, docInfo); } ,onError: function(errorMsg){ $n2.reportError(errorMsg); } }); return resp; }, /** * Method: handleDelete * Called the the request issued by <delete> is complete. May be overridden * by subclasses. * * Parameters: * resp - {<OpenLayers.Protocol.Response>} The response object to pass to * any user callback. * options - {Object} The user options passed to the delete call. */ handleDelete: function(resp, options) { // Perform call back, if needed if(options.callback) { resp.code = OpenLayers.Protocol.Response.SUCCESS; options.callback.call(options.scope, resp); } }, /** * APIMethod: commit * Iterate over each feature and take action based on the feature state. * Possible actions are create, update and delete. * * Parameters: * features - {Array({<OpenLayers.Feature.Vector>})} * options - {Object} Optional object for setting up intermediate commit * callbacks. * * Valid options: * create - {Object} Optional object to be passed to the <create> method. * update - {Object} Optional object to be passed to the <update> method. * delete - {Object} Optional object to be passed to the <delete> method. * callback - {Function} Optional function to be called when the commit * is complete. * scope - {Object} Optional object to be set as the scope of the callback. * * Returns: * {Array(<OpenLayers.Protocol.Response>)} An array of response objects, * one per request made to the server, each object's "priv" property * references the corresponding HTTP request. */ commit: function(features, options) { options = OpenLayers.Util.applyDefaults(options, this.options); var resp = [], nResponses = 0; // Divide up features before issuing any requests. This properly // counts requests in the event that any responses come in before // all requests have been issued. var types = {}; types[OpenLayers.State.INSERT] = []; types[OpenLayers.State.UPDATE] = []; types[OpenLayers.State.DELETE] = []; var feature, list, requestFeatures = []; for(var i=0, len=features.length; i<len; ++i) { feature = features[i]; list = types[feature.state]; if(list) { list.push(feature); requestFeatures.push(feature); } } // tally up number of requests var nRequests = (types[OpenLayers.State.INSERT].length > 0 ? 1 : 0) + types[OpenLayers.State.UPDATE].length + types[OpenLayers.State.DELETE].length; // This response will be sent to the final callback after all the others // have been fired. var success = true; var finalResponse = new OpenLayers.Protocol.Response({ reqFeatures: requestFeatures }); function insertCallback(response) { var len = response.features ? response.features.length : 0; var fids = new Array(len); for(var i=0; i<len; ++i) { fids[i] = response.features[i].fid; } finalResponse.insertIds = fids; callback.apply(this, [response]); } function callback(response) { this.callUserCallback(response, options); success = success && response.success(); nResponses++; if (nResponses >= nRequests) { if (options.callback) { finalResponse.code = success ? OpenLayers.Protocol.Response.SUCCESS : OpenLayers.Protocol.Response.FAILURE; options.callback.apply(options.scope, [finalResponse]); } } } // start issuing requests var queue = types[OpenLayers.State.INSERT]; if(queue.length > 0) { resp.push(this.create( queue, OpenLayers.Util.applyDefaults( {callback: insertCallback, scope: this}, options.create ) )); } queue = types[OpenLayers.State.UPDATE]; for(var i=queue.length-1; i>=0; --i) { resp.push(this.update( queue[i], OpenLayers.Util.applyDefaults( {callback: callback, scope: this}, options.update )) ); } queue = types[OpenLayers.State.DELETE]; for(var i=queue.length-1; i>=0; --i) { resp.push(this["delete"]( queue[i], OpenLayers.Util.applyDefaults( {callback: callback, scope: this}, options["delete"] )) ); } return resp; }, /** * APIMethod: abort * Abort an ongoing request, the response object passed to * this method must come from this HTTP protocol (as a result * of a create, read, update, delete or commit operation). * * Parameters: * response - {<OpenLayers.Protocol.Response>} */ abort: function(response) { if (response) { //response.priv.abort(); // not supported in CouchDb? } }, /** * Method: callUserCallback * This method is used from within the commit method each time an * an HTTP response is received from the server, it is responsible * for calling the user-supplied callbacks. * * Parameters: * resp - {<OpenLayers.Protocol.Response>} * options - {Object} The map of options passed to the commit call. */ callUserCallback: function(resp, options) { var opt = options[resp.requestType]; if(opt && opt.callback) { opt.callback.call(opt.scope, resp); } }, /** * Method: getBboxFromFilter * This method is used to find the bounding box filter within the given * filter and return the information in a format useable by the tiling system. * * Parameters: * filter - {<OpenLayers.Filter>} */ getBboxFromFilter: function(filter) { if( !filter ) return null; if( filter.type === OpenLayers.Filter.Spatial.BBOX ) { // This is a BBOX return [filter.value.left,filter.value.bottom,filter.value.right,filter.value.top] } if( filter.filters ) { // Logical, continue search for(var i=0,e=filter.filters.length; i<e; ++i) { var bounds = this.getBboxFromFilter(filter.filters[i]); if( bounds ) return bounds; } } return null; }, /** * Method: getFidsFromFilter * This method is used to find the FID filter within the given * filter and return the information in a format useable by the view system. * * Parameters: * filter - {<OpenLayers.Filter>} */ getFidsFromFilter: function(filter) { if( !filter ) return null; if( filter.CLASS_NAME === 'OpenLayers.Filter.FeatureId' ) { // This is a FIDs return filter.fids; } if( filter.filters ) { // Logical, continue search for(var i=0,e=filter.filters.length; i<e; ++i) { var fids = this.getFidsFromFilter(filter.filters[i]); if( fids ) return fids; } } return null; }, CLASS_NAME: "OpenLayers.Protocol.Couch" }); /** * Property: OpenLayers.Protocol.Couch.COMP_TYPE_TO_OP_STR * {Object} A private class-level property mapping the * OpenLayers.Filter.Comparison types to the operation * strings of the protocol. */ (function() { var o = OpenLayers.Protocol.Couch.COMP_TYPE_TO_OP_STR = {}; o[OpenLayers.Filter.Comparison.EQUAL_TO] = "eq"; o[OpenLayers.Filter.Comparison.NOT_EQUAL_TO] = "ne"; o[OpenLayers.Filter.Comparison.LESS_THAN] = "lt"; o[OpenLayers.Filter.Comparison.<API key>] = "lte"; o[OpenLayers.Filter.Comparison.GREATER_THAN] = "gt"; o[OpenLayers.Filter.Comparison.<API key>] = "gte"; o[OpenLayers.Filter.Comparison.LIKE] = "ilike"; })(); })(nunaliit2);
#!/usr/bin/python3 import struct import sys if len(sys.argv) == 1: print("python karel_mdo_convert.py mundo.mdo") sys.exit(1) f = open(sys.argv[1], "rb") data = f.read() f.close() worldname = sys.argv[1] if '/' in worldname: worldname = worldname[worldname.rfind('/')+1:] if '.' in worldname: worldname = worldname[:worldname.rfind('.')] kec = False for extension in ("kec", "KEC"): try: f = open(sys.argv[1][:sys.argv[1].rfind(".")] + "." + extension, "rb") kec = f.read() f.close() break except Exception: pass if not kec: print("%s.kec not found" % worldname) sys.exit(1) (x1, width, height, buzzers, karelx, karely, karelorient, wallcount, heapcount, x10) = struct.unpack("HHHHHHHHHH", data[10:30]) tuples = [struct.unpack("HHH", data[i:i+6]) for i in range(30, len(data), 6)] kec = [struct.unpack("HHH", kec[i:i+6]) for i in range(0, len(kec), 6)] maxlines = kec[0][1] if kec[0][0] else 10000000 maxmove = kec[1][1] if kec[1][0] else False maxturnleft = kec[2][1] if kec[2][0] else False maxpickbeeper = kec[3][1] if kec[3][0] else False maxputbeeper = kec[4][1] if kec[4][0] else False maxkarelbeepers = kec[5][1] if kec[5][0] else False maxbeepers = kec[6][1] if kec[6][0] else False endposition = kec[7][1:] if kec[7][0] else False endorientation = ["NORTE", "ESTE", "SUR", "OESTE"][kec[8][1]] if kec[8][0] else False dumpcount = kec[9][1] if kec[9][0] else 0 def formatbuzzers(b): if b == 65535: return "INFINITO" else: return "%d" % b def isborder(wall, w, h): if wall[0] == wall[2]: return wall[0] in (0, w) if wall[1] == wall[3]: return wall[1] in (0, h) def decodewalls(t, w, h): dx = ((-1, 0, -1, -1), (0, 0, 0, -1)) dy = ((0, -1, -1, -1), (0, 0, -1, 0)) for i in range(4): if (t[2] & (1 << i)): wall = (t[0] + dx[0][i], t[1] + dy[0][i], t[0] + dx[1][i], t[1] + dy[1][i]) if not isborder(wall, w, h): yield wall def encodewall(w): if w[0] == w[2]: return 'x1="%d" y1="%d" y2="%d"' % (w[0], min(w[1], w[3]), max(w[1], w[3])) elif w[1] == w[3]: return 'x1="%d" x2="%d" y1="%d"' % (min(w[0], w[2]), max(w[0], w[2]), w[1]) else: sys.exit(1) def generateIn(): print("<ejecucion>") if maxmove != False or maxturnleft != False or maxpickbeeper != False or maxputbeeper != False: print(" <condiciones <API key>=\"%d\" longitudStack=\"65000\">" % maxlines) if maxmove != False: print(' <comando nombre="AVANZA" <API key>="%d" />' % maxmove) if maxturnleft != False: print(' <comando nombre="GIRA_IZQUIERDA" <API key>="%d" />' % maxturnleft) if maxpickbeeper != False: print(' <comando nombre="COGE_ZUMBADOR" <API key>="%d" />' % maxpickbeeper) if maxputbeeper != False: print(' <comando nombre="DEJA_ZUMBADOR" <API key>="%d" />' % maxputbeeper) print(" </condiciones>") else: print(" <condiciones <API key>=\"%d\" longitudStack=\"65000\" />" % maxlines) print(" <mundos>") print(" <mundo nombre=\"mundo_0\" ancho=\"%d\" alto=\"%d\">" % (width, height)) for i in range(wallcount): for wall in decodewalls(tuples[i], width, height): print(" <pared %s/>" % encodewall(wall)) for i in range(wallcount, wallcount + heapcount): print(" <monton x=\"%d\" y=\"%d\" zumbadores=\"%d\"/>" % tuples[i]) for i in range(10, 10 + dumpcount): print(" <posicionDump x=\"%d\" y=\"%d\" />" % kec[i][:2]) print(" </mundo>") print(" </mundos>") print(" <programas tipoEjecucion=\"CONTINUA\" <API key>=\"1\" <API key>=\"0\">") print(" <programa nombre=\"p1\" ruta=\"{$2$}\" mundoDeEjecucion=\"mundo_0\" xKarel=\"%d\" yKarel=\"%s\" direccionKarel=\"%s\" mochilaKarel=\"%s\" >" \ % (karelx, karely, ["", "NORTE", "ESTE", "SUR", "OESTE"][karelorient], formatbuzzers(buzzers))) if dumpcount: print(" <despliega tipo=\"MUNDO\" />") if endorientation: print(" <despliega tipo=\"ORIENTACION\" />") if endposition: print(" <despliega tipo=\"POSICION\" />") print(" </programa>") print(" </programas>") print("</ejecucion>") generateIn()
<?php /** * CChainedLogFilter allows you to attach multiple log filters to a log route (See {@link CLogRoute::$filter} for details). * * @author Carsten Brandt <mail@cebe.cc> * @package system.logging * @since 1.1.13 */ class CChainedLogFilter extends CComponent implements ILogFilter { /** * * @var array list of filters to apply to the logs. * The value of each array element will be passed to {@link Yii::createComponent} to create * a log filter object. As a result, this can be either a string representing the * filter class name or an array representing the filter configuration. * In general, the log filter classes should implement {@link ILogFilter} interface. * Filters will be applied in the order they are defined. */ public $filters = array (); /** * Filters the given log messages by applying all filters configured by {@link filters}. * * @param array $logs * the log messages */ public function filter(&$logs) { foreach ( $this->filters as $filter ) Yii::createComponent ( $filter )->filter ( $logs ); } }
/* * This file is auto-generated. DO NOT MODIFY. * Original file: C:\\Users\\misoch\\<API key>\\CardboardKeyboard\\openCVLibrary310\\src\\main\\aidl\\org\\opencv\\engine\\<API key>.aidl */ package org.opencv.engine; /** * Class provides a Java interface for OpenCV Engine Service. It's synchronous with native OpenCVEngine class. */ public interface <API key> extends android.os.IInterface { /** Local-side IPC implementation stub class. */ public static abstract class Stub extends android.os.Binder implements org.opencv.engine.<API key> { private static final java.lang.String DESCRIPTOR = "org.opencv.engine.<API key>"; /** Construct the stub at attach it to the interface. */ public Stub() { this.attachInterface(this, DESCRIPTOR); } /** * Cast an IBinder object into an org.opencv.engine.<API key> interface, * generating a proxy if needed. */ public static org.opencv.engine.<API key> asInterface(android.os.IBinder obj) { if ((obj==null)) { return null; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin!=null)&&(iin instanceof org.opencv.engine.<API key>))) { return ((org.opencv.engine.<API key>)iin); } return new org.opencv.engine.<API key>.Stub.Proxy(obj); } @Override public android.os.IBinder asBinder() { return this; } @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { switch (code) { case <API key>: { reply.writeString(DESCRIPTOR); return true; } case <API key>: { data.enforceInterface(DESCRIPTOR); int _result = this.getEngineVersion(); reply.writeNoException(); reply.writeInt(_result); return true; } case <API key>: { data.enforceInterface(DESCRIPTOR); java.lang.String _arg0; _arg0 = data.readString(); java.lang.String _result = this.getLibPathByVersion(_arg0); reply.writeNoException(); reply.writeString(_result); return true; } case <API key>: { data.enforceInterface(DESCRIPTOR); java.lang.String _arg0; _arg0 = data.readString(); boolean _result = this.installVersion(_arg0); reply.writeNoException(); reply.writeInt(((_result)?(1):(0))); return true; } case <API key>: { data.enforceInterface(DESCRIPTOR); java.lang.String _arg0; _arg0 = data.readString(); java.lang.String _result = this.getLibraryList(_arg0); reply.writeNoException(); reply.writeString(_result); return true; } } return super.onTransact(code, data, reply, flags); } private static class Proxy implements org.opencv.engine.<API key> { private android.os.IBinder mRemote; Proxy(android.os.IBinder remote) { mRemote = remote; } @Override public android.os.IBinder asBinder() { return mRemote; } public java.lang.String <API key>() { return DESCRIPTOR; } /** * @return Returns service version. */ @Override public int getEngineVersion() throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); int _result; try { _data.writeInterfaceToken(DESCRIPTOR); mRemote.transact(Stub.<API key>, _data, _reply, 0); _reply.readException(); _result = _reply.readInt(); } finally { _reply.recycle(); _data.recycle(); } return _result; } /** * Finds an installed OpenCV library. * @param OpenCV version. * @return Returns path to OpenCV native libs or an empty string if OpenCV can not be found. */ @Override public java.lang.String getLibPathByVersion(java.lang.String version) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); java.lang.String _result; try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeString(version); mRemote.transact(Stub.<API key>, _data, _reply, 0); _reply.readException(); _result = _reply.readString(); } finally { _reply.recycle(); _data.recycle(); } return _result; } /** * Tries to install defined version of OpenCV from Google Play Market. * @param OpenCV version. * @return Returns true if installation was successful or OpenCV package has been already installed. */ @Override public boolean installVersion(java.lang.String version) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); boolean _result; try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeString(version); mRemote.transact(Stub.<API key>, _data, _reply, 0); _reply.readException(); _result = (0!=_reply.readInt()); } finally { _reply.recycle(); _data.recycle(); } return _result; } /** * Returns list of libraries in loading order, separated by semicolon. * @param OpenCV version. * @return Returns names of OpenCV libraries, separated by semicolon. */ @Override public java.lang.String getLibraryList(java.lang.String version) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); java.lang.String _result; try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeString(version); mRemote.transact(Stub.<API key>, _data, _reply, 0); _reply.readException(); _result = _reply.readString(); } finally { _reply.recycle(); _data.recycle(); } return _result; } } static final int <API key> = (android.os.IBinder.<API key> + 0); static final int <API key> = (android.os.IBinder.<API key> + 1); static final int <API key> = (android.os.IBinder.<API key> + 2); static final int <API key> = (android.os.IBinder.<API key> + 3); } /** * @return Returns service version. */ public int getEngineVersion() throws android.os.RemoteException; /** * Finds an installed OpenCV library. * @param OpenCV version. * @return Returns path to OpenCV native libs or an empty string if OpenCV can not be found. */ public java.lang.String getLibPathByVersion(java.lang.String version) throws android.os.RemoteException; /** * Tries to install defined version of OpenCV from Google Play Market. * @param OpenCV version. * @return Returns true if installation was successful or OpenCV package has been already installed. */ public boolean installVersion(java.lang.String version) throws android.os.RemoteException; /** * Returns list of libraries in loading order, separated by semicolon. * @param OpenCV version. * @return Returns names of OpenCV libraries, separated by semicolon. */ public java.lang.String getLibraryList(java.lang.String version) throws android.os.RemoteException; }
#ifndef <API key> #define <API key> #include <stddef.h> #include <limits> #include <type_traits> #include "base/numerics/clamped_math_impl.h" namespace base { namespace internal { template <typename T> class ClampedNumeric { static_assert(std::is_arithmetic<T>::value, "ClampedNumeric<T>: T must be a numeric type."); public: using type = T; constexpr ClampedNumeric() : value_(0) {} // Copy constructor. template <typename Src> constexpr ClampedNumeric(const ClampedNumeric<Src>& rhs) : value_(saturated_cast<T>(rhs.value_)) {} template <typename Src> friend class ClampedNumeric; // This is not an explicit constructor because we implicitly upgrade regular // numerics to ClampedNumerics to make them easier to use. template <typename Src> constexpr ClampedNumeric(Src value) // NOLINT(runtime/explicit) : value_(saturated_cast<T>(value)) { static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric."); } // This is not an explicit constructor because we want a seamless conversion // from StrictNumeric types. template <typename Src> constexpr ClampedNumeric( StrictNumeric<Src> value) // NOLINT(runtime/explicit) : value_(saturated_cast<T>(static_cast<Src>(value))) {} // Returns a ClampedNumeric of the specified type, cast from the current // ClampedNumeric, and saturated to the destination type. template <typename Dst> constexpr ClampedNumeric<typename UnderlyingType<Dst>::type> Cast() const { return *this; } // Prototypes for the supported arithmetic operator overloads. template <typename Src> constexpr ClampedNumeric& operator+=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator-=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator*=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator/=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator%=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator<<=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator>>=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator&=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator|=(const Src rhs); template <typename Src> constexpr ClampedNumeric& operator^=(const Src rhs); constexpr ClampedNumeric operator-() const { // The negation of two's complement int min is int min, so that's the // only overflow case where we will saturate. return ClampedNumeric<T>(SaturatedNegWrapper(value_)); } constexpr ClampedNumeric operator~() const { return ClampedNumeric<decltype(InvertWrapper(T()))>(InvertWrapper(value_)); } constexpr ClampedNumeric Abs() const { // The negation of two's complement int min is int min, so that's the // only overflow case where we will saturate. return ClampedNumeric<T>(SaturatedAbsWrapper(value_)); } template <typename U> constexpr ClampedNumeric<typename MathWrapper<ClampedMaxOp, T, U>::type> Max( const U rhs) const { using result_type = typename MathWrapper<ClampedMaxOp, T, U>::type; return ClampedNumeric<result_type>( ClampedMaxOp<T, U>::Do(value_, Wrapper<U>::value(rhs))); } template <typename U> constexpr ClampedNumeric<typename MathWrapper<ClampedMinOp, T, U>::type> Min( const U rhs) const { using result_type = typename MathWrapper<ClampedMinOp, T, U>::type; return ClampedNumeric<result_type>( ClampedMinOp<T, U>::Do(value_, Wrapper<U>::value(rhs))); } // This function is available only for integral types. It returns an unsigned // integer of the same width as the source type, containing the absolute value // of the source, and properly handling signed min. constexpr ClampedNumeric<typename <API key><T>::type> UnsignedAbs() const { return ClampedNumeric<typename <API key><T>::type>( SafeUnsignedAbs(value_)); } constexpr ClampedNumeric& operator++() { *this += 1; return *this; } constexpr ClampedNumeric operator++(int) { ClampedNumeric value = *this; *this += 1; return value; } constexpr ClampedNumeric& operator *this -= 1; return *this; } constexpr ClampedNumeric operator--(int) { ClampedNumeric value = *this; *this -= 1; return value; } // These perform the actual math operations on the ClampedNumerics. // Binary arithmetic operations. template <template <typename, typename, typename> class M, typename L, typename R> static constexpr ClampedNumeric MathOp(const L lhs, const R rhs) { using Math = typename MathWrapper<M, L, R>::math; return ClampedNumeric<T>( Math::template Do<T>(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs))); } // Assignment arithmetic operations. template <template <typename, typename, typename> class M, typename R> constexpr ClampedNumeric& MathOp(const R rhs) { using Math = typename MathWrapper<M, T, R>::math; *this = ClampedNumeric<T>(Math::template Do<T>(value_, Wrapper<R>::value(rhs))); return *this; } template <typename Dst> constexpr operator Dst() const { return saturated_cast<typename <API key><Dst>::type>( value_); } // This method extracts the raw integer value without saturating it to the // destination type as the conversion operator does. This is useful when // e.g. assigning to an auto type or passing as a deduced template parameter. constexpr T RawValue() const { return value_; } private: T value_; // These wrappers allow us to handle state the same way for both // ClampedNumeric and POD arithmetic types. template <typename Src> struct Wrapper { static constexpr Src value(Src value) { return static_cast<typename UnderlyingType<Src>::type>(value); } }; }; // Convience wrapper to return a new ClampedNumeric from the provided arithmetic // or ClampedNumericType. template <typename T> constexpr ClampedNumeric<typename UnderlyingType<T>::type> MakeClampedNum( const T value) { return value; } // Overload the ostream output operator to make logging work nicely. template <typename T> std::ostream& operator<<(std::ostream& os, const ClampedNumeric<T>& value) { os << static_cast<T>(value); return os; } // These implement the variadic wrapper for the math operations. template <template <typename, typename, typename> class M, typename L, typename R> constexpr ClampedNumeric<typename MathWrapper<M, L, R>::type> ClampMathOp( const L lhs, const R rhs) { using Math = typename MathWrapper<M, L, R>::math; return ClampedNumeric<typename Math::result_type>::template MathOp<M>(lhs, rhs); } // General purpose wrapper template for arithmetic operations. template <template <typename, typename, typename> class M, typename L, typename R, typename... Args> constexpr ClampedNumeric<typename ResultType<M, L, R, Args...>::type> ClampMathOp(const L lhs, const R rhs, const Args... args) { return ClampMathOp<M>(ClampMathOp<M>(lhs, rhs), args...); } <API key>(Clamped, Clamp, Add, +, +=) <API key>(Clamped, Clamp, Sub, -, -=) <API key>(Clamped, Clamp, Mul, *, *=) <API key>(Clamped, Clamp, Div, /, /=) <API key>(Clamped, Clamp, Mod, %, %=) <API key>(Clamped, Clamp, Lsh, <<, <<=) <API key>(Clamped, Clamp, Rsh, >>, >>=) <API key>(Clamped, Clamp, And, &, &=) <API key>(Clamped, Clamp, Or, |, |=) <API key>(Clamped, Clamp, Xor, ^, ^=) <API key>(Clamped, Clamp, Max) <API key>(Clamped, Clamp, Min) <API key>(Clamped, IsLess, <); <API key>(Clamped, IsLessOrEqual, <=); <API key>(Clamped, IsGreater, >); <API key>(Clamped, IsGreaterOrEqual, >=); <API key>(Clamped, IsEqual, ==); <API key>(Clamped, IsNotEqual, !=); } // namespace internal using internal::ClampAdd; using internal::ClampAnd; using internal::ClampDiv; using internal::ClampedNumeric; using internal::ClampLsh; using internal::ClampMax; using internal::ClampMin; using internal::ClampMod; using internal::ClampMul; using internal::ClampOr; using internal::ClampRsh; using internal::ClampSub; using internal::ClampXor; using internal::MakeClampedNum; } // namespace base #endif // <API key>
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.label.xml Template File: point-flaw-05.tmpl.c */ /* * @description * CWE: 253 Incorrect Check of Return Value * Sinks: sscanf * GoodSink: Correctly check if sscanf() failed * BadSink : Incorrectly check if sscanf() failed * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse) * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #define SRC_STRING "string" /* The two variables below are not defined as "const", but are never assigned any other value, so a tool should be able to identify that reads of these will always return their initialized values. */ static int staticTrue = 1; /* true */ static int staticFalse = 0; /* false */ #ifndef OMITBAD void <API key>() { if(staticTrue) { { /* By initializing dataBuffer, we ensure this will not be the * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */ char dataBuffer[100] = ""; char * data = dataBuffer; /* FLAW: sscanf() might fail, in which case the return value will be EOF (-1), but * we are checking to see if the return value is 0 */ if (sscanf(SRC_STRING, "%99s\0", data) == 0) { printLine("sscanf failed!"); } } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(staticFalse) instead of if(staticTrue) */ static void good1() { if(staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { /* By initializing dataBuffer, we ensure this will not be the * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */ char dataBuffer[100] = ""; char * data = dataBuffer; /* FIX: check for the correct return value */ if (sscanf(SRC_STRING, "%99s\0", data) == EOF) { printLine("sscanf failed!"); } } } } /* good2() reverses the bodies in the if statement */ static void good2() { if(staticTrue) { { /* By initializing dataBuffer, we ensure this will not be the * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgets() and other variants */ char dataBuffer[100] = ""; char * data = dataBuffer; /* FIX: check for the correct return value */ if (sscanf(SRC_STRING, "%99s\0", data) == EOF) { printLine("sscanf failed!"); } } } } void <API key>() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.c Label Definition File: <API key>.label.xml Template File: source-sinks-63a.tmpl.c */ /* * @description * CWE: 404 Improper Resource Shutdown or Release * BadSource: fopen Open a file using fopen() * Sinks: w32CloseHandle * GoodSink: Close the file using fclose() * BadSink : Close the file using CloseHandle * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <windows.h> #ifndef OMITBAD /* bad function declaration */ void <API key>(FILE * * dataPtr); void <API key>() { FILE * data; /* Initialize data */ data = NULL; /* POTENTIAL FLAW: Open a file - need to make sure it is closed properly in the sink */ data = fopen("BadSource_fopen.txt", "w+"); <API key>(&data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G uses the BadSource with the GoodSink */ void <API key>(FILE * * data); static void goodB2G() { FILE * data; /* Initialize data */ data = NULL; /* POTENTIAL FLAW: Open a file - need to make sure it is closed properly in the sink */ data = fopen("BadSource_fopen.txt", "w+"); <API key>(&data); } void <API key>() { goodB2G(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); <API key>(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); <API key>(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#include "gm/gm.h" #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkImageInfo.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkRect.h" #include "include/core/SkShader.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkTileMode.h" #include "include/core/SkTypes.h" #include "src/core/SkCanvasPriv.h" #include "src/gpu/GrCaps.h" #include "src/gpu/GrDirectContextPriv.h" #include "src/gpu/GrFragmentProcessor.h" #include "src/gpu/SkGr.h" #include "src/gpu/SurfaceFillContext.h" #include "src/gpu/effects/GrRRectEffect.h" #include "src/gpu/effects/GrSkSLFP.h" #include "src/gpu/effects/GrTextureEffect.h" #include "src/gpu/glsl/<API key>.h" #include "tools/Resources.h" #include "tools/ToolUtils.h" class SampleCoordEffect : public GrFragmentProcessor { public: inline static constexpr GrProcessor::ClassID CLASS_ID = (GrProcessor::ClassID) 0; SampleCoordEffect(std::unique_ptr<GrFragmentProcessor> child) : INHERITED(CLASS_ID, <API key>) { this->registerChild(std::move(child), SkSL::SampleUsage::Explicit()); } const char* name() const override { return "SampleCoordEffect"; } std::unique_ptr<GrFragmentProcessor> clone() const override { SkASSERT(false); return nullptr; } void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {} bool onIsEqual(const GrFragmentProcessor&) const override { SkASSERT(false); return true; } private: std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override; using INHERITED = GrFragmentProcessor; }; std::unique_ptr<GrFragmentProcessor::ProgramImpl> SampleCoordEffect::onMakeProgramImpl() const { class Impl : public ProgramImpl { public: void emitCode(EmitArgs& args) override { <API key>* fragBuilder = args.fFragBuilder; SkString s1 = this->invokeChild(0, args, "float2(sk_FragCoord.x, sk_FragCoord.y)"); SkString s2 = this->invokeChild(0, args, "float2(sk_FragCoord.x, 512-sk_FragCoord.y)"); fragBuilder->codeAppendf("return (%s + %s) / 2;\n", s1.c_str(), s2.c_str()); } }; return std::make_unique<Impl>(); } <API key>(<API key>, rContext, canvas, 512, 512, ToolUtils::color_to_565(0xFF66AA99)) { auto sfc = SkCanvasPriv::<API key>(canvas); if (!sfc) { return; } SkBitmap bmp; GetResourceAsBitmap("images/mandrill_512_q075.jpg", &bmp); auto view = std::get<0>(<API key>(rContext, bmp, GrMipmapped::kNo)); if (!view) { return; } std::unique_ptr<GrFragmentProcessor> imgFP = GrTextureEffect::Make(std::move(view), bmp.alphaType(), SkMatrix()); auto fp = std::unique_ptr<GrFragmentProcessor>(new SampleCoordEffect(std::move(imgFP))); sfc->fillWithFP(std::move(fp)); }
from __future__ import absolute_import, unicode_literals import warnings from django.core.exceptions import <API key> from django.template.loader import render_to_string from django.utils.safestring import mark_safe from wagtail.utils.deprecation import <API key> from wagtail.wagtailadmin.edit_handlers import BaseChooserPanel from wagtail.wagtailcore.utils import <API key> from .widgets import AdminSnippetChooser class <API key>(BaseChooserPanel): object_type_name = 'item' _target_model = None @classmethod def widget_overrides(cls): return {cls.field_name: AdminSnippetChooser(model=cls.target_model())} @classmethod def target_model(cls): if cls._target_model is None: if cls.snippet_type: # <API key>: The target_model is automatically # detected from the relation, so snippet_type is deprecated. try: cls._target_model = <API key>(cls.snippet_type) except LookupError: raise <API key>( "{0}.snippet_type must be of the form 'app_label.model_name', given {1!r}" .format(cls.__name__, cls.snippet_type) ) except ValueError: raise <API key>( "{0}.snippet_type refers to model {1!r} that has not been installed" .format(cls.__name__, cls.snippet_type) ) else: cls._target_model = cls.model._meta.get_field(cls.field_name).rel.model return cls._target_model def render_as_field(self): instance_obj = self.get_chosen_item() return mark_safe(render_to_string(self.field_template, { 'field': self.bound_field, self.object_type_name: instance_obj, })) class SnippetChooserPanel(object): def __init__(self, field_name, snippet_type=None): self.field_name = field_name if snippet_type is not None: warnings.warn( 'The snippet_type argument to SnippetChooserPanel is deprecated. ' 'The related model is now automatically detected.', <API key>) self.snippet_type = snippet_type def bind_to_model(self, model): return type(str('<API key>'), (<API key>,), { 'model': model, 'field_name': self.field_name, 'snippet_type': self.snippet_type, })
#ifndef __PFMLIB_H__ #define __PFMLIB_H__ #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> #include <unistd.h> #include <inttypes.h> #include <stdio.h> #define LIBPFM_VERSION (4 << 16 | 0) #define PFM_MAJ_VERSION(v) ((v)>>16) #define PFM_MIN_VERSION(v) ((v) & 0xffff) /* * ABI revision level */ #define LIBPFM_ABI_VERSION 0 /* * priv level mask (for dfl_plm) */ #define PFM_PLM0 0x01 /* kernel */ #define PFM_PLM1 0x02 /* not yet used */ #define PFM_PLM2 0x04 /* not yet used */ #define PFM_PLM3 0x08 /* priv level 3, 2, 1 (x86) */ #define PFM_PLMH 0x10 /* hypervisor */ /* * Performance Event Source * * The source is what is providing events. * It can be: * - Hardware Performance Monitoring Unit (PMU) * - a particular kernel subsystem * * Identifiers are guaranteed constant across libpfm revisions * * New sources must be added at the end before PFM_PMU_MAX */ typedef enum { PFM_PMU_NONE= 0, /* no PMU */ PFM_PMU_GEN_IA64, /* Intel IA-64 architected PMU */ PFM_PMU_ITANIUM, /* Intel Itanium */ PFM_PMU_ITANIUM2, /* Intel Itanium 2 */ PFM_PMU_MONTECITO, /* Intel Dual-Core Itanium 2 9000 */ PFM_PMU_AMD64, /* AMD AMD64 (obsolete) */ PFM_PMU_I386_P6, /* Intel PIII (P6 core) */ <API key>, /* Intel Netburst (Pentium 4) */ <API key>, /* Intel Netburst Prescott (Pentium 4) */ PFM_PMU_COREDUO, /* Intel Core Duo/Core Solo */ PFM_PMU_I386_PM, /* Intel Pentium M */ PFM_PMU_INTEL_CORE, /* Intel Core */ PFM_PMU_INTEL_PPRO, /* Intel Pentium Pro */ PFM_PMU_INTEL_PII, /* Intel Pentium II */ PFM_PMU_INTEL_ATOM, /* Intel Atom */ PFM_PMU_INTEL_NHM, /* Intel Nehalem core PMU */ <API key>, /* Intel Nehalem-EX core PMU */ <API key>, /* Intel Nehalem uncore PMU */ <API key>, /* Intel X86 architectural PMU */ PFM_PMU_MIPS_20KC, /* MIPS 20KC */ PFM_PMU_MIPS_24K, /* MIPS 24K */ PFM_PMU_MIPS_25KF, /* MIPS 25KF */ PFM_PMU_MIPS_34K, /* MIPS 34K */ PFM_PMU_MIPS_5KC, /* MIPS 5KC */ PFM_PMU_MIPS_74K, /* MIPS 74K */ PFM_PMU_MIPS_R10000, /* MIPS R10000 */ PFM_PMU_MIPS_R12000, /* MIPS R12000 */ PFM_PMU_MIPS_RM7000, /* MIPS RM7000 */ PFM_PMU_MIPS_RM9000, /* MIPS RM9000 */ PFM_PMU_MIPS_SB1, /* MIPS SB1/SB1A */ PFM_PMU_MIPS_VR5432, /* MIPS VR5432 */ PFM_PMU_MIPS_VR5500, /* MIPS VR5500 */ PFM_PMU_MIPS_ICE9A, /* SiCortex ICE9A */ PFM_PMU_MIPS_ICE9B, /* SiCortex ICE9B */ PFM_PMU_POWERPC, /* POWERPC */ PFM_PMU_CELL, /* IBM CELL */ <API key>, /* UltraSPARC I, II, IIi, and IIe */ <API key>, /* UltraSPARC III */ <API key>, /* UltraSPARC IIIi and IIIi+ */ <API key>, /* UltraSPARC III+ and IV */ <API key>, /* UltraSPARC IV+ */ <API key>, /* Niagara-1 */ <API key>, /* Niagara-2 */ PFM_PMU_PPC970, /* IBM PowerPC 970(FX,GX) */ PFM_PMU_PPC970MP, /* IBM PowerPC 970MP */ PFM_PMU_POWER3, /* IBM POWER3 */ PFM_PMU_POWER4, /* IBM POWER4 */ PFM_PMU_POWER5, /* IBM POWER5 */ PFM_PMU_POWER5p, /* IBM POWER5+ */ PFM_PMU_POWER6, /* IBM POWER6 */ PFM_PMU_POWER7, /* IBM POWER7 */ PFM_PMU_PERF_EVENT, /* perf_event PMU */ PFM_PMU_INTEL_WSM, /* Intel Westmere single-socket (Clarkdale) */ <API key>, /* Intel Westmere dual-socket (Westmere-EP, Gulftwon) */ <API key>, /* Intel Westmere uncore PMU */ PFM_PMU_AMD64_K7, /* AMD AMD64 K7 */ <API key>, /* AMD AMD64 K8 RevB */ <API key>, /* AMD AMD64 K8 RevC */ <API key>, /* AMD AMD64 K8 RevD */ <API key>, /* AMD AMD64 K8 RevE */ <API key>, /* AMD AMD64 K8 RevF */ <API key>, /* AMD AMD64 K8 RevG */ <API key>, /* AMD AMD64 Fam10h Barcelona RevB */ <API key>, /* AMD AMD64 Fam10h Shanghai RevC */ <API key>, /* AMD AMD64 Fam10h Istanbul RevD */ <API key>, /* ARM Cortex A8 */ <API key>, /* ARM Cortex A9 */ PFM_PMU_TORRENT, /* IBM Torrent hub chip */ PFM_PMU_INTEL_SNB, /* Intel Sandy Bridge (single socket) */ <API key>, /* AMD AMD64 Fam14h Bobcat */ <API key>,/* AMD AMD64 Fam15h Interlagos */ <API key>, /* Intel SandyBridge EP */ <API key>, /* AMD AMD64 Fam12h Llano */ <API key>, /* AMD AMD64 Fam11h Turion */ /* MUST ADD NEW PMU MODELS HERE */ PFM_PMU_MAX /* end marker */ } pfm_pmu_t; typedef enum { <API key>=0, /* unknown PMU type */ PFM_PMU_TYPE_CORE, /* processor core PMU */ PFM_PMU_TYPE_UNCORE, /* processor socket-level PMU */ <API key>,/* generic OS-provided PMU */ PFM_PMU_TYPE_MAX } pfm_pmu_type_t; typedef enum { PFM_ATTR_NONE=0, /* no attribute */ PFM_ATTR_UMASK, /* unit mask */ PFM_ATTR_MOD_BOOL, /* register modifier */ <API key>, /* register modifier */ PFM_ATTR_RAW_UMASK, /* raw umask (not user visible) */ PFM_ATTR_MAX /* end-marker */ } pfm_attr_t; /* * define additional event data types beyond historic uint64 * what else can fit in 64 bits? */ typedef enum { PFM_DTYPE_UNKNOWN=0, /* unkown */ PFM_DTYPE_UINT64, /* uint64 */ PFM_DTYPE_INT64, /* int64 */ PFM_DTYPE_DOUBLE, /* IEEE double precision float */ PFM_DTYPE_FIXED, /* 32.32 fixed point */ PFM_DTYPE_RATIO, /* 32/32 integer ratio */ PFM_DTYPE_CHAR8, /* 8 char unterminated string */ PFM_DTYPE_MAX /* end-marker */ } pfm_dtype_t; /* * event attribute control: which layer is controlling * the attribute could be PMU, OS APIs */ typedef enum { <API key> = 0, /* unknown */ PFM_ATTR_CTRL_PMU, /* PMU hardware */ <API key>, /* perf_events kernel interface */ PFM_ATTR_CTRL_MAX } pfm_attr_ctrl_t; /* * OS layer * Used when querying event or attribute information */ typedef enum { PFM_OS_NONE = 0, /* only PMU */ PFM_OS_PERF_EVENT, /* perf_events PMU attribute subset + PMU */ <API key>, /* perf_events all attributes + PMU */ PFM_OS_MAX, } pfm_os_t; /* SWIG doesn't deal well with anonymous nested structures */ #ifdef SWIG #define SWIG_NAME(x) x #else #define SWIG_NAME(x) #endif /* SWIG */ /* * special data type for libpfm error value used to help * with Python support and in particular for SWIG. By using * a specific type we can detect library calls and trap errors * in one SWIG statement as opposed to having to keep track of * each call individually. Programs can use 'int' safely for * the return value. */ typedef int pfm_err_t; /* error if !PFM_SUCCESS */ typedef int os_err_t; /* error if a syscall fails */ typedef struct { const char *name; /* event name */ const char *desc; /* event description */ size_t size; /* struct sizeof */ pfm_pmu_t pmu; /* PMU identification */ pfm_pmu_type_t type; /* PMU type */ int nevents; /* how many events for this PMU */ int first_event; /* opaque index of first event */ int max_encoding; /* max number of uint64_t to encode an event */ int num_cntrs; /* number of generic counters */ int num_fixed_cntrs;/* number of fixed counters */ struct { unsigned int is_present:1; /* present on host system */ unsigned int is_dfl:1; /* is architecture default PMU */ unsigned int reserved_bits:30; } SWIG_NAME(flags); } pfm_pmu_info_t; typedef struct { const char *name; /* event name */ const char *desc; /* event description */ const char *equiv; /* event is equivalent to */ size_t size; /* struct sizeof */ uint64_t code; /* event raw code (not encoding) */ pfm_pmu_t pmu; /* which PMU */ pfm_dtype_t dtype; /* data type of event value */ int idx; /* unique event identifier */ int nattrs; /* number of attributes */ int reserved; /* for future use */ struct { unsigned int is_precise:1; /* precise sampling (Intel X86=PEBS) */ unsigned int reserved_bits:31; } SWIG_NAME(flags); } pfm_event_info_t; typedef struct { const char *name; /* attribute symbolic name */ const char *desc; /* attribute description */ const char *equiv; /* attribute is equivalent to */ size_t size; /* struct sizeof */ uint64_t code; /* attribute code */ pfm_attr_t type; /* attribute type */ int idx; /* attribute opaque index */ pfm_attr_ctrl_t ctrl; /* what is providing attr */ struct { unsigned int is_dfl:1; /* is default umask */ unsigned int is_precise:1; /* Intel X86: supports PEBS */ unsigned int reserved_bits:30; } SWIG_NAME(flags); union { uint64_t dfl_val64; /* default 64-bit value */ const char *dfl_str; /* default string value */ int dfl_bool; /* default boolean value */ int dfl_int; /* default integer value */ } SWIG_NAME(defaults); } <API key>; /* * use with PFM_OS_NONE for <API key>() */ typedef struct { uint64_t *codes; /* out/in: event codes array */ char **fstr; /* out/in: fully qualified event string */ size_t size; /* sizeof struct */ int count; /* out/in: # of elements in array */ int idx; /* out: unique event identifier */ } <API key>; #if __WORDSIZE == 64 #define PFM_PMU_INFO_ABI0 56 #define PFM_EVENT_INFO_ABI0 64 #define PFM_ATTR_INFO_ABI0 64 #define PFM_RAW_ENCODE_ABI0 32 #else #define PFM_PMU_INFO_ABI0 44 #define PFM_EVENT_INFO_ABI0 48 #define PFM_ATTR_INFO_ABI0 48 #define PFM_RAW_ENCODE_ABI0 20 #endif /* * initialization, configuration, errors */ extern pfm_err_t pfm_initialize(void); extern void pfm_terminate(void); extern const char *pfm_strerror(int code); extern int pfm_get_version(void); /* * PMU API */ extern pfm_err_t pfm_get_pmu_info(pfm_pmu_t pmu, pfm_pmu_info_t *output); /* * event API */ extern int pfm_get_event_next(int idx); extern int pfm_find_event(const char *str); extern pfm_err_t pfm_get_event_info(int idx, pfm_os_t os, pfm_event_info_t *output); /* * event encoding API * * content of args depends on value of os (refer to man page) */ extern pfm_err_t <API key>(const char *str, int dfl_plm, pfm_os_t os, void *args); /* * attribute API */ extern pfm_err_t <API key>(int eidx, int aidx, pfm_os_t os, <API key> *output); /* * library validation API */ extern pfm_err_t pfm_pmu_validate(pfm_pmu_t pmu_id, FILE *fp); /* * older encoding API */ extern pfm_err_t <API key>(const char *str, int dfl_plm, char **fstr, int *idx, uint64_t **codes, int *count); /* * error codes */ #define PFM_SUCCESS 0 /* success */ #define PFM_ERR_NOTSUPP -1 /* function not supported */ #define PFM_ERR_INVAL -2 /* invalid parameters */ #define PFM_ERR_NOINIT -3 /* library was not initialized */ #define PFM_ERR_NOTFOUND -4 /* event not found */ #define PFM_ERR_FEATCOMB -5 /* invalid combination of features */ #define PFM_ERR_UMASK -6 /* invalid or missing unit mask */ #define PFM_ERR_NOMEM -7 /* out of memory */ #define PFM_ERR_ATTR -8 /* invalid event attribute */ #define PFM_ERR_ATTR_VAL -9 /* invalid event attribute value */ #define PFM_ERR_ATTR_SET -10 /* attribute value already set */ #define PFM_ERR_TOOMANY -11 /* too many parameters */ #define PFM_ERR_TOOSMALL -12 /* parameter is too small */ /* * event, attribute iterators * must be used because no guarante indexes are contiguous * * for pmu, simply iterate over pfm_pmu_t enum and use * pfm_get_pmu_info() and the is_present field */ #define <API key>(x, z) \ for((x)=0; (x) < (z)->nattrs; (x) = (x)+1) #define pfm_for_all_pmus(x) \ for((x)= 0 ; (x) < PFM_PMU_MAX; (x)++) #ifdef __cplusplus /* extern C */ } #endif #endif /* __PFMLIB_H__ */
#ifndef SkSVGValue_DEFINED #define SkSVGValue_DEFINED #include "experimental/svg/model/SkSVGTypes.h" #include "include/core/SkColor.h" #include "include/core/SkMatrix.h" #include "include/core/SkPath.h" #include "include/core/SkTypes.h" #include "include/private/SkNoncopyable.h" class SkSVGValue : public SkNoncopyable { public: enum class Type { kClip, kColor, kDashArray, kFillRule, kLength, kLineCap, kLineJoin, kNumber, kPaint, kPath, kPoints, kSpreadMethod, kString, kTransform, kViewBox, kVisibility, }; Type type() const { return fType; } template <typename T> const T* as() const { return fType == T::TYPE ? static_cast<const T*>(this) : nullptr; } protected: SkSVGValue(Type t) : fType(t) { } private: Type fType; typedef SkNoncopyable INHERITED; }; template <typename T, SkSVGValue::Type ValueType> class SkSVGWrapperValue final : public SkSVGValue { public: static constexpr Type TYPE = ValueType; explicit SkSVGWrapperValue(const T& v) : INHERITED(ValueType) , fWrappedValue(v) { } operator const T&() const { return fWrappedValue; } const T* operator->() const { return &fWrappedValue; } private: // Stack-only void* operator new(size_t) = delete; void* operator new(size_t, void*) = delete; const T& fWrappedValue; typedef SkSVGValue INHERITED; }; using SkSVGClipValue = SkSVGWrapperValue<SkSVGClip , SkSVGValue::Type::kClip >; using SkSVGColorValue = SkSVGWrapperValue<SkSVGColorType , SkSVGValue::Type::kColor >; using SkSVGFillRuleValue = SkSVGWrapperValue<SkSVGFillRule , SkSVGValue::Type::kFillRule >; using SkSVGLengthValue = SkSVGWrapperValue<SkSVGLength , SkSVGValue::Type::kLength >; using SkSVGPathValue = SkSVGWrapperValue<SkPath , SkSVGValue::Type::kPath >; using SkSVGTransformValue = SkSVGWrapperValue<SkSVGTransformType, SkSVGValue::Type::kTransform >; using SkSVGViewBoxValue = SkSVGWrapperValue<SkSVGViewBoxType , SkSVGValue::Type::kViewBox >; using SkSVGPaintValue = SkSVGWrapperValue<SkSVGPaint , SkSVGValue::Type::kPaint >; using SkSVGLineCapValue = SkSVGWrapperValue<SkSVGLineCap , SkSVGValue::Type::kLineCap >; using SkSVGLineJoinValue = SkSVGWrapperValue<SkSVGLineJoin , SkSVGValue::Type::kLineJoin >; using SkSVGNumberValue = SkSVGWrapperValue<SkSVGNumberType , SkSVGValue::Type::kNumber >; using SkSVGPointsValue = SkSVGWrapperValue<SkSVGPointsType , SkSVGValue::Type::kPoints >; using SkSVGStringValue = SkSVGWrapperValue<SkSVGStringType , SkSVGValue::Type::kString >; using <API key> = SkSVGWrapperValue<SkSVGSpreadMethod , SkSVGValue::Type::kSpreadMethod>; using <API key> = SkSVGWrapperValue<SkSVGVisibility , SkSVGValue::Type::kVisibility>; using SkSVGDashArrayValue = SkSVGWrapperValue<SkSVGDashArray , SkSVGValue::Type::kDashArray >; #endif // SkSVGValue_DEFINED
/* TEMPLATE GENERATED TESTCASE FILE Filename: <API key>.cpp Label Definition File: <API key>.label.xml Template File: sources-sink-84a.tmpl.cpp */ /* * @description * CWE: 195 Signed to Unsigned Conversion Error * BadSource: rand Set data to result of rand(), which may be zero * GoodSource: Positive integer * Sinks: memmove * BadSink : Copy strings using memmove() with the length of data * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #include "std_testcase.h" #include "<API key>.h" namespace <API key> { #ifndef OMITBAD void bad() { int data; /* Initialize data */ data = -1; <API key> * badObject = new <API key>(data); delete badObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int data; /* Initialize data */ data = -1; <API key> * goodG2BObject = new <API key>(data); delete goodG2BObject; } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace <API key>; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#ifndef LayoutSize_h #define LayoutSize_h #include "platform/LayoutUnit.h" #include "platform/geometry/FloatSize.h" #include "platform/geometry/IntSize.h" namespace blink { class LayoutPoint; enum AspectRatioFit { <API key>, AspectRatioFitGrow }; class LayoutSize { public: LayoutSize() { } LayoutSize(const IntSize& size) : m_width(size.width()), m_height(size.height()) { } LayoutSize(LayoutUnit width, LayoutUnit height) : m_width(width), m_height(height) { } explicit LayoutSize(const FloatSize& size) : m_width(size.width()), m_height(size.height()) { } LayoutUnit width() const { return m_width; } LayoutUnit height() const { return m_height; } void setWidth(LayoutUnit width) { m_width = width; } void setHeight(LayoutUnit height) { m_height = height; } bool isEmpty() const { return m_width.rawValue() <= 0 || m_height.rawValue() <= 0; } bool isZero() const { return !m_width && !m_height; } float aspectRatio() const { return m_width.toFloat() / m_height.toFloat(); } void expand(LayoutUnit width, LayoutUnit height) { m_width += width; m_height += height; } void shrink(LayoutUnit width, LayoutUnit height) { m_width -= width; m_height -= height; } void scale(float scale) { m_width *= scale; m_height *= scale; } void scale(float widthScale, float heightScale) { m_width *= widthScale; m_height *= heightScale; } LayoutSize expandedTo(const LayoutSize& other) const { return LayoutSize(m_width > other.m_width ? m_width : other.m_width, m_height > other.m_height ? m_height : other.m_height); } LayoutSize shrunkTo(const LayoutSize& other) const { return LayoutSize(m_width < other.m_width ? m_width : other.m_width, m_height < other.m_height ? m_height : other.m_height); } void clampNegativeToZero() { *this = expandedTo(LayoutSize()); } void clampToMinimumSize(const LayoutSize& minimumSize) { if (m_width < minimumSize.width()) m_width = minimumSize.width(); if (m_height < minimumSize.height()) m_height = minimumSize.height(); } LayoutSize transposedSize() const { return LayoutSize(m_height, m_width); } LayoutSize fitToAspectRatio(const LayoutSize& aspectRatio, AspectRatioFit fit) const { float heightScale = height().toFloat() / aspectRatio.height().toFloat(); float widthScale = width().toFloat() / aspectRatio.width().toFloat(); if ((widthScale > heightScale) != (fit == AspectRatioFitGrow)) return LayoutSize(height() * aspectRatio.width() / aspectRatio.height(), height()); return LayoutSize(width(), width() * aspectRatio.height() / aspectRatio.width()); } LayoutSize fraction() const { return LayoutSize(m_width.fraction(), m_height.fraction()); } private: LayoutUnit m_width, m_height; }; inline LayoutSize& operator+=(LayoutSize& a, const LayoutSize& b) { a.setWidth(a.width() + b.width()); a.setHeight(a.height() + b.height()); return a; } inline LayoutSize& operator-=(LayoutSize& a, const LayoutSize& b) { a.setWidth(a.width() - b.width()); a.setHeight(a.height() - b.height()); return a; } inline LayoutSize operator+(const LayoutSize& a, const LayoutSize& b) { return LayoutSize(a.width() + b.width(), a.height() + b.height()); } inline LayoutSize operator-(const LayoutSize& a, const LayoutSize& b) { return LayoutSize(a.width() - b.width(), a.height() - b.height()); } inline LayoutSize operator-(const LayoutSize& size) { return LayoutSize(-size.width(), -size.height()); } inline bool operator==(const LayoutSize& a, const LayoutSize& b) { return a.width() == b.width() && a.height() == b.height(); } inline bool operator!=(const LayoutSize& a, const LayoutSize& b) { return a.width() != b.width() || a.height() != b.height(); } inline IntSize flooredIntSize(const LayoutSize& s) { return IntSize(s.width().floor(), s.height().floor()); } inline IntSize roundedIntSize(const LayoutSize& s) { return IntSize(s.width().round(), s.height().round()); } inline LayoutSize roundedLayoutSize(const FloatSize& s) { return LayoutSize(s); } } // namespace blink #endif // LayoutSize_h
#include "components/policy/core/common/cloud/<API key>.h" #include <memory> #include <string> #include "base/callback.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/values.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_util.h" #include "components/policy/core/common/cloud/<API key>.h" #include "components/policy/core/common/cloud/dm_auth.h" #include "components/policy/policy_export.h" #include "components/version_info/version_info.h" #include "google_apis/google_api_keys.h" #include "services/network/public/cpp/<API key>.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" namespace policy { // Strings for |<API key>|. const char <API key>::<API key>::kDeviceKey[] = "device"; const char <API key>::<API key>::kDMToken[] = "dmToken"; const char <API key>::<API key>::kClientId[] = "clientId"; const char <API key>::<API key>::kOSVersion[] = "osVersion"; const char <API key>::<API key>::kOSPlatform[] = "osPlatform"; const char <API key>::<API key>::kName[] = "name"; // static base::Value <API key>::<API key>::<API key>( const std::string& dm_token, const std::string& client_id) { base::Value device_dictionary{base::Value::Type::DICTIONARY}; device_dictionary.SetStringKey(kDMToken, dm_token); device_dictionary.SetStringKey(kClientId, client_id); device_dictionary.SetStringKey(kOSVersion, GetOSVersion()); device_dictionary.SetStringKey(kOSPlatform, GetOSPlatform()); device_dictionary.SetStringKey(kName, GetDeviceName()); return device_dictionary; } // static std::string <API key>::<API key>::GetDMTokenPath() { return GetStringPath(kDMToken); } // static std::string <API key>::<API key>::GetClientIdPath() { return GetStringPath(kClientId); } // static std::string <API key>::<API key>::GetOSVersionPath() { return GetStringPath(kOSVersion); } // static std::string <API key>::<API key>::GetOSPlatformPath() { return GetStringPath(kOSPlatform); } // static std::string <API key>::<API key>::GetNamePath() { return GetStringPath(kName); } // static std::string <API key>::<API key>::GetStringPath( base::StringPiece leaf_name) { return base::JoinString({kDeviceKey, leaf_name}, "."); } // Strings for |<API key>|. const char <API key>::<API key>::kBrowserKey[] = "browser"; const char <API key>::<API key>::kBrowserId[] = "browserId"; const char <API key>::<API key>::kUserAgent[] = "userAgent"; const char <API key>::<API key>::kMachineUser[] = "machineUser"; const char <API key>::<API key>::kChromeVersion[] = "chromeVersion"; // static base::Value <API key>::<API key>::<API key>( bool include_device_info) { base::Value browser_dictionary{base::Value::Type::DICTIONARY}; base::FilePath browser_id; if (base::PathService::Get(base::DIR_EXE, &browser_id)) { browser_dictionary.SetStringKey(kBrowserId, browser_id.AsUTF8Unsafe()); } if (include_device_info) browser_dictionary.SetStringKey(kMachineUser, GetOSUsername()); browser_dictionary.SetStringKey(kChromeVersion, version_info::GetVersionNumber()); return browser_dictionary; } // static std::string <API key>::<API key>::GetBrowserIdPath() { return GetStringPath(kBrowserId); } // static std::string <API key>::<API key>::GetUserAgentPath() { return GetStringPath(kUserAgent); } // static std::string <API key>::<API key>::GetMachineUserPath() { return GetStringPath(kMachineUser); } // static std::string <API key>::<API key>:: <API key>() { return GetStringPath(kChromeVersion); } // static std::string <API key>::<API key>::GetStringPath( base::StringPiece leaf_name) { return base::JoinString({kBrowserKey, leaf_name}, "."); } std::string <API key>::GetPayload() { // Move context keys to the payload. if (context_.has_value()) { payload_.MergeDictionary(&context_.value()); context_.reset(); } // Allow children to mutate the payload if need be. <API key>(); std::string payload_string; base::JSONWriter::Write(payload_, &payload_string); return payload_string; } std::string <API key>::GetUmaName() { return GetUmaString() + GetJobTypeAsString(GetType()); } <API key>::Job::RetryMethod <API key>::ShouldRetry(int response_code, const std::string& response_body) { // If the request wasn't successfully processed at all, resending it won't do // anything. Don't retry. if (response_code != <API key>::kSuccess) { return <API key>::Job::NO_RETRY; } // Allow child to determine if any portion of the message should be retried. return ShouldRetryInternal(response_code, response_body); } void <API key>::OnBeforeRetry( int response_code, const std::string& response_body) { // If the request wasn't successful, don't try to retry. if (response_code != <API key>::kSuccess) { return; } <API key>(response_code, response_body); } void <API key>::OnURLLoadComplete( <API key>::Job* job, int net_error, int response_code, const std::string& response_body) { absl::optional<base::Value> response = base::JSONReader::Read(response_body); // Parse the response even if |response_code| is not a success since the // response data may contain an error message. // Map the net_error/response_code to a <API key>. <API key> code; if (net_error != net::OK) { code = <API key>; } else { switch (response_code) { case <API key>::kSuccess: code = DM_STATUS_SUCCESS; break; case <API key>::kInvalidArgument: code = <API key>; break; case <API key>::<API key>: code = <API key>; break; case <API key>::<API key>: code = <API key>; break; default: // Handle all unknown 5xx HTTP error codes as temporary and any other // unknown error as one that needs more time to recover. if (response_code >= 500 && response_code <= 599) code = <API key>; else code = <API key>; break; } } base::Value response_value = response ? std::move(*response) : base::Value(); std::move(callback_).Run(job, code, net_error, response_value); } <API key>::Job::RetryMethod <API key>::ShouldRetryInternal( int response_code, const std::string& response_body) { return <API key>::ShouldRetry(response_code, response_body); } void <API key>::<API key>( int response_code, const std::string& response_body) {} void <API key>::<API key>() {} GURL <API key>::GetURL(int last_error) const { return GURL(server_url_); } <API key>::<API key>( JobType type, scoped_refptr<network::<API key>> factory, CloudPolicyClient* client, const std::string& server_url, bool include_device_info, <API key> callback) : <API key>(type, DMAuth::FromDMToken(client->dm_token()), /*oauth_token=*/absl::nullopt, factory), payload_(base::Value::Type::DICTIONARY), callback_(std::move(callback)), server_url_(server_url) { DCHECK(GetAuth().has_dm_token()); InitializePayload(client, include_device_info); } <API key>::~<API key>() = default; void <API key>::InitializePayload( CloudPolicyClient* client, bool include_device_info) { AddParameter("key", google_apis::GetAPIKey()); if (include_device_info) { payload_.SetKey(<API key>::kDeviceKey, <API key>::<API key>( client->dm_token(), client->client_id())); } payload_.SetKey( <API key>::kBrowserKey, <API key>::<API key>(include_device_info)); } } // namespace policy
// SteppedScatterPlot.h // Plot Gallery-Mac #import "PlotItem.h" @interface SteppedScatterPlot : PlotItem<<API key>, CPTPlotDataSource, <API key>> { NSArray *plotData; } @end
<?php class Pimcore_Helper_Mail { /** * Returns the debug information that is appended to the debug emails * * @static * @param $type 'html' or 'text' * @param Pimcore_Mail $mail * @return string * @throws Exception */ public static function getDebugInformation($type, Pimcore_Mail $mail) { $type = strtolower($type); if ($type != 'html' && $type != 'text') { throw new Exception('$type has to be "html" or "text"'); } $temporaryStorage = $mail->getTemporaryStorage(); //generating html debug info if ($type == 'html') { $debugInformation = '<br/><br/><table class="<API key>"> <tr><th colspan="2">Debug information</th></tr>'; $debugInformation .= '<tr><td class="<API key>">From:</td><td>'; if ($mail->getFrom()) { $debugInformation .= $mail->getFrom(); } else { $defaultFrom = $mail->getDefaultFrom(); $debugInformation .= $defaultFrom["email"] . '<br/>Info: No "from" email address given so the default "from" email address is used from "Settings" -> "System" -> "Email Settings" )'; } $debugInformation .= '</td></tr>'; foreach (array('To', 'Cc', 'Bcc') as $key) { if (!empty($temporaryStorage[$key])) { $debugInformation .= '<tr><td class="<API key>">' . $key . ': </td>'; $debugInformation .= '<td>' . self::<API key>($temporaryStorage[$key]) . '</td></tr>'; } } $debugInformation .= '</table>'; } else { //generating text debug info $debugInformation = "\r\n \r\nDebug Information: \r\n \r\n"; foreach (array('To', 'Cc', 'Bcc') as $key) { if (!empty($temporaryStorage[$key])) { $debugInformation .= "$key: " . self::<API key>($temporaryStorage[$key]) . "\r\n"; } } } return $debugInformation; } /** * Return the basic css styles for the html debug information * * @static * @return string */ public static function <API key>() { $style = <<<'CSS' <style type="text/css"> .<API key>{ width:100%; background-color:#f8f8f8; font-size:12px; font-family: Arial, sans-serif; border-spacing:0px; border-collapse:collapse } .<API key> td, .<API key> th{ padding: 5px 10px; vertical-align:top; border: 1px solid #ccc; } .<API key> th{ text-align:center; font-weight:bold; } .<API key>{ width:80px; } </style> CSS; return $style; } /** * Helper to format the receivers for the debug email and logging * * @param array $receivers * @return string */ protected function <API key>(Array $receivers) { $tmpString = ''; foreach ($receivers as $entry) { $tmpString .= $entry['email']; if ($entry['name']) { $tmpString .= " (" . $entry["name"] . ")"; } $tmpString .= ", "; } $tmpString = substr($tmpString, 0, strrpos($tmpString, ',')); return $tmpString; } /** * Helper to log the email to the database and the file system * * @static * @param Pimcore_Mail $mail */ public static function logEmail(Pimcore_Mail $mail) { $emailLog = new Document_Email_Log(); $document = $mail->getDocument(); if ($document instanceof Document) { $emailLog->setDocumentId($document->getId()); } $emailLog->setRequestUri(htmlspecialchars($_SERVER['REQUEST_URI'])); $emailLog->setParams($mail->getParams()); $emailLog->setSubject($mail->getSubject()); $emailLog->setSentDate(time()); $mailFrom = $mail->getFrom(); if ($mailFrom) { $emailLog->setFrom($mailFrom); } else { $defaultFrom = $mail->getDefaultFrom(); $tmpString = $defaultFrom['email']; if ($defaultFrom['name']) { $tmpString .= " (" . $defaultFrom["name"] . ")"; } $emailLog->setFrom($tmpString); } $html = $mail->getBodyHtml(); if ($html instanceof Zend_Mime_Part) { $emailLog->setBodyHtml($html->getRawContent()); } $text = $mail->getBodyText(); if ($text instanceof Zend_Mime_Part) { $emailLog->setBodyText($text->getRawContent()); } $temporaryStorage = $mail->getTemporaryStorage(); foreach (array('To', 'Cc', 'Bcc') as $key) { if (!empty($temporaryStorage[$key])) { if (method_exists($emailLog, 'set' . $key)) { $emailLog->{"set$key"}(self::<API key>($temporaryStorage[$key])); } } } $emailLog->save(); } /** * Replaces URLs with the full path including the Host * * @static * @param string $string - the content to modify * @param null | Document $document * @return string * @throws Exception - if something else than a document is passed */ public static function setAbsolutePaths($string, $document = null, $hostUrl = null) { if ($document && $document instanceof Document == false) { throw new Exception('$document has to be an instance of Document'); } if(is_null($hostUrl)){ $hostUrl = Pimcore_Tool::getHostUrl(); } //matches all links preg_match_all("@(href|src)\s*=[\"']([^(http|mailto|javascript)].*?(css|jpe?g|gif|png)?)[\"']@is", $string, $matches); if (!empty($matches[0])) { foreach ($matches[0] as $key => $value) { $fullMatch = $matches[0][$key]; $linkType = $matches[1][$key]; $path = $matches[2][$key]; $fileType = $matches[3][$key]; if (strpos($path, '/') === 0) { $absolutePath = $hostUrl . $path; } else { $absolutePath = $hostUrl . "/$path"; $netUrl = new Net_URL2($absolutePath); $absolutePath = $netUrl->getNormalizedURL(); } $path = preg_quote($path); $string = preg_replace("!([\"'])$path([\"'])!is", "\\1" . $absolutePath . "\\2", $string); } } return $string; } /** * Embeds the css stylesheets to the html email and normalizes the url() css tag * In addition .less files are compiled, modified and embedded to html email * * @static * @param $string - the content to modify * @param null | Document $document * @return string * @throws Exception - if something else than a document is passed */ public static function embedAndModifyCss($string, $document = null) { if ($document && $document instanceof Document == false) { throw new Exception('$document has to be an instance of Document'); } //matches all <link> Tags preg_match_all("@<link.*?href\s*=\s*[\"']([^http].*?)[\"'].*?(/?>|</\s*link>)@is", $string, $matches); if (!empty($matches[0])) { foreach ($matches[0] as $key => $value) { $fullMatch = $matches[0][$key]; $path = $matches[1][$key]; $fileInfo = self::<API key>($path, $document); if (in_array($fileInfo['fileExtension'], array('css', 'less'))) { if (is_readable($fileInfo['filePathNormalized'])) { if ($fileInfo['fileExtension'] == 'css') { $fileContent = file_get_contents($fileInfo['filePathNormalized']); } else { $fileContent = Pimcore_Tool_Less::compile($fileInfo['filePathNormalized']); $fileContent = str_replace('','',$fileContent); } if ($fileContent) { $fileContent = self::normalizeCssContent($fileContent, $fileInfo); $string = str_replace($fullMatch, '<style type="text/css">' . $fileContent . '</style>', $string); } } } } } return $string; } /** * Normalizes the css content (replaces images with the full path including the host) * * @static * @param string $content * @param array $fileInfo * @return string */ public static function normalizeCssContent($content, Array $fileInfo) { preg_match_all("@url\s*\(\s*[\"']?(.*?)[\"']?\s*\)@is", $content, $matches); $hostUrl = Pimcore_Tool::getHostUrl(); if (is_array($matches[0])) { foreach ($matches[0] as $key => $value) { $fullMatch = $matches[0][$key]; $path = $matches[1][$key]; if ($path[0] == '/') { $imageUrl = $hostUrl . $path; } else { $imageUrl = dirname($fileInfo['fileUrlNormalized']) . "/$path"; $netUrl = new Net_URL2($imageUrl); $imageUrl = $netUrl->getNormalizedURL(); } $content = str_replace($fullMatch, " url(" . $imageUrl . ") ", $content); } } return $content; } /** * Gets file information for replacement * * @static * @param string $path * @param Document | null $document * @return array * @throws Exception */ public static function <API key>($path, $document = null) { if ($document && $document instanceof Document == false) { throw new Exception('$document has to be an instance of Document'); } $fileInfo = array(); $hostUrl = Pimcore_Tool::getHostUrl(); if ($path[0] != '/') { $fileInfo['fileUrl'] = $hostUrl . $document . "/$path"; //relative eg. ../file.css } else { $fileInfo['fileUrl'] = $hostUrl . $path; } $fileInfo['fileExtension'] = substr($path, strrpos($path, '.') + 1); $netUrl = new Net_URL2($fileInfo['fileUrl']); $fileInfo['fileUrlNormalized'] = $netUrl->getNormalizedURL(); $fileInfo['filePathNormalized'] = <API key> . str_replace($hostUrl, '', $fileInfo['fileUrlNormalized']); return $fileInfo; } }
namespace NGM.Forum.Models { public static class VotingConstants { public const string ViewConstant = "ContentViews"; public const string RatingConstant = "VoteUpDown"; } }
#import <DatabaseKit/DBQuery.h> #import <DatabaseKit/DBModel.h> @class DBAs, DBJoin; extern NSString *const DBInnerJoin; extern NSString *const DBLeftJoin; extern NSString *const DBUnion; extern NSString *const DBUnionAll; @interface DBSelectQuery : DBReadQuery <DBTableQuery, DBFilterableQuery, NSFastEnumeration> @property(readonly, strong) DBSelectQuery *subQuery; @property(readonly, strong) NSArray *orderedBy; @property(readonly, strong) NSArray *groupedBy; @property(readonly) DBOrder order; @property(readonly) NSUInteger limit, offset; @property(readonly, strong) DBJoin *join; @property(readonly, strong) DBSelectQuery *unionQuery; @property(readonly, strong) NSString *unionType; @property(readonly) BOOL distinct; + (instancetype)fromSubquery:(DBSelectQuery *)aSubQuery; - (instancetype)order:(DBOrder)order by:(NSArray *)columns; - (instancetype)orderBy:(NSArray *)columns; - (instancetype)groupBy:(NSArray *)columns; - (instancetype)limit:(NSUInteger)limit; - (instancetype)offset:(NSUInteger)offset; - (instancetype)distinct:(BOOL)distinct; - (instancetype)join:(DBJoin *)join; - (instancetype)innerJoin:(id)table on:(NSString *)format, ...; - (instancetype)leftJoin:(id)table on:(NSString *)format, ...; - (instancetype)union:(DBSelectQuery *)otherQuery; - (instancetype)union:(DBSelectQuery *)otherQuery type:(NSString *)type; - (id)<API key>:(NSUInteger)idx; - (NSUInteger)count; - (id)firstObject; @end @interface DBJoin : NSObject @property(readonly, strong) NSString *type; @property(readonly, strong) DBTable *table; @property(readonly, strong) NSPredicate *predicate; + (DBJoin *)withType:(NSString *)type table:(id)table predicate:(NSPredicate *)aPredicate; @end @interface DBAs : NSObject <DBSQLRepresentable> @property(readonly, strong) NSString *field, *alias; + (DBAs *)field:(NSString *)field alias:(NSString *)alias; @end @interface DBQuery (DBSelectQuery) - (DBSelectQuery *)select:(NSArray *)columns; - (DBSelectQuery *)select; @end @interface DBModel (DBSelectQuery) + (BOOL)<API key>; @end
// coding: utf-8 #ifndef XPCC_PT__THREAD_HPP #define XPCC_PT__THREAD_HPP #include <stdint.h> #include "macros.hpp" namespace xpcc { namespace pt { /** * \brief A very lightweight, stackless thread * * Because protothreads do not save the stack context across a blocking * call, local variables are not preserved when the protothread blocks. * This means that local variables should be used with utmost care - if in * doubt, do not use local variables inside a protothread! Use * private/protected member variables to save state between a context switch. * * A protothread is driven by repeated calls to the run()-function in which * the protothread is running. Each time the function is called, the * protothread will run until it blocks or exits. Thus the scheduling of * protothreads is done by the application that uses protothreads. * * Example: * \code * #include <xpcc/architecture.hpp> * #include <xpcc/utils/protothread.hpp> * #include <xpcc/utils/timeout.hpp> * * typedef GpioOutputB0 Led; * * class BlinkingLight : public xpcc::pt::Protothread * { * public: * bool * run() * { * PT_BEGIN(); * * // set everything up * Led::setOutput(); * Led::set(); * * while (true) * { * timeout.start(100); * Led::set(); * PT_WAIT_UNTIL(timeout.isExpired()); * * timeout.start(200); * Led::reset(); * PT_WAIT_UNTIL(timeout.isExpired()); * } * * PT_END(); * } * * private: * xpcc::ShortTimeout timeout; * }; * * * ... * BlinkingLight light; * * while (...) { * light.run(); * } * \endcode * * For other examples take a look in the \c examples folder in the XPCC * root folder. * * \warning The names \c ptState and \c ptYield are reserved and may not * be used as variables or function names! * * \ingroup protothread */ class Protothread { public: /** * \brief Construct a new protothread that will start from the * beginning of its run() function. */ Protothread() : ptState(0) { } Restart protothread. inline void restart() { this->ptState = 0; } /** * \brief Stop the protothread from running. * * Happens automatically at PT_END. * * \note This differs from the Dunkels' original protothread * behavior (his restart automatically, which is usually not * what you want). */ inline void stop() { this->ptState = Invalid; } /** * \brief Check if the protothread is still running * * \return \c true if the protothread is running or waiting, * \c false if it has ended or exited. */ inline bool isRunning() const { return (this->ptState != Invalid); } #ifdef __DOXYGEN__ @cond /** * \brief Run the protothread * * Run next part of protothread or return immediately if it's still * waiting. Returns \c true if protothread is still running, \c false * if it has finished. * * Implement this method in your Protothread subclass. * * \warning This is method is not virtual, therefore you cannot access * it through a Pointer to this class, but only directly from * the subclass! This was done on purpose to keep the memory * footprint low. */ bool run(); #endif protected: /** * Used to store a protothread's position (what Dunkels calls a * "local continuation"). */ typedef uint16_t PtState; An invalid line number, used to mark the protothread has ended. static const PtState Invalid = static_cast<PtState>(-1); /** * Stores the protothread's position (by storing the line number of * the last PT_WAIT, which is then switched on at the next Run). */ PtState ptState; @endcond }; } } #endif // XPCC_PT__THREAD_HPP
#!/usr/bin/env python from HTMLParser import HTMLParser, HTMLParseError import optparse from urllib2 import urlopen, URLError from searchengine.logger import Logging class TagSelector(HTMLParser): """ Strip all HTML tags from a string. """ def __init__(self, *args, **kwargs): self.reset() self.content_dict = { 'title': "", 'content': [], 'links': [], } self.current_tag = None self.current_attrs = None self.visible_tags = kwargs.get('visible_tags', [ 'body', 'title', 'p', 'div', 'td', 'span', 'blockquote', 'li', 'a', ]) def attr_dict(self, attrs): """ Iterate through the attrs and convert to a dict. """ attrs_dict = {} if attrs: for a in attrs: attrs_dict.update({a[0]: a[1]}) return attrs_dict def handle_starttag(self, tag, attrs): """ Set the current tag the parser has reached. TODO: add css support """ self.current_tag = tag self.current_attrs = self.attr_dict(attrs) def handle_data(self, data): """ Append visible data to the list. """ data = data.strip() # find visible data and update to the content_dict if self.current_tag in self.visible_tags and data: if self.current_tag == 'title': self.content_dict['title'] = data if self.current_tag == 'a' and self.current_attrs.has_key('href'): link = self.current_attrs['href'] self.content_dict['links'].append((data, link)) self.content_dict['content'].append(data) def get_data(self): return self.content_dict class HTMLScraper(object): """ A simple HTML Scraper class to get visable text from a given URL. """ def __init__(self, url, *args, **kwargs): self.log = kwargs.get('log', Logging()) self.url = url def get_url_content(self): """ Open and read the content of a URL. """ try: url_handler = urlopen(self.url) except URLError, e: self.log.warning("HTMLScraper", "get_url_content", e) return "" html_content = url_handler.read() url_handler.close() return html_content def get_content(self): """ Parse the visable content of a url into plain text. """ html_content = self.get_url_content() html_parser = TagSelector() try: html_parser.feed(unicode(html_content, errors='replace')) except HTMLParseError, e: self.log.warning("HTMLScraper", "get_content", e) return {} # get the content and update with the url scraped parsed_content = html_parser.get_data() parsed_content.update({'url': self.url}) return parsed_content
# Install script for directory: C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/SuiteSparse/AMD # Set the install prefix if(NOT DEFINED <API key>) set(<API key> "C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/build_cuda55_vs2013/install") endif() string(REGEX REPLACE "/$" "" <API key> "${<API key>}") # Set the install configuration name. if(NOT DEFINED <API key>) if(BUILD_TYPE) string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" <API key> "${BUILD_TYPE}") else() set(<API key> "Release") endif() message(STATUS "Install configuration: \"${<API key>}\"") endif() # Set the component getting installed. if(NOT <API key>) if(COMPONENT) message(STATUS "Install component: \"${COMPONENT}\"") set(<API key> "${COMPONENT}") else() set(<API key>) endif() endif() if(NOT <API key> OR "${<API key>}" STREQUAL "Unspecified") if("${<API key>}" MATCHES "^([Dd][Ee][Bb][Uu][Gg])$") file(INSTALL DESTINATION "${<API key>}/lib64" TYPE STATIC_LIBRARY FILES "C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/build_cuda55_vs2013/lib/Debug/libamdd.lib") elseif("${<API key>}" MATCHES "^([Rr][Ee][Ll][Ee][Aa][Ss][Ee])$") file(INSTALL DESTINATION "${<API key>}/lib64" TYPE STATIC_LIBRARY FILES "C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/build_cuda55_vs2013/lib/Release/libamd.lib") elseif("${<API key>}" MATCHES "^([Mm][Ii][Nn][Ss][Ii][Zz][Ee][Rr][Ee][Ll])$") file(INSTALL DESTINATION "${<API key>}/lib64" TYPE STATIC_LIBRARY FILES "C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/build_cuda55_vs2013/lib/MinSizeRel/libamd.lib") elseif("${<API key>}" MATCHES "^([Rr][Ee][Ll][Ww][Ii][Tt][Hh][Dd][Ee][Bb][Ii][Nn][Ff][Oo])$") file(INSTALL DESTINATION "${<API key>}/lib64" TYPE STATIC_LIBRARY FILES "C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/build_cuda55_vs2013/lib/RelWithDebInfo/libamd.lib") endif() endif() if(NOT <API key> OR "${<API key>}" STREQUAL "Unspecified") file(INSTALL DESTINATION "${<API key>}/include/suitesparse" TYPE FILE FILES "C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/SuiteSparse/AMD/Include/amd.h" "C:/Users/dkvandyke/Source/Repos/<API key>/<API key>/SuiteSparse/AMD/Include/amd_internal.h" ) endif()
(function ($) { // When called on a container with a selector, fetches the href with // ajax into the container or with the data-pjax attribute on the link // itself. // Tries to make sure the back button and ctrl+click work the way // you'd expect. // Exported as $.fn.pjax // Accepts a jQuery ajax options object that may include these // pjax specific options: // container - Where to stick the response body. Usually a String selector. // $(container).html(xhr.responseBody) // (default: current jquery context) // push - Whether to pushState the URL. Defaults to true (of course). // replace - Want to use replaceState instead? That's cool. // history - Work with window.history. Defaults to true // cache - Whether to cache pages HTML. Defaults to true // For convenience the second parameter can be either the container or // the options object. // Returns the jQuery object function fnPjax(selector, container, options) { var context = this return this.on('click.pjax', selector, function (event) { var opts = $.extend({history: true}, optionsFor(container, options)) if (!opts.container) opts.container = $(this).attr('data-pjax') || context handleClick(event, opts) }) } // Public: pjax on click handler // Exported as $.pjax.click. // event - "click" jQuery.Event // options - pjax options // If the click event target has 'data-pjax="0"' attribute, the event is ignored, and no pjax call is made. // Examples // $(document).on('click', 'a', $.pjax.click) // // is the same as // $(document).pjax('a') // $(document).on('click', 'a', function(event) { // var container = $(this).closest('[data-pjax-container]') // $.pjax.click(event, container) // Returns nothing. function handleClick(event, container, options) { options = optionsFor(container, options) var link = event.currentTarget // Ignore links with data-pjax="0" if ($(link).data('pjax') == 0) { return; } if (link.tagName.toUpperCase() !== 'A') throw "$.fn.pjax or $.pjax.click requires an anchor element" // Middle click, cmd click, and ctrl click should open // links in a new tab as normal. if (event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return // Ignore cross origin links if (location.protocol !== link.protocol || location.hostname !== link.hostname) return // Ignore case when a hash is being tacked on the current URL if (link.href.indexOf('#') > -1 && stripHash(link) == stripHash(location)) return // Ignore event with default prevented if (event.isDefaultPrevented()) return var defaults = { url: link.href, container: $(link).attr('data-pjax'), target: link } var opts = $.extend({}, defaults, options) var clickEvent = $.Event('pjax:click') $(link).trigger(clickEvent, [opts]) if (!clickEvent.isDefaultPrevented()) { pjax(opts) event.preventDefault() $(link).trigger('pjax:clicked', [opts]) } } // Public: pjax on form submit handler // Exported as $.pjax.submit // event - "click" jQuery.Event // options - pjax options // Examples // $(document).on('submit', 'form', function(event) { // var container = $(this).closest('[data-pjax-container]') // $.pjax.submit(event, container) // Returns nothing. function handleSubmit(event, container, options) { options = optionsFor(container, options) var form = event.currentTarget if (form.tagName.toUpperCase() !== 'FORM') throw "$.pjax.submit requires a form element" var defaults = { type: form.method.toUpperCase(), url: form.action, container: $(form).attr('data-pjax'), target: form } if (defaults.type !== 'GET' && window.FormData !== undefined) { defaults.data = new FormData(form); defaults.processData = false; defaults.contentType = false; } else { // Can't handle file uploads, exit if ($(form).find(':file').length) { return; } // Fallback to manually serializing the fields defaults.data = $(form).serializeArray(); } pjax($.extend({}, defaults, options)) event.preventDefault() } // Loads a URL with ajax, puts the response body inside a container, // then pushState()'s the loaded URL. // Works just like $.ajax in that it accepts a jQuery ajax // settings object (with keys like url, type, data, etc). // Accepts these extra keys: // container - Where to stick the response body. // $(container).html(xhr.responseBody) // push - Whether to pushState the URL. Defaults to true (of course). // replace - Want to use replaceState instead? That's cool. // Use it just like $.ajax: // var xhr = $.pjax({ url: this.href, container: '#main' }) // console.log( xhr.readyState ) // Returns whatever $.ajax returns. function pjax(options) { options = $.extend(true, {}, $.ajaxSettings, pjax.defaults, options) if ($.isFunction(options.url)) { options.url = options.url() } var target = options.target var hash = parseURL(options.url).hash var context = options.context = findContainerFor(options.container) // We want the browser to maintain two separate internal caches: one // for pjax'd partial page loads and one for normal page loads. // Without adding this secret parameter, some browsers will often // confuse the two. if (!options.data) options.data = {} if ($.isArray(options.data)) { options.data.push({name: '_pjax', value: context.selector}) } else { options.data._pjax = context.selector } function fire(type, args, props) { if (!props) props = {} props.relatedTarget = target var event = $.Event(type, props) context.trigger(event, args) return !event.isDefaultPrevented() } var timeoutTimer options.beforeSend = function (xhr, settings) { // No timeout for non-GET requests // Its not safe to request the resource again with a fallback method. if (settings.type !== 'GET') { settings.timeout = 0 } xhr.setRequestHeader('X-PJAX', 'true') xhr.setRequestHeader('X-PJAX-Container', context.selector) if (!fire('pjax:beforeSend', [xhr, settings])) return false if (settings.timeout > 0) { timeoutTimer = setTimeout(function () { if (fire('pjax:timeout', [xhr, options])) xhr.abort('timeout') }, settings.timeout) // Clear timeout setting so jquerys internal timeout isn't invoked settings.timeout = 0 } var url = parseURL(settings.url) url.hash = hash options.requestUrl = stripInternalParams(url.href) } options.complete = function (xhr, textStatus) { if (timeoutTimer) clearTimeout(timeoutTimer) fire('pjax:complete', [xhr, textStatus, options]) fire('pjax:end', [xhr, options]) } options.error = function (xhr, textStatus, errorThrown) { var container = extractContainer("", xhr, options) // Check redirect status code var redirect = (xhr.status >= 301 && xhr.status <= 303) // Do not fire pjax::error in case of redirect var allowed = redirect || fire('pjax:error', [xhr, textStatus, errorThrown, options]) if (redirect || options.type == 'GET' && textStatus !== 'abort' && allowed) { locationReplace(container.url) } } options.success = function (data, status, xhr) { var previousState = pjax.state; // If $.pjax.defaults.version is a function, invoke it first. // Otherwise it can be a static string. var currentVersion = (typeof $.pjax.defaults.version === 'function') ? $.pjax.defaults.version() : $.pjax.defaults.version var latestVersion = xhr.getResponseHeader('X-PJAX-Version') var container = extractContainer(data, xhr, options) var url = parseURL(container.url) if (hash) { url.hash = hash container.url = url.href } // If there is a layout version mismatch, hard load the new url if (currentVersion && latestVersion && currentVersion !== latestVersion) { locationReplace(container.url) return } // If the new response is missing a body, hard load the page if (!container.contents) { locationReplace(container.url) return } pjax.state = { id: options.id || uniqueId(), url: container.url, title: container.title, container: context.selector, fragment: options.fragment, timeout: options.timeout } if (options.history && (options.push || options.replace)) { window.history.replaceState(pjax.state, container.title, container.url) } // Clear out any focused controls before inserting new page contents. try { document.activeElement.blur() } catch (e) { } if (container.title) document.title = container.title fire('pjax:beforeReplace', [container.contents, options], { state: pjax.state, previousState: previousState }) context.html(container.contents) // FF bug: Won't autofocus fields that are inserted via JS. // This behavior is incorrect. So if theres no current focus, autofocus // the last field. var autofocusEl = context.find('input[autofocus], textarea[autofocus]').last()[0] if (autofocusEl && document.activeElement !== autofocusEl) { autofocusEl.focus(); } executeScriptTags(container.scripts) var scrollTo = options.scrollTo // Ensure browser scrolls to the element referenced by the URL anchor if (hash) { var name = decodeURIComponent(hash.slice(1)) var target = document.getElementById(name) || document.getElementsByName(name)[0] if (target) scrollTo = $(target).offset().top } if (typeof scrollTo == 'number') $(window).scrollTop(scrollTo) fire('pjax:success', [data, status, xhr, options]) } // Initialize pjax.state for the initial page load. Assume we're // using the container and options of the link we're loading for the // back button to the initial page. This ensures good back button // behavior. if (!pjax.state) { pjax.state = { id: uniqueId(), url: window.location.href, title: document.title, container: context.selector, fragment: options.fragment, timeout: options.timeout } window.history.replaceState(pjax.state, document.title) } // Cancel the current request if we're already pjaxing abortXHR(pjax.xhr) // Strip _pjax parameter from URL, if exists. options.url = stripInternalParams(options.url); pjax.options = options var xhr = pjax.xhr = $.ajax(options) if (xhr.readyState > 0) { if (options.history && (options.push && !options.replace)) { // Cache current container element before replacing it cachePush(pjax.state.id, cloneContents(context)) window.history.pushState(null, "", options.requestUrl) } fire('pjax:start', [xhr, options]) fire('pjax:send', [xhr, options]) } return pjax.xhr } // Public: Reload current page with pjax. // Returns whatever $.pjax returns. function pjaxReload(container, options) { var defaults = { url: window.location.href, push: false, replace: true, scrollTo: false } return pjax($.extend(defaults, optionsFor(container, options))) } // Internal: Hard replace current state with url. // Work for around WebKit // Returns nothing. function locationReplace(url) { if (!pjax.options.history) return; window.history.replaceState(null, "", pjax.state.url) window.location.replace(url) } var initialPop = true var initialURL = window.location.href var initialState = window.history.state // Initialize $.pjax.state if possible // Happens when reloading a page and coming forward from a different // session history. if (initialState && initialState.container) { pjax.state = initialState } // Non-webkit browsers don't fire an initial popstate event if ('state' in window.history) { initialPop = false } // popstate handler takes care of the back and forward buttons // You probably shouldn't use pjax on pages with other pushState // stuff yet. function onPjaxPopstate(event) { // Hitting back or forward should override any pending PJAX request. if (!initialPop) { abortXHR(pjax.xhr) } var previousState = pjax.state var state = event.state if (state && state.container) { // When coming forward from a separate history session, will get an // initial pop with a state we are already at. Skip reloading the current // page. if (initialPop && initialURL == state.url) return var direction, containerSelector = state.container if (previousState) { // If popping back to the same state, just skip. // Could be clicking back from hashchange rather than a pushState. if (previousState.id === state.id) return // Since state IDs always increase, we can deduce the navigation direction direction = previousState.id < state.id ? 'forward' : 'back' if (direction == 'back') containerSelector = previousState.container } var container = $(containerSelector) if (container.length) { var contents = cacheMapping[state.id] if (previousState) { // Cache current container before replacement and inform the // cache which direction the history shifted. cachePop(direction, previousState.id, cloneContents(container)) } var popstateEvent = $.Event('pjax:popstate', { state: state, direction: direction }) container.trigger(popstateEvent) var options = { id: state.id, url: state.url, container: container, push: false, fragment: state.fragment, timeout: state.timeout, scrollTo: false } if (contents) { container.trigger('pjax:start', [null, options]) pjax.state = state if (state.title) document.title = state.title var beforeReplaceEvent = $.Event('pjax:beforeReplace', { state: state, previousState: previousState }) container.trigger(beforeReplaceEvent, [contents, options]) container.html(contents) container.trigger('pjax:end', [null, options]) } else { pjax(options) } // Force reflow/relayout before the browser tries to restore the // scroll position. container[0].offsetHeight } else { locationReplace(location.href) } } initialPop = false } // Fallback version of main pjax function for browsers that don't // support pushState. // Returns nothing since it retriggers a hard form submission. function fallbackPjax(options) { var url = $.isFunction(options.url) ? options.url() : options.url, method = options.type ? options.type.toUpperCase() : 'GET' var form = $('<form>', { method: method === 'GET' ? 'GET' : 'POST', action: url, style: 'display:none' }) if (method !== 'GET' && method !== 'POST') { form.append($('<input>', { type: 'hidden', name: '_method', value: method.toLowerCase() })) } var data = options.data if (typeof data === 'string') { $.each(data.split('&'), function (index, value) { var pair = value.split('=') form.append($('<input>', {type: 'hidden', name: pair[0], value: pair[1]})) }) } else if ($.isArray(data)) { $.each(data, function (index, value) { form.append($('<input>', {type: 'hidden', name: value.name, value: value.value})) }) } else if (typeof data === 'object') { var key for (key in data) form.append($('<input>', {type: 'hidden', name: key, value: data[key]})) } $(document.body).append(form) form.submit() } // Internal: Abort an XmlHttpRequest if it hasn't been completed, // also removing its event handlers. function abortXHR(xhr) { if (xhr && xhr.readyState < 4) { xhr.onreadystatechange = $.noop xhr.abort() } } // Internal: Generate unique id for state object. // Use a timestamp instead of a counter since ids should still be // unique across page loads. // Returns Number. function uniqueId() { return (new Date).getTime() } function cloneContents(container) { var cloned = container.clone() // Unmark script tags as already being eval'd so they can get executed again // when restored from cache. HAXX: Uses jQuery internal method. cloned.find('script').each(function () { if (!this.src) jQuery._data(this, 'globalEval', false) }) return cloned.contents() } // Internal: Strips named query param from url // url - String // Returns String. function stripParam(url, name) { return url .replace(new RegExp('[?&]' + name + '=[^& .replace(/[?&]($| .replace(/[?&]/, '?') } function stripInternalParams(url) { url = stripParam(url, '_pjax') url = stripParam(url, '_') return url } // Internal: Parse URL components and returns a Locationish object. // url - String URL // Returns HTMLAnchorElement that acts like Location. function parseURL(url) { var a = document.createElement('a') a.href = url return a } // Internal: Return the `href` component of given URL object with the hash // portion removed. // location - Location or HTMLAnchorElement // Returns String function stripHash(location) { return location.href.replace(/ } // Internal: Build options Object for arguments. // For convenience the first parameter can be either the container or // the options object. // Examples // optionsFor('#container') // // => {container: '#container'} // optionsFor('#container', {push: true}) // // => {container: '#container', push: true} // optionsFor({container: '#container', push: true}) // // => {container: '#container', push: true} // Returns options Object. function optionsFor(container, options) { // Both container and options if (container && options) options.container = container // First argument is options Object else if ($.isPlainObject(container)) options = container // Only container else options = {container: container} // Find and validate container if (options.container) options.container = findContainerFor(options.container) return options } // Internal: Find container element for a variety of inputs. // Because we can't persist elements using the history API, we must be // able to find a String selector that will consistently find the Element. // container - A selector String, jQuery object, or DOM Element. // Returns a jQuery object whose context is `document` and has a selector. function findContainerFor(container) { container = $(container) if (!container.length) { throw "no pjax container for " + container.selector } else if (container.selector !== '' && container.context === document) { return container } else if (container.attr('id')) { return $('#' + container.attr('id')) } else { throw "cant get selector for pjax container!" } } // Internal: Filter and find all elements matching the selector. // Where $.fn.find only matches descendants, findAll will test all the // top level elements in the jQuery object as well. // elems - jQuery object of Elements // selector - String selector to match // Returns a jQuery object. function findAll(elems, selector) { return elems.filter(selector).add(elems.find(selector)); } function parseHTML(html) { return $.parseHTML(html, document, true) } // Internal: Extracts container and metadata from response. // 1. Extracts X-PJAX-URL header if set // 2. Extracts inline <title> tags // 3. Builds response Element and extracts fragment if set // data - String response data // xhr - XHR response // options - pjax options Object // Returns an Object with url, title, and contents keys. function extractContainer(data, xhr, options) { var obj = {}, fullDocument = /<html/i.test(data) // Prefer X-PJAX-URL header if it was set, otherwise fallback to // using the original requested url. var serverUrl = xhr.getResponseHeader('X-PJAX-URL') obj.url = serverUrl ? stripInternalParams(serverUrl) : options.requestUrl // Attempt to parse response html into elements if (fullDocument) { var $head = $(parseHTML(data.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0])) var $body = $(parseHTML(data.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0])) } else { var $head = $body = $(parseHTML(data)) } // If response data is empty, return fast if ($body.length === 0) return obj // If there's a <title> tag in the header, use it as // the page's title. obj.title = findAll($head, 'title').last().text() if (options.fragment) { // If they specified a fragment, look for it in the response // and pull it out. if (options.fragment === 'body') { var $fragment = $body } else { var $fragment = findAll($body, options.fragment).first() } if ($fragment.length) { obj.contents = options.fragment === 'body' ? $fragment : $fragment.contents() // If there's no title, look for data-title and title attributes // on the fragment if (!obj.title) obj.title = $fragment.attr('title') || $fragment.data('title') } } else if (!fullDocument) { obj.contents = $body } // Clean up any <title> tags if (obj.contents) { // Remove any parent title elements obj.contents = obj.contents.not(function () { return $(this).is('title') }) // Then scrub any titles from their descendants obj.contents.find('title').remove() // Gather all script[src] elements obj.scripts = findAll(obj.contents, 'script[src]').remove() obj.contents = obj.contents.not(obj.scripts) } // Trim any whitespace off the title if (obj.title) obj.title = $.trim(obj.title) return obj } // Load an execute scripts using standard script request. // Avoids jQuery's traditional $.getScript which does a XHR request and // globalEval. // scripts - jQuery object of script Elements // Returns nothing. function executeScriptTags(scripts) { if (!scripts) return var existingScripts = $('script[src]') scripts.each(function () { var src = this.src var matchedScripts = existingScripts.filter(function () { return this.src === src }) if (matchedScripts.length) return var script = document.createElement('script') var type = $(this).attr('type') if (type) script.type = type script.src = $(this).attr('src') document.head.appendChild(script) }) } // Internal: History DOM caching class. var cacheMapping = {} var cacheForwardStack = [] var cacheBackStack = [] // Push previous state id and container contents into the history // cache. Should be called in conjunction with `pushState` to save the // previous container contents. // id - State ID Number // value - DOM Element to cache // Returns nothing. function cachePush(id, value) { if (!pjax.options.cache) { return; } cacheMapping[id] = value cacheBackStack.push(id) // Remove all entries in forward history stack after pushing a new page. trimCacheStack(cacheForwardStack, 0) // Trim back history stack to max cache length. trimCacheStack(cacheBackStack, pjax.defaults.maxCacheLength) } // Shifts cache from directional history cache. Should be // called on `popstate` with the previous state id and container // contents. // direction - "forward" or "back" String // id - State ID Number // value - DOM Element to cache // Returns nothing. function cachePop(direction, id, value) { if (!pjax.options.cache) { return; } var pushStack, popStack cacheMapping[id] = value if (direction === 'forward') { pushStack = cacheBackStack popStack = cacheForwardStack } else { pushStack = cacheForwardStack popStack = cacheBackStack } pushStack.push(id) if (id = popStack.pop()) delete cacheMapping[id] // Trim whichever stack we just pushed to to max cache length. trimCacheStack(pushStack, pjax.defaults.maxCacheLength) } // Trim a cache stack (either cacheBackStack or cacheForwardStack) to be no // longer than the specified length, deleting cached DOM elements as necessary. // stack - Array of state IDs // length - Maximum length to trim to // Returns nothing. function trimCacheStack(stack, length) { while (stack.length > length) delete cacheMapping[stack.shift()] } // Public: Find version identifier for the initial page load. // Returns String version or undefined. function findVersion() { return $('meta').filter(function () { var name = $(this).attr('http-equiv') return name && name.toUpperCase() === 'X-PJAX-VERSION' }).attr('content') } // Install pjax functions on $.pjax to enable pushState behavior. // Does nothing if already enabled. // Examples // $.pjax.enable() // Returns nothing. function enable() { $.fn.pjax = fnPjax $.pjax = pjax $.pjax.enable = $.noop $.pjax.disable = disable $.pjax.click = handleClick $.pjax.submit = handleSubmit $.pjax.reload = pjaxReload $.pjax.defaults = { history: true, cache: true, timeout: 650, push: true, replace: false, type: 'GET', dataType: 'html', scrollTo: 0, maxCacheLength: 20, version: findVersion } $(window).on('popstate.pjax', onPjaxPopstate) } // Disable pushState behavior. // This is the case when a browser doesn't support pushState. It is // sometimes useful to disable pushState for debugging on a modern // browser. // Examples // $.pjax.disable() // Returns nothing. function disable() { $.fn.pjax = function () { return this } $.pjax = fallbackPjax $.pjax.enable = enable $.pjax.disable = $.noop $.pjax.click = $.noop $.pjax.submit = $.noop $.pjax.reload = function () { window.location.reload() } $(window).off('popstate.pjax', onPjaxPopstate) } // Add the state property to jQuery's event object so we can use it in // $(window).bind('popstate') if ($.inArray('state', $.event.props) < 0) $.event.props.push('state') // Is pjax supported by this browser? $.support.pjax = window.history && window.history.pushState && window.history.replaceState && // pushState isn't reliable on iOS until 5. !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/) $.support.pjax ? enable() : disable() })(jQuery);
@font-face { font-family: 'FontAwesome'; src: url('../icons/<API key>.eot'); src: url('../icons/<API key>.eot') format('embedded-opentype'), url('../icons/<API key>.woff') format('woff'), url('../icons/<API key>.ttf') format('truetype'); font-weight: normal; font-style: normal; } [class^="icon-"], [class*=" icon-"] { font-family: FontAwesome; font-weight: normal; font-style: normal; text-decoration: inherit; -<API key>: antialiased; /* sprites.less reset */ display: inline; width: auto; height: auto; line-height: normal; vertical-align: baseline; background-image: none; background-position: 0% 0%; background-repeat: repeat; margin-top: 0; } /* more sprites.less reset */ .icon-white, .nav-pills > .active > a > [class^="icon-"], .nav-pills > .active > a > [class*=" icon-"], .nav-list > .active > a > [class^="icon-"], .nav-list > .active > a > [class*=" icon-"], .navbar-inverse .nav > .active > a > [class^="icon-"], .navbar-inverse .nav > .active > a > [class*=" icon-"], .dropdown-menu > li > a:hover > [class^="icon-"], .dropdown-menu > li > a:hover > [class*=" icon-"], .dropdown-menu > .active > a > [class^="icon-"], .dropdown-menu > .active > a > [class*=" icon-"], .dropdown-submenu:hover > a > [class^="icon-"], .dropdown-submenu:hover > a > [class*=" icon-"] { background-image: none; } [class^="icon-"]:before, [class*=" icon-"]:before { text-decoration: inherit; display: inline-block; speak: none; } /* makes sure icons active on rollover in links */ a [class^="icon-"], a [class*=" icon-"] { display: inline-block; } /* makes the font 33% larger relative to the icon container */ .icon-large:before { vertical-align: -10%; font-size: 1.3333333333333333em; } .btn [class^="icon-"], .nav [class^="icon-"], .btn [class*=" icon-"], .nav [class*=" icon-"] { display: inline; /* keeps button heights with and without icons the same */ } .btn [class^="icon-"].icon-large, .nav [class^="icon-"].icon-large, .btn [class*=" icon-"].icon-large, .nav [class*=" icon-"].icon-large { line-height: .9em; } .btn [class^="icon-"].icon-spin, .nav [class^="icon-"].icon-spin, .btn [class*=" icon-"].icon-spin, .nav [class*=" icon-"].icon-spin { display: inline-block; } .nav-tabs [class^="icon-"], .nav-pills [class^="icon-"], .nav-tabs [class*=" icon-"], .nav-pills [class*=" icon-"] { /* keeps button heights with and without icons the same */ } .nav-tabs [class^="icon-"], .nav-pills [class^="icon-"], .nav-tabs [class*=" icon-"], .nav-pills [class*=" icon-"], .nav-tabs [class^="icon-"].icon-large, .nav-pills [class^="icon-"].icon-large, .nav-tabs [class*=" icon-"].icon-large, .nav-pills [class*=" icon-"].icon-large { line-height: .9em; } li [class^="icon-"], .nav li [class^="icon-"], li [class*=" icon-"], .nav li [class*=" icon-"] { display: inline-block; width: 1.25em; text-align: center; } li [class^="icon-"].icon-large, .nav li [class^="icon-"].icon-large, li [class*=" icon-"].icon-large, .nav li [class*=" icon-"].icon-large { /* increased font size for icon-large */ width: 1.5625em; } ul.icons { list-style-type: none; text-indent: -0.75em; } ul.icons li [class^="icon-"], ul.icons li [class*=" icon-"] { width: .75em; } .icon-muted { color: #eeeeee; } .icon-border { border: solid 1px #eeeeee; padding: .2em .25em .15em; -<API key>: 3px; -moz-border-radius: 3px; border-radius: 3px; } .icon-2x { font-size: 2em; } .icon-2x.icon-border { border-width: 2px; -<API key>: 4px; -moz-border-radius: 4px; border-radius: 4px; } .icon-3x { font-size: 3em; } .icon-3x.icon-border { border-width: 3px; -<API key>: 5px; -moz-border-radius: 5px; border-radius: 5px; } .icon-4x { font-size: 4em; } .icon-4x.icon-border { border-width: 4px; -<API key>: 6px; -moz-border-radius: 6px; border-radius: 6px; } .pull-right { float: right; } .pull-left { float: left; } [class^="icon-"].pull-left, [class*=" icon-"].pull-left { margin-right: .3em; } [class^="icon-"].pull-right, [class*=" icon-"].pull-right { margin-left: .3em; } .btn [class^="icon-"].pull-left.icon-2x, .btn [class*=" icon-"].pull-left.icon-2x, .btn [class^="icon-"].pull-right.icon-2x, .btn [class*=" icon-"].pull-right.icon-2x { margin-top: .18em; } .btn [class^="icon-"].icon-spin.icon-large, .btn [class*=" icon-"].icon-spin.icon-large { line-height: .8em; } .btn.btn-small [class^="icon-"].pull-left.icon-2x, .btn.btn-small [class*=" icon-"].pull-left.icon-2x, .btn.btn-small [class^="icon-"].pull-right.icon-2x, .btn.btn-small [class*=" icon-"].pull-right.icon-2x { margin-top: .25em; } .btn.btn-large [class^="icon-"], .btn.btn-large [class*=" icon-"] { margin-top: 0; } .btn.btn-large [class^="icon-"].pull-left.icon-2x, .btn.btn-large [class*=" icon-"].pull-left.icon-2x, .btn.btn-large [class^="icon-"].pull-right.icon-2x, .btn.btn-large [class*=" icon-"].pull-right.icon-2x { margin-top: .05em; } .btn.btn-large [class^="icon-"].pull-left.icon-2x, .btn.btn-large [class*=" icon-"].pull-left.icon-2x { margin-right: .2em; } .btn.btn-large [class^="icon-"].pull-right.icon-2x, .btn.btn-large [class*=" icon-"].pull-right.icon-2x { margin-left: .2em; } .icon-spin { display: inline-block; -moz-animation: spin 2s infinite linear; -o-animation: spin 2s infinite linear; -webkit-animation: spin 2s infinite linear; animation: spin 2s infinite linear; } @-moz-keyframes spin { 0% { -moz-transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); } } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(359deg); } } @-o-keyframes spin { 0% { -o-transform: rotate(0deg); } 100% { -o-transform: rotate(359deg); } } @-ms-keyframes spin { 0% { -ms-transform: rotate(0deg); } 100% { -ms-transform: rotate(359deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(359deg); } } @-moz-document url-prefix() { .icon-spin { height: .9em; } .btn .icon-spin { height: auto; } .icon-spin.icon-large { height: 1.25em; } .btn .icon-spin.icon-large { height: .75em; } } /* Humanitarian Font uses the Unicode Private Use Area (PUA) to ensure screen readers do not read off random characters that represent icons */ .icon-glass:before { content: "\f000"; } .icon-music:before { content: "\f001"; } .icon-search:before { content: "\f002"; } .icon-envelope:before { content: "\f003"; } .icon-heart:before { content: "\f004"; } .icon-star:before { content: "\f005"; } .icon-star-empty:before { content: "\f006"; } .icon-user:before { content: "\f007"; } .icon-film:before { content: "\f008"; } .icon-th-large:before { content: "\f009"; } .icon-th:before { content: "\f00a"; } .icon-th-list:before { content: "\f00b"; } .icon-ok:before { content: "\f00c"; } .icon-remove:before { content: "\f00d"; } .icon-zoom-in:before { content: "\f00e"; } .icon-zoom-out:before { content: "\f010"; } .icon-off:before { content: "\f011"; } .icon-signal:before { content: "\f012"; } .icon-cog:before { content: "\f013"; } .icon-trash:before { content: "\f014"; } .icon-home:before { content: "\f015"; } .icon-file:before { content: "\f016"; } .icon-time:before { content: "\f017"; } .icon-road:before { content: "\f018"; } .icon-download-alt:before { content: "\f019"; } .icon-download:before { content: "\f01a"; } .icon-upload:before { content: "\f01b"; } .icon-inbox:before { content: "\f01c"; } .icon-play-circle:before { content: "\f01d"; } .icon-repeat:before { content: "\f01e"; } /* \f020 doesn't work in Safari. all shifted one down */ .icon-refresh:before { content: "\f021"; } .icon-list-alt:before { content: "\f022"; } .icon-lock:before { content: "\f023"; } .icon-flag:before { content: "\f024"; } .icon-headphones:before { content: "\f025"; } .icon-volume-off:before { content: "\f026"; } .icon-volume-down:before { content: "\f027"; } .icon-volume-up:before { content: "\f028"; } .icon-qrcode:before { content: "\f029"; } .icon-barcode:before { content: "\f02a"; } .icon-tag:before { content: "\f02b"; } .icon-tags:before { content: "\f02c"; } .icon-book:before { content: "\f02d"; } .icon-bookmark:before { content: "\f02e"; } .icon-print:before { content: "\f02f"; } .icon-camera:before { content: "\f030"; } .icon-font:before { content: "\f031"; } .icon-bold:before { content: "\f032"; } .icon-italic:before { content: "\f033"; } .icon-text-height:before { content: "\f034"; } .icon-text-width:before { content: "\f035"; } .icon-align-left:before { content: "\f036"; } .icon-align-center:before { content: "\f037"; } .icon-align-right:before { content: "\f038"; } .icon-align-justify:before { content: "\f039"; } .icon-list:before { content: "\f03a"; } .icon-indent-left:before { content: "\f03b"; } .icon-indent-right:before { content: "\f03c"; } .icon-facetime-video:before { content: "\f03d"; } .icon-picture:before { content: "\f03e"; } .icon-pencil:before { content: "\f040"; } .icon-map-marker:before { content: "\f041"; } .icon-adjust:before { content: "\f042"; } .icon-tint:before { content: "\f043"; } .icon-edit:before { content: "\f044"; } .icon-share:before { content: "\f045"; } .icon-check:before { content: "\f046"; } .icon-move:before { content: "\f047"; } .icon-step-backward:before { content: "\f048"; } .icon-fast-backward:before { content: "\f049"; } .icon-backward:before { content: "\f04a"; } .icon-play:before { content: "\f04b"; } .icon-pause:before { content: "\f04c"; } .icon-stop:before { content: "\f04d"; } .icon-forward:before { content: "\f04e"; } .icon-fast-forward:before { content: "\f050"; } .icon-step-forward:before { content: "\f051"; } .icon-eject:before { content: "\f052"; } .icon-chevron-left:before { content: "\f053"; } .icon-chevron-right:before { content: "\f054"; } .icon-plus-sign:before { content: "\f055"; } .icon-minus-sign:before { content: "\f056"; } .icon-remove-sign:before { content: "\f057"; } .icon-ok-sign:before { content: "\f058"; } .icon-question-sign:before { content: "\f059"; } .icon-info-sign:before { content: "\f05a"; } .icon-screenshot:before { content: "\f05b"; } .icon-remove-circle:before { content: "\f05c"; } .icon-ok-circle:before { content: "\f05d"; } .icon-ban-circle:before { content: "\f05e"; } .icon-arrow-left:before { content: "\f060"; } .icon-arrow-right:before { content: "\f061"; } .icon-arrow-up:before { content: "\f062"; } .icon-arrow-down:before { content: "\f063"; } .icon-share-alt:before { content: "\f064"; } .icon-resize-full:before { content: "\f065"; } .icon-resize-small:before { content: "\f066"; } .icon-plus:before { content: "\f067"; } .icon-minus:before { content: "\f068"; } .icon-asterisk:before { content: "\f069"; } .<API key>:before { content: "\f06a"; } .icon-gift:before { content: "\f06b"; } .icon-leaf:before { content: "\f06c"; } .icon-fire:before { content: "\f06d"; } .icon-eye-open:before { content: "\f06e"; } .icon-eye-close:before { content: "\f070"; } .icon-warning-sign:before { content: "\f071"; } .icon-plane:before { content: "\f072"; } .icon-calendar:before { content: "\f073"; } .icon-random:before { content: "\f074"; } .icon-comment:before { content: "\f075"; } .icon-magnet:before { content: "\f076"; } .icon-chevron-up:before { content: "\f077"; } .icon-chevron-down:before { content: "\f078"; } .icon-retweet:before { content: "\f079"; } .icon-shopping-cart:before { content: "\f07a"; } .icon-folder-close:before { content: "\f07b"; } .icon-folder-open:before { content: "\f07c"; } .<API key>:before { content: "\f07d"; } .<API key>:before { content: "\f07e"; } .icon-bar-chart:before { content: "\f080"; } .icon-twitter-sign:before { content: "\f081"; } .icon-facebook-sign:before { content: "\f082"; } .icon-camera-retro:before { content: "\f083"; } .icon-key:before { content: "\f084"; } .icon-cogs:before { content: "\f085"; } .icon-comments:before { content: "\f086"; } .icon-thumbs-up:before { content: "\f087"; } .icon-thumbs-down:before { content: "\f088"; } .icon-star-half:before { content: "\f089"; } .icon-heart-empty:before { content: "\f08a"; } .icon-signout:before { content: "\f08b"; } .icon-linkedin-sign:before { content: "\f08c"; } .icon-pushpin:before { content: "\f08d"; } .icon-external-link:before { content: "\f08e"; } .icon-signin:before { content: "\f090"; } .icon-trophy:before { content: "\f091"; } .icon-github-sign:before { content: "\f092"; } .icon-upload-alt:before { content: "\f093"; } .icon-lemon:before { content: "\f094"; } .icon-phone:before { content: "\f095"; } .icon-check-empty:before { content: "\f096"; } .icon-bookmark-empty:before { content: "\f097"; } .icon-phone-sign:before { content: "\f098"; } .icon-twitter:before { content: "\f099"; } .icon-facebook:before { content: "\f09a"; } .icon-github:before { content: "\f09b"; } .icon-unlock:before { content: "\f09c"; } .icon-credit-card:before { content: "\f09d"; } .icon-rss:before { content: "\f09e"; } .icon-hdd:before { content: "\f0a0"; } .icon-bullhorn:before { content: "\f0a1"; } .icon-bell:before { content: "\f0a2"; } .icon-certificate:before { content: "\f0a3"; } .icon-hand-right:before { content: "\f0a4"; } .icon-hand-left:before { content: "\f0a5"; } .icon-hand-up:before { content: "\f0a6"; } .icon-hand-down:before { content: "\f0a7"; } .<API key>:before { content: "\f0a8"; } .<API key>:before { content: "\f0a9"; } .<API key>:before { content: "\f0aa"; } .<API key>:before { content: "\f0ab"; } .icon-globe:before { content: "\f0ac"; } .icon-wrench:before { content: "\f0ad"; } .icon-tasks:before { content: "\f0ae"; } .icon-filter:before { content: "\f0b0"; } .icon-briefcase:before { content: "\f0b1"; } .icon-fullscreen:before { content: "\f0b2"; } .icon-group:before { content: "\f0c0"; } .icon-link:before { content: "\f0c1"; } .icon-cloud:before { content: "\f0c2"; } .icon-beaker:before { content: "\f0c3"; } .icon-cut:before { content: "\f0c4"; } .icon-copy:before { content: "\f0c5"; } .icon-paper-clip:before { content: "\f0c6"; } .icon-save:before { content: "\f0c7"; } .icon-sign-blank:before { content: "\f0c8"; } .icon-reorder:before { content: "\f0c9"; } .icon-list-ul:before { content: "\f0ca"; } .icon-list-ol:before { content: "\f0cb"; } .icon-strikethrough:before { content: "\f0cc"; } .icon-underline:before { content: "\f0cd"; } .icon-table:before { content: "\f0ce"; } .icon-magic:before { content: "\f0d0"; } .icon-truck:before { content: "\f0d1"; } .icon-pinterest:before { content: "\f0d2"; } .icon-pinterest-sign:before { content: "\f0d3"; } .<API key>:before { content: "\f0d4"; } .icon-google-plus:before { content: "\f0d5"; } .icon-money:before { content: "\f0d6"; } .icon-caret-down:before { content: "\f0d7"; } .icon-caret-up:before { content: "\f0d8"; } .icon-caret-left:before { content: "\f0d9"; } .icon-caret-right:before { content: "\f0da"; } .icon-columns:before { content: "\f0db"; } .icon-sort:before { content: "\f0dc"; } .icon-sort-down:before { content: "\f0dd"; } .icon-sort-up:before { content: "\f0de"; } .icon-envelope-alt:before { content: "\f0e0"; } .icon-linkedin:before { content: "\f0e1"; } .icon-undo:before { content: "\f0e2"; } .icon-legal:before { content: "\f0e3"; } .icon-dashboard:before { content: "\f0e4"; } .icon-comment-alt:before { content: "\f0e5"; } .icon-comments-alt:before { content: "\f0e6"; } .icon-bolt:before { content: "\f0e7"; } .icon-sitemap:before { content: "\f0e8"; } .icon-umbrella:before { content: "\f0e9"; } .icon-paste:before { content: "\f0ea"; } .icon-lightbulb:before { content: "\f0eb"; } .icon-exchange:before { content: "\f0ec"; } .icon-cloud-download:before { content: "\f0ed"; } .icon-cloud-upload:before { content: "\f0ee"; } .icon-user-md:before { content: "\f0f0"; } .icon-stethoscope:before { content: "\f0f1"; } .icon-suitcase:before { content: "\f0f2"; } .icon-bell-alt:before { content: "\f0f3"; } .icon-coffee:before { content: "\f0f4"; } .icon-food:before { content: "\f0f5"; } .icon-file-alt:before { content: "\f0f6"; } .icon-building:before { content: "\f0f7"; } .icon-hospital:before { content: "\f0f8"; } .icon-ambulance:before { content: "\f0f9"; } .icon-medkit:before { content: "\f0fa"; } .icon-fighter-jet:before { content: "\f0fb"; } .icon-beer:before { content: "\f0fc"; } .icon-h-sign:before { content: "\f0fd"; } .icon-plus-sign-alt:before { content: "\f0fe"; } .<API key>:before { content: "\f100"; } .<API key>:before { content: "\f101"; } .<API key>:before { content: "\f102"; } .<API key>:before { content: "\f103"; } .icon-angle-left:before { content: "\f104"; } .icon-angle-right:before { content: "\f105"; } .icon-angle-up:before { content: "\f106"; } .icon-angle-down:before { content: "\f107"; } .icon-desktop:before { content: "\f108"; } .icon-laptop:before { content: "\f109"; } .icon-tablet:before { content: "\f10a"; } .icon-mobile-phone:before { content: "\f10b"; } .icon-circle-blank:before { content: "\f10c"; } .icon-quote-left:before { content: "\f10d"; } .icon-quote-right:before { content: "\f10e"; } .icon-spinner:before { content: "\f110"; } .icon-circle:before { content: "\f111"; } .icon-reply:before { content: "\f112"; } .icon-github-alt:before { content: "\f113"; } .<API key>:before { content: "\f114"; } .<API key>:before { content: "\f115"; } /* Here start the humanitarian ones */ /* Sector */ .icon-basicneeds:before { content: "\f5e4"; } .<API key>:before { content: "\f300"; } .<API key>:before { content: "\f301"; } .<API key>:before { content: "\f361"; } .<API key>:before { content: "\f362"; } .<API key>:before { content: "\f367"; } .<API key>:before { content: "\f366"; } .<API key>:before { content: "\f364"; } .<API key>:before { content: "\f365"; } .<API key>:before { content: "\f369"; } .<API key>:before { content: "\f359"; } .<API key>:before { content: "\f371"; } .<API key>:before { content: "\f368"; } .<API key>:before { content: "\f342"; } .<API key>:before { content: "\f36a"; } .<API key>:before { content: "\f3c8"; } .<API key>:before { content: "\f55c"; } .<API key>:before { content: "\f363"; } .<API key>:before { content: "\f334"; } .<API key>:before { content: "\f32a"; } /* New Sector */ .icon-new-basicneeds:before { content: "\f5e5"; } .<API key>:before { content: "\f5e8"; } .<API key>:before { content: "\f5e7"; } .<API key>:before { content: "\e7a1"; } .<API key>:before { content: "\e7a6"; } .<API key>:before { content: "\e7a7"; } .<API key>:before { content: "\e7a3"; } .<API key>:before { content: "\e7a2"; } .<API key>:before { content: "\e7a5"; } .<API key>:before { content: "\e7a4"; } .icon-new-refugee:before { content: "\e7a9"; } .icon-new-program:before { content: "\e7a8"; } /* Affected population */ .<API key>:before { content: "\f3b0"; } .<API key>:before { content: "\f30c"; } .<API key>:before { content: "\f30d"; } .<API key>:before { content: "\f30e"; } .<API key>:before { content: "\f30f"; } .<API key>:before { content: "\f31a"; } .<API key>:before { content: "\f40d"; } .<API key>:before { content: "\f40a"; } .icon-child_soldier:before { content: "\f54f"; } .icon-individual:before { content: "\f5a8"; } /* Relief Item */ .<API key>:before { content: "\f401"; } .<API key>:before { content: "\f402"; } .<API key>:before { content: "\f403"; } .icon-ocha-item-food:before { content: "\f404"; } .<API key>:before { content: "\f405"; } .<API key>:before { content: "\f406"; } .<API key>:before { content: "\f407"; } .<API key>:before { content: "\f411"; } .<API key>:before { content: "\f412"; } .<API key>:before { content: "\f413"; } .<API key>:before { content: "\f414"; } .icon-ocha-item-tent:before { content: "\f415"; } .<API key>:before { content: "\f409"; } .<API key>:before { content: "\f410"; } .icon-ocha-cash:before { content: "\f533"; } /* Event */ .<API key>:before { content: "\f39f"; } .icon-event-force:before { content: "\f40e"; } .<API key>:before { content: "\f41b"; } .<API key>:before { content: "\f57a"; } .icon-event-judge:before { content: "\f564"; } .icon-event-protest:before { content: "\f569"; } .icon-event-cashwork:before { content: "\f573"; } .<API key>:before { content: "\f557"; } .<API key>:before { content: "\f554"; } .<API key>:before { content: "\f559"; } .icon-event-lecturer:before { content: "\f566"; } .icon-event-hit:before { content: "\f548"; } .<API key>:before { content: "\f574"; } .icon-event-register:before { content: "\f560"; } .icon-event-violence:before { content: "\f55e"; } /* Relief Item .icon-ocha-security:before { content: "\f327"; } .icon-ocha-security:before { content: "\f328"; } .icon-ocha-security:before { content: "\f329"; } .icon-ocha-security:before { content: "\f330"; } .icon-ocha-security:before { content: "\f331"; } .icon-ocha-security:before { content: "\f332"; } .icon-ocha-security:before { content: "\f333"; } .icon-ocha-security:before { content: "\f334"; } .icon-ocha-security:before { content: "\f335"; } .icon-ocha-security:before { content: "\f336"; } .icon-ocha-security:before { content: "\f337"; } .icon-ocha-security:before { content: "\f338"; } .icon-ocha-security:before { content: "\f339"; } .icon-ocha-security:before { content: "\f340"; } .icon-ocha-security:before { content: "\f341"; } .icon-ocha-security:before { content: "\f342"; } .icon-ocha-security:before { content: "\f343"; } .icon-ocha-security:before { content: "\f344"; } .icon-ocha-security:before { content: "\f345"; } .icon-ocha-security:before { content: "\f346"; } .icon-ocha-security:before { content: "\f347"; } .icon-ocha-security:before { content: "\f348"; } .icon-ocha-security:before { content: "\f349"; } .icon-ocha-security:before { content: "\f350"; } .icon-ocha-security:before { content: "\f351"; } .icon-ocha-security:before { content: "\f352"; } .icon-ocha-security:before { content: "\f353"; } .icon-ocha-security:before { content: "\f354"; } .icon-ocha-security:before { content: "\f355"; } .icon-ocha-security:before { content: "\f356"; } .icon-ocha-security:before { content: "\f357"; } .icon-ocha-security:before { content: "\f358"; } .icon-ocha-security:before { content: "\f359"; } .icon-ocha-security:before { content: "\f360"; } .icon-ocha-security:before { content: "\f361"; } .icon-ocha-security:before { content: "\f362"; } .icon-ocha-security:before { content: "\f363"; } .icon-ocha-security:before { content: "\f364"; } .icon-ocha-security:before { content: "\f365"; } .icon-ocha-security:before { content: "\f366"; } .icon-ocha-security:before { content: "\f367"; } .icon-ocha-security:before { content: "\f368"; } .icon-ocha-security:before { content: "\f369"; } .icon-ocha-security:before { content: "\f370"; } .icon-ocha-security:before { content: "\f371"; } .icon-ocha-security:before { content: "\f372"; } .icon-ocha-security:before { content: "\f373"; } .icon-ocha-security:before { content: "\f374"; } .icon-ocha-security:before { content: "\f375"; } .icon-ocha-security:before { content: "\f376"; } .icon-ocha-security:before { content: "\f377"; } .icon-ocha-security:before { content: "\f378"; } .icon-ocha-security:before { content: "\f379"; } .icon-ocha-security:before { content: "\f380"; } .icon-ocha-security:before { content: "\f381"; } .icon-ocha-security:before { content: "\f382"; } .icon-ocha-security:before { content: "\f383"; } .icon-ocha-security:before { content: "\f384"; } .icon-ocha-security:before { content: "\f385"; } .icon-ocha-security:before { content: "\f386"; } .icon-ocha-security:before { content: "\f387"; } .icon-ocha-security:before { content: "\f388"; } .icon-ocha-security:before { content: "\f389"; } .icon-ocha-security:before { content: "\f390"; } .icon-ocha-security:before { content: "\f391"; } .icon-ocha-security:before { content: "\f392"; } .icon-ocha-security:before { content: "\f393"; } .icon-ocha-security:before { content: "\f394"; } .icon-ocha-security:before { content: "\f395"; } .icon-ocha-security:before { content: "\f396"; } .icon-ocha-security:before { content: "\f397"; } .icon-ocha-security:before { content: "\f398"; } .icon-ocha-security:before { content: "\f399"; } .icon-ocha-security:before { content: "\f400"; } .icon-ocha-security:before { content: "\f401"; } .icon-ocha-security:before { content: "\f402"; } .icon-ocha-security:before { content: "\f403"; } .icon-ocha-security:before { content: "\f404"; } .icon-ocha-security:before { content: "\f405"; } .icon-ocha-security:before { content: "\f406"; } .icon-ocha-security:before { content: "\f407"; } .icon-ocha-security:before { content: "\f408"; } .icon-ocha-security:before { content: "\f409"; } .icon-ocha-security:before { content: "\f410"; } .icon-ocha-security:before { content: "\f411"; } .icon-ocha-security:before { content: "\f412"; } .icon-ocha-security:before { content: "\f413"; } .icon-ocha-security:before { content: "\f414"; } .icon-ocha-security:before { content: "\f415"; } .icon-ocha-security:before { content: "\f416"; } .icon-ocha-security:before { content: "\f417"; } .icon-ocha-security:before { content: "\f418"; } .icon-ocha-security:before { content: "\f419"; } .icon-ocha-security:before { content: "\f420"; } */ /* Information management */ .icon-im-coord:before { content: "\e69f"; } .icon-im-pie:before { content: "\e615"; } .icon-im-line:before { content: "\e60f"; } .icon-im-increase:before { content: "\e611"; } .icon-im-bar:before { content: "\e6c0"; } .icon-im-pin:before { content: "\e6c4"; } /* UNHCR map */ .icon-unhcr-office:before { content: "\f500"; } .<API key>:before { content: "\f501"; } .<API key>:before { content: "\f50a"; } .<API key>:before { content: "\f50b"; } .<API key>:before { content: "\f502"; } .<API key>:before { content: "\f503"; } .<API key>:before { content: "\f504"; } .icon-unhcr-location:before { content: "\f505"; } .<API key>:before { content: "\f506"; } .<API key>:before { content: "\f507"; } .<API key>:before { content: "\f508"; } .<API key>:before { content: "\f509"; } .<API key>:before { content: "\f510"; } .<API key>:before { content: "\f511"; } .<API key>:before { content: "\f512"; } .<API key>:before { content: "\f5e1"; } .<API key>:before { content: "\f5e2"; } .<API key>:before { content: "\f57d"; } .icon-office-ngo:before { content: "\f57c"; } /* Humanitarian Organisation */ .icon-orga-acp:before { content: "\f800"; } .<API key>:before { content: "\f801"; } .<API key>:before { content: "\f802"; } .<API key>:before { content: "\f803"; } .<API key>:before { content: "\f804"; } .icon-orga-ecowas:before { content: "\f806"; } .icon-orga-ecre:before { content: "\f807"; } .<API key>:before { content: "\f808"; } .icon-orga-fao:before { content: "\f809"; } .icon-orga-gichd:before { content: "\f810"; } .<API key>:before { content: "\f811"; } .icon-orga-icrc:before { content: "\f812"; } .icon-orga-icva:before { content: "\f813"; } .icon-orga-ifrc:before { content: "\f814"; } .icon-orga-iftdh:before { content: "\f815"; } .icon-orga-ilo:before { content: "\f816"; } .<API key>:before { content: "\f817"; } .icon-orga-iom:before { content: "\f818"; } .icon-orga-irc:before { content: "\f819"; } .icon-orga-itu:before { content: "\f820"; } .icon-orga-iucn:before { content: "\f821"; } .icon-orga-loas:before { content: "\f822"; } .icon-orga-lwf:before { content: "\f823"; } .icon-orga-mdm:before { content: "\f824"; } .icon-orga-nato:before { content: "\f825"; } .icon-orga-ocha:before { content: "\f826"; } .icon-orga-ohchr:before { content: "\f827"; } .icon-orga-oic:before { content: "\f828"; } .icon-orga-osagi:before { content: "\f829"; } .icon-orga-osce:before { content: "\f830"; } .icon-orga-oxfam:before { content: "\f831"; } .<API key>:before { content: "\f832"; } .<API key>:before { content: "\f833"; } .icon-orga-unaids:before { content: "\f834"; } .icon-orga-undp:before { content: "\f834"; } .icon-orga-unece:before { content: "\f835"; } .icon-orga-unep:before { content: "\f836"; } .icon-orga-unesco:before { content: "\f837"; } .icon-orga-unfpa:before { content: "\f838"; } .icon-orga-unhcr:before { content: "\f839"; } .icon-orga-unhsp:before { content: "\f840"; } .icon-orga-unicef:before { content: "\f841"; } .icon-orga-unitair:before { content: "\f842"; } .icon-orga-undoc:before { content: "\f843"; } .icon-orga-unops:before { content: "\f844"; } .icon-orga-unrwa:before { content: "\f84a"; } .icon-orga-unv:before { content: "\f845"; } .icon-orga-voice:before { content: "\f846"; } .icon-orga-wcc:before { content: "\f847"; } .icon-orga-wfp:before { content: "\f848"; } .icon-orga-who:before { content: "\f849"; } .icon-orga-wipo:before { content: "\f850"; } .icon-orga-wmo:before { content: "\f851"; } .icon-orga-word-bank:before { content: "\f852"; } .icon-orga-msf:before { content: "\f853"; } .icon-orga-unog:before { content: "\f854"; } .icon-orga-cartong:before { content: "\f855"; }
# bootstrap.py from machine import State from pydgin.utils import r_uint #from pydgin.storage import Memory EMULATE_GEM5 = False EMULATE_SIMIT = True # Currently these constants are set to match gem5 memory_size = 2**27 page_size = 8192 if EMULATE_SIMIT: memory_size = 0xc0000000 + 1 MAX_ENVIRON = 1024 * 16 # MIPS stack starts at top of kuseg (0x7FFF.FFFF) and grows down #stack_base = 0x7FFFFFFF stack_base = memory_size-1 # TODO: set this correctly! # syscall_init # MIPS Memory Map (32-bit): # 0xC000.0000 - Mapped (kseg2) - 1GB # 0xA000.0000 - Unmapped uncached (kseg1) - 512MB # 0x8000.0000 - Unmapped cached (kseg0) - 512MB # 0x0000.0000 - 32-bit user space (kuseg) - 2GB def syscall_init( mem, entrypoint, breakpoint, argv, envp, debug ): # memory map initialization # TODO: for multicore allocate 8MB for each process #proc_stack_base[pid] = stack_base - pid * 8 * 1024 * 1024 # top of heap (breakpoint) # TODO: handled in load program # memory maps: 1GB above top of heap # mmap_start = mmap_end = break_point + 0x40000000 # stack argument initialization # contents size # 0x7FFF.FFFF [ end marker ] 4 (NULL) # [ environment str data ] >=0 # [ arguments str data ] >=0 # [ padding ] 0-16 # [ auxv[n] data ] 8 (AT_NULL Vector) # [ auxv[0] data ] 8 # [ envp[n] pointer ] 4 (NULL) # [ envp[0] pointer ] 4 # [ argv[n] pointer ] 4 (NULL) # [ argv[0] pointer ] 4 (program name) # stack ptr-> [ argc ] 4 (size of argv) # (stack grows down!!!) # 0x7F7F.FFFF < stack limit for pid 0 > # auxv variables initialized by gem5, are these needed? # - PAGESZ: system page size # - PHDR: virtual addr of program header tables # (for statically linked binaries) # - PHENT: size of program header entries in elf file # - PHNUM: number of program headers in elf file # - AT_ENRTY: program entry point # - UID: user ID # - EUID: effective user ID # - GID: group ID # - EGID: effective group ID # TODO: handle auxv, envp variables auxv = [] if EMULATE_GEM5: argv = argv[1:] argc = len( argv ) def sum_( x ): val = 0 for i in x: val += i return val # calculate sizes of sections # TODO: parameterize auxv/envp/argv calc for variable int size? stack_nbytes = [ 4, # end mark nbytes (sentry) sum_([len(x)+1 for x in envp]), # envp_str nbytes sum_([len(x)+1 for x in argv]), # argv_str nbytes 0, # padding nbytes 8*(len(auxv) + 1), # auxv nbytes 4*(len(envp) + 1), # envp nbytes 4*(len(argv) + 1), # argv nbytes 4 ] # argc nbytes if EMULATE_SIMIT: stack_nbytes[4] = 0 # don't to auxv for simit def round_up( val ): alignment = 16 return (val + alignment - 1) & ~(alignment - 1) # calculate padding to align boundary # NOTE: MIPs approach (but ignored by gem5) #stack_nbytes[3] = 16 - (sum_(stack_nbytes[:3]) % 16) # NOTE: gem5 ARM approach stack_nbytes[3] = round_up( sum_(stack_nbytes) ) - sum_(stack_nbytes) if EMULATE_SIMIT: stack_nbytes[3] = 0 def round_down( val ): alignment = 16 return val & ~(alignment - 1) # calculate stack pointer based on size of storage needed for args # TODO: round to nearest page size? stack_ptr = round_down( stack_base - sum_( stack_nbytes ) ) if EMULATE_SIMIT: stack_ptr = stack_base - MAX_ENVIRON offset = stack_ptr + sum_( stack_nbytes ) # FIXME: this offset seems really wrong, but this is how gem5 does it! if EMULATE_GEM5: offset = stack_base print "XXX", offset stack_off = [] for nbytes in stack_nbytes: offset -= nbytes stack_off.append( offset ) # FIXME: this is fails for GEM5's hacky offset... if not EMULATE_GEM5: assert offset == stack_ptr if debug.enabled( 'bootstrap' ): print 'stack base', hex( stack_base ) print 'stack min ', hex( stack_ptr ) print 'stack size', stack_base - stack_ptr print print 'sentry ', stack_nbytes[0] print 'env d ', stack_nbytes[1] print 'arg d ', stack_nbytes[2] print 'padding', stack_nbytes[3] print 'auxv ', stack_nbytes[4] print 'envp ', stack_nbytes[5] print 'argv ', stack_nbytes[6] print 'argc ', stack_nbytes[7] # utility functions def str_to_mem( mem, val, addr ): for i, char in enumerate(val+'\0'): mem.write( addr + i, 1, ord( char ) ) return addr + len(val) + 1 def int_to_mem( mem, val, addr ): # TODO properly handle endianess for i in range( 4 ): mem.write( addr+i, 1, (val >> 8*i) & 0xFF ) return addr + 4 # write end marker to memory int_to_mem( mem, 0, stack_off[0] ) # write environment strings to memory envp_ptrs = [] offset = stack_off[1] for x in envp: envp_ptrs.append( offset ) offset = str_to_mem( mem, x, offset ) assert offset == stack_off[0] # write argument strings to memory argv_ptrs = [] offset = stack_off[2] for x in argv: argv_ptrs.append( offset ) offset = str_to_mem( mem, x, offset ) assert offset == stack_off[1] # write auxv vectors to memory offset = stack_off[4] if not EMULATE_SIMIT: for type_, value in auxv + [(0,0)]: offset = int_to_mem( mem, type_, offset ) offset = int_to_mem( mem, value, offset ) assert offset == stack_off[3] # write envp pointers to memory offset = stack_off[5] for env in envp_ptrs + [0]: offset = int_to_mem( mem, env, offset ) assert offset == stack_off[4] # write argv pointers to memory offset = stack_off[6] for arg in argv_ptrs + [0]: offset = int_to_mem( mem, arg, offset ) assert offset == stack_off[5] # write argc to memory offset = stack_off[7] offset = int_to_mem( mem, argc, offset ) assert offset == stack_off[6] # write zeros to bottom of stack # TODO: why does gem5 do this? offset = stack_off[7] - 1 while offset >= stack_ptr: mem.write( offset, 1, ord( '\0' ) ) offset -= 1 # initialize processor state state = State( mem, debug, reset_addr=0x1000 ) if debug.enabled( 'bootstrap' ): print ' #print 'argc = %d (%x)' % ( argc, stack_off[-1] ) #for i, ptr in enumerate(argv_ptrs): # print 'argv[%2d] = %x (%x)' % ( i, argv_ptrs[i], stack_off[-2]+4*i ), # print len( argv[i] ), argv[i] #print 'argd = %s (%x)' % ( argv[0], stack_off[-6] ) print ' print 'envd-base', hex(stack_off[-7]) print 'argd-base', hex(stack_off[-6]) print 'auxv-base', hex(stack_off[-4]) print 'envp-base', hex(stack_off[-3]) print 'argv-base', hex(stack_off[-2]) print 'argc-base', hex(stack_off[-1]) print 'STACK_PTR', hex( stack_ptr ) # TODO: where should this go? #state.pc = entrypoint state.breakpoint = r_uint( breakpoint ) # initialize processor registers state.rf[ 0 ] = 0 # ptr to func to run when program exits, disable state.rf[ 1 ] = stack_off[6] # argument 1 reg = argv ptr addr state.rf[ 2 ] = stack_off[5] # argument 2 reg = envp ptr addr if EMULATE_SIMIT: state.rf[ 1 ] = argc # argument 1 reg = argc state.rf[ 2 ] = stack_off[6] # argument 2 reg = argv ptr addr state.rf[ 13 ] = stack_ptr # stack pointer reg state.rf[ 15 ] = entrypoint # program counter if debug.enabled( 'bootstrap' ): state.rf.print_regs( per_row=4 ) print '='* 20, 'end bootstrap', '='*20 return state
#include "range.h" #include <ctype.h> #include <errno.h> #include <kdbassert.h> #include <kdberrors.h> #include <kdbhelper.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> typedef enum { INT, UINT, FLOAT, CHAR, HEX, NA, } RangeType; typedef struct { RangeType type; union uValue { unsigned long long int i; long double f; } Value; } RangeValue; // switch min and max values if needed and apply -1 factor static void normalizeValues (RangeType type, RangeValue * min, RangeValue * max, RangeValue * a, RangeValue * b, int factorA, int factorB) { unsigned long long int tmpIA = factorA == -1 ? ULLONG_MAX - (*a).Value.i + 1 : (*a).Value.i; unsigned long long int tmpIB = factorB == -1 ? ULLONG_MAX - (*b).Value.i + 1 : (*b).Value.i; long double tmpFA = factorA * (*a).Value.f; long double tmpFB = factorB * (*b).Value.f; switch (type) { case INT: case HEX: case CHAR: if ((long long) tmpIA <= (long long) tmpIB) { min->Value.i = tmpIA; max->Value.i = tmpIB; } else { min->Value.i = tmpIB; max->Value.i = tmpIA; } break; case UINT: if (tmpIA <= tmpIB) { min->Value.i = tmpIA; max->Value.i = tmpIB; } else { min->Value.i = tmpIB; max->Value.i = tmpIA; } break; case FLOAT: if (tmpFA <= tmpFB) { min->Value.f = tmpFA; max->Value.f = tmpFB; } else { min->Value.f = tmpFB; max->Value.f = tmpFA; } break; default: break; } } // parse value starting at ptr and set ptr to the first character // after value. return a RangeValue with type == NA on error RangeValue strToValue (const char ** ptr, RangeType type) { RangeValue v; v.type = type; v.Value.i = 0; char * endPtr = NULL; errno = 0; // the c std library doesn't reset errno, so do it before conversions to be safe switch (type) { case INT: case UINT: v.Value.i = strtoull (*ptr, &endPtr, 10); if (errno == ERANGE || (errno != 0 && v.Value.i == 0)) { v.type = NA; } break; case FLOAT: v.Value.f = strtold (*ptr, &endPtr); if (errno == ERANGE || (errno != 0 && fpclassify (v.Value.f) == FP_ZERO)) { v.type = NA; } break; case HEX: v.Value.i = strtoull (*ptr, &endPtr, 16); if (errno == ERANGE || (errno != 0 && v.Value.i == 0)) { v.type = NA; } break; case CHAR: if (!isalpha (**ptr)) { v.type = NA; } v.Value.i = **ptr; endPtr = (char *) *ptr + 1; default: break; } *ptr = endPtr; return v; } // parse string into min - max values // return -1 on error, 0 on success; static int rangeStringToRange (const char * rangeString, RangeValue * min, RangeValue * max, RangeType type) { int factorA = 1; // multiplication factors for parsed values int factorB = 1; // if '-' is read, factor will be set to -1 RangeValue a, b; a.type = type; b.type = type; a.Value.i = 0; b.Value.i = 0; int pos = 0; const char * ptr = rangeString; while (*ptr) { if (isspace (*ptr)) { ++ptr; continue; } else if (*ptr == '-') { if (pos == 0) { if (factorA == -1) { return -1; } if (type == UINT) { return -1; } factorA = -1; } else if (pos == 1) { pos = 2; } else if (pos == 2) { if (factorB == -1) { return -1; } if (type == UINT) { return -1; } factorB = -1; } else { return -1; } ++ptr; continue; } else if (isalnum (*ptr)) { if (pos == 0) { pos = 1; a = strToValue (&ptr, type); } else if (pos == 2) { pos = 3; b = strToValue (&ptr, type); if (b.type == NA) { return -1; } } else { return -1; } } else { return -1; } } if (pos != 1 && pos != 3) { return -1; } if (pos == 1) { b = a; factorB = factorA; } normalizeValues (type, min, max, &a, &b, factorA, factorB); return 0; } static int validateSingleRange (const char * valueStr, const char * rangeString, RangeType type) { RangeValue min, max; min.Value.i = 0; max.Value.i = 0; min.type = type; max.type = type; int rc = rangeStringToRange (rangeString, &min, &max, type); if (rc) { return -1; } RangeValue val; val.type = type; val.Value.i = 0; char * endPtr; errno = 0; // the c std library doesn't reset errno, so do it before conversions to be safe switch (type) { case INT: case UINT: val.Value.i = strtoull (valueStr, &endPtr, 10); break; case FLOAT: val.Value.f = strtold (valueStr, &endPtr); break; case HEX: val.Value.i = strtoull (valueStr, &endPtr, 16); break; case CHAR: val.Value.i = valueStr[0]; break; default: break; } if (errno == ERANGE || (errno != 0 && val.Value.i == 0)) { return -1; } switch (type) { case INT: case HEX: case CHAR: if ((long long) val.Value.i < (long long) min.Value.i || (long long) val.Value.i > (long long) max.Value.i) { return 0; } else { return 1; } break; case UINT: if (val.Value.i < min.Value.i || val.Value.i > max.Value.i) { return 0; } else { return 1; } break; case FLOAT: if (val.Value.f < min.Value.f || val.Value.f > max.Value.f) { return 0; } else { return 1; } break; default: return -1; break; } } static int <API key> (const char * valueStr, const char * rangeString, Key * parentKey, RangeType type) { char * localCopy = elektraStrDup (rangeString); char * savePtr = NULL; char * token = strtok_r (localCopy, ",", &savePtr); int rc = validateSingleRange (valueStr, token, type); if (rc == 1) { elektraFree (localCopy); return 1; } else if (rc == -1) { elektraFree (localCopy); <API key> (parentKey, "Invalid syntax: %s", token); return -1; } while ((token = strtok_r (NULL, ",", &savePtr)) != NULL) { rc = validateSingleRange (valueStr, token, type); if (rc == 1) { elektraFree (localCopy); return 1; } else if (rc == -1) { elektraFree (localCopy); <API key> (parentKey, "Invalid syntax: %s", token); return -1; } } elektraFree (localCopy); return 0; } static RangeType stringToType (const Key * typeMeta) { if (typeMeta) { static const char * intTypes[] = { "short", "long", "long long", NULL, }; static const char * uintTypes[] = { "unsigned short", "unsigned long", "unsigned long long", NULL, }; static const char * floatTypes[] = { "float", "double", "long double", NULL, }; const char * strVal = keyString (typeMeta); for (int i = 0; intTypes[i] != NULL; ++i) { if (!strcasecmp (strVal, intTypes[i])) return INT; } for (int i = 0; uintTypes[i] != NULL; ++i) { if (!strcasecmp (strVal, uintTypes[i])) return UINT; } for (int i = 0; floatTypes[i] != NULL; ++i) { if (!strcasecmp (strVal, floatTypes[i])) return FLOAT; } if (!strcasecmp (strVal, "char")) return CHAR; else if (!strcasecmp (strVal, "HEX")) return HEX; } return NA; } static RangeType getType (const Key * key) { const Key * typeMeta = keyGetMeta (key, "check/type"); // If "check/type" is not specified, fall back to "type". // As decided in https://github.com/ElektraInitiative/libelektra/issues/3984#<API key> if (typeMeta == NULL) { typeMeta = keyGetMeta (key, "type"); } RangeType type = stringToType (typeMeta); if (type == NA) return INT; else return type; } static int validateKey (Key * key, Key * parentKey, bool errorsAsWarnings) { const Key * rangeMeta = keyGetMeta (key, "check/range"); const char * rangeString = keyString (rangeMeta); RangeType type = getType (key); if (type == UINT) { const char * ptr = keyString (key); while (*ptr) { if (*ptr == '-') { return -1; } else if (isdigit (*ptr)) { break; } ++ptr; } } if (!strchr (rangeString, ',')) { int rc = validateSingleRange (keyString (key), rangeString, type); if (rc == -1) { if (errorsAsWarnings) { <API key> (parentKey, "Invalid syntax: %s", keyString (rangeMeta)); return 1; } else { <API key> (parentKey, "Invalid syntax: %s", keyString (rangeMeta)); return -1; } } else if (rc == 0) { if (errorsAsWarnings) { <API key> (parentKey, RANGE_ERROR_MESSAGE, keyString (key), keyName (key), rangeString); return 0; } else { <API key> (parentKey, RANGE_ERROR_MESSAGE, keyString (key), keyName (key), rangeString); return 0; } } else { return rc; } } else { int rc = <API key> (keyString (key), rangeString, parentKey, type); if (rc == 0) { if (errorsAsWarnings) { <API key> (parentKey, RANGE_ERROR_MESSAGE, keyString (key), keyName (key), rangeString); } else { <API key> (parentKey, RANGE_ERROR_MESSAGE, keyString (key), keyName (key), rangeString); } } return rc; } } int elektraRangeGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED) { if (!elektraStrCmp (keyName (parentKey), "system:/elektra/modules/range")) { KeySet * contract = ksNew (30, keyNew ("system:/elektra/modules/range", KEY_VALUE, "range plugin waits for your orders", KEY_END), keyNew ("system:/elektra/modules/range/exports", KEY_END), keyNew ("system:/elektra/modules/range/exports/get", KEY_FUNC, elektraRangeGet, KEY_END), keyNew ("system:/elektra/modules/range/exports/set", KEY_FUNC, elektraRangeSet, KEY_END), keyNew ("system:/elektra/modules/range/exports/validateKey", KEY_FUNC, validateKey, KEY_END), #include ELEKTRA_README keyNew ("system:/elektra/modules/range/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END); ksAppend (returned, contract); ksDel (contract); return 1; // success } // Validate all keys, treat errors as warnings. Key * cur; while ((cur = ksNext (returned)) != NULL) { /* skip parent namespaces that differ from the key namespace, * otherwise every warning would get issued multiple times */ if (keyGetNamespace (parentKey) != keyGetNamespace (cur)) continue; const Key * meta = keyGetMeta (cur, "check/range"); if (meta) { validateKey (cur, parentKey, true); } } // Always return 1. We don't want kdbGet() to fail because of validation problems. return <API key>; // success } int elektraRangeSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED) { // set all keys // this function is optional Key * cur; while ((cur = ksNext (returned)) != NULL) { const Key * meta = keyGetMeta (cur, "check/range"); if (meta) { int rc = validateKey (cur, parentKey, false); if (rc <= 0) { return -1; } } } return 1; // success } Plugin * <API key> { // clang-format off return elektraPluginExport ("range", ELEKTRA_PLUGIN_GET, &elektraRangeGet, ELEKTRA_PLUGIN_SET, &elektraRangeSet, ELEKTRA_PLUGIN_END); }
package gov.nih.nci.cadsr.persist.concept; /** * @author hveerla * */ public class ConVO { String conIDSEQ; String concept_value; public ConVO(){ } /** * @return the conIDSEQ */ public String getConIDSEQ() { return conIDSEQ; } /** * @param conIDSEQ the conIDSEQ to set */ public void setConIDSEQ(String conIDSEQ) { this.conIDSEQ = conIDSEQ; } /** * @return the concept_value */ public String getConcept_value() { return concept_value; } /** * @param concept_value the concept_value to set */ public void setConcept_value(String concept_value) { this.concept_value = concept_value; } }
#include "SbetCommon.hpp" namespace pdal { Dimension::IdList fileDimensions() { Dimension::IdList ids; // Data for each point is in the source file in the order these dimensions // are listed, I would suppose. Would be really nice to have a reference // to the file spec. I searched the Internet and found that it is from // some company called Applanix (Trimble), but I can't find anything // describing the file format on their website. using namespace Dimension; ids.push_back(Id::GpsTime); ids.push_back(Id::Y); ids.push_back(Id::X); ids.push_back(Id::Z); ids.push_back(Id::XVelocity); ids.push_back(Id::YVelocity); ids.push_back(Id::ZVelocity); ids.push_back(Id::Roll); ids.push_back(Id::Pitch); ids.push_back(Id::Azimuth); ids.push_back(Id::WanderAngle); ids.push_back(Id::XBodyAccel); ids.push_back(Id::YBodyAccel); ids.push_back(Id::ZBodyAccel); ids.push_back(Id::XBodyAngRate); ids.push_back(Id::YBodyAngRate); ids.push_back(Id::ZBodyAngRate); return ids; } } // namespace pdal
#include "ximajbg.h" #if CXIMAGE_SUPPORT_JBG #include "ximaiter.h" #define JBIG_BUFSIZE 8192 #if <API key> bool CxImageJBG::Decode(CxFile *hFile) { if (hFile == NULL) return false; struct jbg_dec_state jbig_state; uint32_t xmax = 4294967295UL, ymax = 4294967295UL; uint32_t len, cnt; uint8_t *buffer=0,*p; int32_t result; cx_try { jbg_dec_init(&jbig_state); jbg_dec_maxsize(&jbig_state, xmax, ymax); buffer = (uint8_t*)malloc(JBIG_BUFSIZE); if (!buffer) cx_throw("Sorry, not enough memory available!"); result = JBG_EAGAIN; do { len = hFile->Read(buffer, 1, JBIG_BUFSIZE); if (!len) break; cnt = 0; p = buffer; while (len > 0 && (result == JBG_EAGAIN || result == JBG_EOK)) { result = jbg_dec_in(&jbig_state, p, len, &cnt); p += cnt; len -= cnt; } } while (result == JBG_EAGAIN || result == JBG_EOK); if (hFile->Error()) cx_throw("Problem while reading input file"); if (result != JBG_EOK && result != JBG_EOK_INTR) cx_throw("Problem with input file"); int32_t w, h, bpp, planes, ew; w = jbg_dec_getwidth(&jbig_state); h = jbg_dec_getheight(&jbig_state); planes = jbg_dec_getplanes(&jbig_state); bpp = (planes+7)>>3; ew = (w + 7)>>3; if (info.nEscape == -1){ head.biWidth = w; head.biHeight= h; info.dwType = CXIMAGE_FORMAT_JBG; cx_throw("output dimensions returned"); } switch (planes){ case 1: { uint8_t* binary_image = jbg_dec_getimage(&jbig_state, 0); if (!Create(w,h,1,CXIMAGE_FORMAT_JBG)) cx_throw(""); SetPaletteColor(0,255,255,255); SetPaletteColor(1,0,0,0); CImageIterator iter(this); iter.Upset(); for (int32_t i=0;i<h;i++){ iter.SetRow(binary_image+i*ew,ew); iter.PrevRow(); } break; } default: cx_throw("cannot decode images with more than 1 plane"); } jbg_dec_free(&jbig_state); free(buffer); } cx_catch { jbg_dec_free(&jbig_state); if (buffer) free(buffer); if (strcmp(message,"")) strncpy(info.szLastError,message,255); if (info.nEscape == -1 && info.dwType == CXIMAGE_FORMAT_JBG) return true; return false; } return true; } #endif //<API key> bool CxImageJBG::Encode(CxFile * hFile) { if (EncodeSafeCheck(hFile)) return false; if (head.biBitCount != 1){ strcpy(info.szLastError,"JBG can save only 1-bpp images"); return false; } int32_t w, h, bpp, planes, ew, i, j, x, y; w = head.biWidth; h = head.biHeight; planes = 1; bpp = (planes+7)>>3; ew = (w + 7)>>3; uint8_t mask; RGBQUAD *rgb = GetPalette(); if (CompareColors(&rgb[0],&rgb[1])<0) mask=255; else mask=0; uint8_t *buffer = (uint8_t*)malloc(ew*h*2); if (!buffer) { strcpy(info.szLastError,"Sorry, not enough memory available!"); return false; } for (y=0; y<h; y++){ i= y*ew; j= (h-y-1)*info.dwEffWidth; for (x=0; x<ew; x++){ buffer[i + x]=info.pImage[j + x]^mask; } } struct jbg_enc_state jbig_state; jbg_enc_init(&jbig_state, w, h, planes, &buffer, jbig_data_out, hFile); //jbg_enc_layers(&jbig_state, 2); //jbg_enc_lrlmax(&jbig_state, 800, 600); // Specify a few other options (each is ignored if negative) int32_t dl = -1, dh = -1, d = -1, l0 = -1, mx = -1; int32_t options = JBG_TPDON | JBG_TPBON | JBG_DPON; int32_t order = JBG_ILEAVE | JBG_SMID; jbg_enc_lrange(&jbig_state, dl, dh); jbg_enc_options(&jbig_state, order, options, l0, mx, -1); // now encode everything and send it to data_out() jbg_enc_out(&jbig_state); // give encoder a chance to free its temporary data structures jbg_enc_free(&jbig_state); free(buffer); if (hFile->Error()){ strcpy(info.szLastError,"Problem while writing JBG file"); return false; } return true; } #endif // CXIMAGE_SUPPORT_JBG
# Name: modulo1 # Purpose: # Created: 14/02/2012 # Licence: <your licence> #!/usr/bin/env python def main(): pass if __name__ == '__main__': main() import os import math import <API key> as chrono import <API key> as chronoirr # Create the simulation system. # (Do not create parts and constraints programmatically here, we will # load a mechanism from file) my_system = chrono.ChSystem() # Set the collision margins. This is expecially important for very large or # very small objects (as in this example)! Do this before creating shapes. chrono.ChCollisionModel.<API key>(0.001); chrono.ChCollisionModel.<API key>(0.001); # load the file generated by the SolidWorks CAD plugin # and add it to the ChSystem print ("Loading C::E scene..."); exported_items = chrono.<API key>('../../../data/solid_works/swiss_escapement') print ("...done!"); # Print exported items for my_item in exported_items: print (my_item.GetName()) # Add items to the physical system for my_item in exported_items: my_system.Add(my_item) # Create an Irrlicht application to visualize the system myapplication = chronoirr.ChIrrApp(my_system); myapplication.AddTypicalSky('../../../data/skybox/') myapplication.AddTypicalCamera(chronoirr.vector3df(0.6,0.6,0.8)) myapplication.AddTypicalLights() # ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items # in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. # If you need a finer control on which item really needs a visualization proxy in # Irrlicht, just use application.AssetBind(myitem); on a per-item basis. myapplication.AssetBindAll(); # ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets # that you added to the bodies into 3D shapes, they can be visualized by Irrlicht! myapplication.AssetUpdateAll(); # Run the simulation myapplication.GetSystem().<API key>(0.002); myapplication.SetTimestep(0.002) while(myapplication.GetDevice().run()): myapplication.BeginScene() myapplication.DrawAll() myapplication.DoStep() myapplication.EndScene()
@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "<API key>" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> <API key> %BUILDDIR%\qthelp\vero.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\vero.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end
<?php namespace SilverStripe\AssetAdmin\GraphQL; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\ResolveInfo; use SilverStripe\Assets\File; use SilverStripe\Assets\Folder; use SilverStripe\GraphQL\MutationCreator; use SilverStripe\GraphQL\OperationResolver; use SilverStripe\Versioned\Versioned; use SilverStripe\GraphQL\Util\<API key>; use SilverStripe\GraphQL\Manager; class <API key> extends MutationCreator implements OperationResolver { /** * @var <API key> */ protected $accessor; public function __construct(Manager $manager = null) { $this->accessor = new <API key>(); parent::__construct($manager); } public function attributes() { return [ 'name' => 'moveFiles', ]; } public function type() { return $this->manager->getType('FileInterface'); } public function args() { return [ 'folderId' => [ 'type' => Type::nonNull(Type::id()) ], 'fileIds' => [ 'type' => Type::listOf(Type::id()) ], ]; } public function resolve($object, array $args, $context, ResolveInfo $info) { $folderId = (isset($args['folderId'])) ? $args['folderId'] : 0; if ($folderId) { /** @var Folder $folder */ $folder = Versioned::get_by_stage(Folder::class, Versioned::DRAFT) ->byID($folderId); if (!$folder) { throw new \<API key>(sprintf( '%s#%s not found', Folder::class, $folderId )); } if (!$folder->canEdit($context['currentUser'])) { throw new \<API key>(sprintf( '%s edit not allowed', Folder::class )); } } $files = Versioned::get_by_stage(File::class, Versioned::DRAFT) ->byIDs($args['fileIds']); $errorFiles = []; /** @var File $file */ foreach ($files as $file) { if ($file->canEdit($context['currentUser'])) { $this->accessor->setValue($file, 'ParentID', $folderId); $file->writeToStage(Versioned::DRAFT); } else { $errorFiles[] = $file->ID; } } if ($errorFiles) { throw new \<API key>(sprintf( '%s (%s) edit not allowed', File::class, implode(', ', $errorFiles) )); } if (!isset($folder)) { return Folder::singleton(); } return $folder; } }
#ifndef <API key> #define <API key> #include "base/basictypes.h" #include "base/callback.h" #include "base/file_path.h" #include "base/gtest_prod_util.h" #include "base/location.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/cancelable_request.h" #include "chrome/browser/profiles/<API key>.h" #include "chrome/browser/sessions/session_id.h" #include "googleurl/src/gurl.h" class Profile; class SessionBackend; class SessionCommand; class TabNavigation; namespace content { class NavigationEntry; } // BaseSessionService is the super class of both tab restore service and // session service. It contains commonality needed by both, in particular // it manages a set of SessionCommands that are periodically sent to a // SessionBackend. class BaseSessionService : public <API key>, public ProfileKeyedService { public: // Identifies the type of session service this is. This is used by the // backend to determine the name of the files. enum SessionType { SESSION_RESTORE, TAB_RESTORE }; // Creates a new BaseSessionService. After creation you need to invoke // Init. // |type| gives the type of session service, |profile| the profile and // |path| the path to save files to. If |profile| is non-NULL, |path| is // ignored and instead the path comes from the profile. BaseSessionService(SessionType type, Profile* profile, const FilePath& path); Profile* profile() const { return profile_; } // Deletes the last session. void DeleteLastSession(); class <API key>; typedef base::Callback<void(Handle, scoped_refptr<<API key>>)> <API key>; // Callback used when fetching the last session. The last session consists // of a vector of SessionCommands. class <API key> : public CancelableRequest<<API key>> { public: explicit <API key>(const CallbackType& callback) : CancelableRequest<<API key>>(callback) { } // The commands. The backend fills this in for us. std::vector<SessionCommand*> commands; protected: virtual ~<API key>(); private: <API key>(<API key>); }; protected: virtual ~BaseSessionService(); // Returns the backend. SessionBackend* backend() const { return backend_; } // Returns the set of commands that needed to be scheduled. The commands // in the vector are owned by BaseSessionService, until they are scheduled // on the backend at which point the backend owns the commands. std::vector<SessionCommand*>& pending_commands() { return pending_commands_; } // Whether the next save resets the file before writing to it. void set_pending_reset(bool value) { pending_reset_ = value; } bool pending_reset() const { return pending_reset_; } // Returns the number of commands sent down since the last reset. int <API key>() const { return <API key>; } // Schedules a command. This adds |command| to pending_commands_ and // invokes StartSaveTimer to start a timer that invokes Save at a later // time. virtual void ScheduleCommand(SessionCommand* command); // Starts the timer that invokes Save (if timer isn't already running). void StartSaveTimer(); // Saves pending commands to the backend. This is invoked from the timer // scheduled by StartSaveTimer. virtual void Save(); // Creates a SessionCommand that represents a navigation. SessionCommand* <API key>( SessionID::id_type command_id, SessionID::id_type tab_id, int index, const content::NavigationEntry& entry); // Creates a SessionCommand that represents marking a tab as an application. SessionCommand* <API key>( SessionID::id_type command_id, SessionID::id_type tab_id, const std::string& extension_id); // Creates a SessionCommand that containing user agent override used by a // tab's navigations. SessionCommand* <API key>( SessionID::id_type command_id, SessionID::id_type tab_id, const std::string& user_agent_override); // Creates a SessionCommand stores a browser window's app name. SessionCommand* <API key>( SessionID::id_type command_id, SessionID::id_type window_id, const std::string& app_name); // <API key> into a TabNavigation. Returns true // on success. If successful |tab_id| is set to the id of the restored tab. bool <API key>(const SessionCommand& command, TabNavigation* navigation, SessionID::id_type* tab_id); // <API key> into the tab id and application // extension id. bool <API key>( const SessionCommand& command, SessionID::id_type* tab_id, std::string* extension_app_id); // <API key> into the tab id and user agent. bool <API key>( const SessionCommand& command, SessionID::id_type* tab_id, std::string* user_agent_override); // <API key> into the window id and application name. bool <API key>( const SessionCommand& command, SessionID::id_type* window_id, std::string* app_name); // Returns true if the entry at specified |url| should be written to disk. bool ShouldTrackEntry(const GURL& url); // Invokes <API key> with request on the backend thread. // If testing, <API key> is invoked directly. Handle <API key>( <API key>* request, <API key>* consumer); // In production, this posts the task to the FILE thread. For // tests, it immediately runs the specified task on the current // thread. bool <API key>(const tracked_objects::Location& from_here, const base::Closure& task); // Returns true if we appear to be running in production, false if we appear // to be running as part of a unit test or if the FILE thread has gone away. bool RunningInProduction() const; // Max number of navigation entries in each direction we'll persist. static const int <API key>; private: <API key>(SessionServiceTest, <API key>); <API key>(SessionServiceTest, RemovePostData); <API key>(SessionServiceTest, <API key>); // The profile. This may be null during testing. Profile* profile_; // The backend. scoped_refptr<SessionBackend> backend_; // Used to invoke Save. base::WeakPtrFactory<BaseSessionService> weak_factory_; // Commands we need to send over to the backend. std::vector<SessionCommand*> pending_commands_; // Whether the backend file should be recreated the next time we send // over the commands. bool pending_reset_; // The number of commands sent to the backend before doing a reset. int <API key>; // Whether to save the HTTP bodies of the POST requests. bool save_post_data_; <API key>(BaseSessionService); }; #endif // <API key>
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Tue May 01 09:56:12 CEST 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Interface net.sourceforge.pmd.lang.TokenManager (PMD 5.0.0 API) </TITLE> <META NAME="date" CONTENT="2012-05-01"> <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 Interface net.sourceforge.pmd.lang.TokenManager (PMD 5.0.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang"><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?net/sourceforge/pmd/lang//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TokenManager.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> <HR> <CENTER> <H2> <B>Uses of Interface<br>net.sourceforge.pmd.lang.TokenManager</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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.lang"><B>net.sourceforge.pmd.lang</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.lang.cpp"><B>net.sourceforge.pmd.lang.cpp</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.lang.ecmascript"><B>net.sourceforge.pmd.lang.ecmascript</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.lang.java"><B>net.sourceforge.pmd.lang.java</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.lang.jsp"><B>net.sourceforge.pmd.lang.jsp</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.lang.xml"><B>net.sourceforge.pmd.lang.xml</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.lang"></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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A> in <A HREF="../../../../../net/sourceforge/pmd/lang/package-summary.html">net.sourceforge.pmd.lang</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../net/sourceforge/pmd/lang/package-summary.html">net.sourceforge.pmd.lang</A> that return <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected abstract &nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>AbstractParser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/AbstractParser.html <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>&nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>AbstractParser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/AbstractParser.html <A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io">Reader</A>&nbsp;source)</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>&nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>Parser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/Parser.html <A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io">Reader</A>&nbsp;source)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get a TokenManager for the given source.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.lang.cpp"></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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A> in <A HREF="../../../../../net/sourceforge/pmd/lang/cpp/package-summary.html">net.sourceforge.pmd.lang.cpp</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../net/sourceforge/pmd/lang/cpp/package-summary.html">net.sourceforge.pmd.lang.cpp</A> that implement <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../net/sourceforge/pmd/lang/cpp/CppTokenManager.html" title="class in net.sourceforge.pmd.lang.cpp">CppTokenManager</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;C++ Token Manager implementation.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../net/sourceforge/pmd/lang/cpp/package-summary.html">net.sourceforge.pmd.lang.cpp</A> that return <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>CppParser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/cpp/CppParser.html <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.lang.ecmascript"></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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A> in <A HREF="../../../../../net/sourceforge/pmd/lang/ecmascript/package-summary.html">net.sourceforge.pmd.lang.ecmascript</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../net/sourceforge/pmd/lang/ecmascript/package-summary.html">net.sourceforge.pmd.lang.ecmascript</A> that return <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>Ecmascript3Parser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/ecmascript/Ecmascript3Parser.html <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.lang.java"></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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A> in <A HREF="../../../../../net/sourceforge/pmd/lang/java/package-summary.html">net.sourceforge.pmd.lang.java</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../net/sourceforge/pmd/lang/java/package-summary.html">net.sourceforge.pmd.lang.java</A> that implement <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../net/sourceforge/pmd/lang/java/JavaTokenManager.html" title="class in net.sourceforge.pmd.lang.java">JavaTokenManager</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Java Token Manager implementation.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../net/sourceforge/pmd/lang/java/package-summary.html">net.sourceforge.pmd.lang.java</A> that return <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>AbstractJavaParser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/java/AbstractJavaParser.html <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.lang.jsp"></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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A> in <A HREF="../../../../../net/sourceforge/pmd/lang/jsp/package-summary.html">net.sourceforge.pmd.lang.jsp</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../net/sourceforge/pmd/lang/jsp/package-summary.html">net.sourceforge.pmd.lang.jsp</A> that implement <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../net/sourceforge/pmd/lang/jsp/JspTokenManager.html" title="class in net.sourceforge.pmd.lang.jsp">JspTokenManager</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;JSP Token Manager implementation.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../net/sourceforge/pmd/lang/jsp/package-summary.html">net.sourceforge.pmd.lang.jsp</A> that return <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>JspParser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/jsp/JspParser.html <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.lang.xml"></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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A> in <A HREF="../../../../../net/sourceforge/pmd/lang/xml/package-summary.html">net.sourceforge.pmd.lang.xml</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="<API key>"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../net/sourceforge/pmd/lang/xml/package-summary.html">net.sourceforge.pmd.lang.xml</A> that return <A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang">TokenManager</A></CODE></FONT></TD> <TD><CODE><B>XmlParser.</B><B><A HREF="../../../../../net/sourceforge/pmd/lang/xml/XmlParser.html <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <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="<API key>"></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="../../../../../net/sourceforge/pmd/lang/TokenManager.html" title="interface in net.sourceforge.pmd.lang"><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?net/sourceforge/pmd/lang//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TokenManager.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> <HR> Copyright & </BODY> </HTML>
var tape = require('tape'), context = require('d3-path').path, vega = require('../'), Bounds = vega.Bounds, pathParse = vega.pathParse, pathRender = vega.pathRender; function bound(path, bounds) { pathRender(vega.boundContext(bounds), path, 0, 0); return bounds; } const paths = [ 'M 10,10 m 10,20', 'M 10,10 l 10,20', 'M 10,10 L 10,20', 'M 10,10 L 10,20 L 20,20 Z', 'M 10,10 L 10,20 L 20,20 z', 'M 10,10 h 20', 'M 10,10 H 20', 'M 10,10 v 20', 'M 10,10 V 20', 'M 10,10 c 10,0,10,10,0,10', 'M 10,10 C 10,0,10,10,0,10', 'M 10,10 c 10,0,10,10,0,10 s 10,20,20,0', 'M 10,10 C 10,0,10,10,0,10 S 10,20,20,0', 'M 10,10 q 10,10,0,10', 'M 10,10 Q 10,10,0,10', 'M 10,10 t 20,0', 'M 10,10 q 10,10,0,10 t 20,0', 'M 10,10 Q 10,10,0,10 t 20,0', 'M 10,10 t 0,10 t 20,0', 'M 10,10 Q 10,10,0,10 T 20,0', 'M 80,80 a 45,45,0,0,0,125,125 L 125,80 Z', 'M 80,80 A 45,45,0,0,0,125,125 L 125,80 Z', 'M 230,80 A 45,45,0,1,0,275,125 L 275,80 Z', 'M 80,230 A 45,45,0,0,1,125,275 L 125,230 Z', 'M 230,230 A 45,45,0,1,1,275,275 L 275,230 Z', 'M 0,0 A 0.45,0.45,0,1,1,20,20 Z', 'M 0,0 A 0.45,0.45,0,0,0,20,20 Z' ]; var bounds = [ { x1: 10, y1: 10, x2: 20, y2: 30 }, { x1: 10, y1: 10, x2: 20, y2: 30 }, { x1: 10, y1: 10, x2: 10, y2: 20 }, { x1: 10, y1: 10, x2: 20, y2: 20 }, { x1: 10, y1: 10, x2: 20, y2: 20 }, { x1: 10, y1: 10, x2: 30, y2: 10 }, { x1: 10, y1: 10, x2: 20, y2: 10 }, { x1: 10, y1: 10, x2: 10, y2: 30 }, { x1: 10, y1: 10, x2: 10, y2: 20 }, { x1: 10, y1: 10, x2: 17.5, y2: 20 }, { x1: 0, y1: 5.555555555555556, x2: 10, y2: 10 }, { x1: 7.274575140626315, y1: 10, x2: 30, y2: 28.888888888888886 }, { x1: -2.7254248593736854, y1: 0, x2: 20, y2: 12.5 }, { x1: 10, y1: 10, x2: 15, y2: 20 }, { x1: 0, y1: 10, x2: 10, y2: 10 }, { x1: 10, y1: 10, x2: 30, y2: 10 }, { x1: 7.5, y1: 10, x2: 30, y2: 20 }, { x1: 0, y1: 10, x2: 20, y2: 10 }, { x1: 10, y1: 10, x2: 30, y2: 25 }, { x1: -2.5, y1: 0, x2: 20, y2: 10 }, { x1: 54.11165235168157, y1: 80, x2: 205, y2: 230.88834764831847 }, { x1: 80, y1: 80, x2: 125, y2: 125 }, { x1: 185.00000000000003, y1: 80, x2: 275, y2: 170 }, { x1: 80, y1: 230, x2: 125, y2: 275 }, { x1: 230, y1: 185.00000000000003, x2: 320, y2: 275 }, { x1: 0, y1: -4.142135623730948, x2: 24.14213562373095, y2: 20 }, { x1: -4.142135623730949, y1: 0, x2: 19.999999999999996, y2: 24.14213562373095 } ]; const output = [ 'M10,10M20,30', 'M10,10L20,30', 'M10,10L10,20', 'M10,10L10,20L20,20Z', 'M10,10L10,20L20,20Z', 'M10,10L30,10', 'M10,10L20,10', 'M10,10L10,30', 'M10,10L10,20', 'M10,10C20,10,20,20,10,20', 'M10,10C10,0,10,10,0,10', 'M10,10C20,10,20,20,10,20C0,20,20,40,30,20', 'M10,10C10,0,10,10,0,10C-10,10,10,20,20,0', 'M10,10Q20,20,10,20', 'M10,10Q10,10,0,10', 'M10,10Q10,10,30,10', 'M10,10Q20,20,10,20Q0,20,30,20', 'M10,10Q10,10,0,10Q10,10,20,10', 'M10,10Q10,10,10,20Q10,30,30,20', 'M10,10Q10,10,0,10Q-10,10,20,0', 'M80,80C45.48220313557543,114.5177968644246,45.482203135575425,170.4822031355754,80,205C114.51779686442458,239.51779686442458,170.4822031355754,239.51779686442458,205,205L125,80Z', 'M80,80C80,104.8528137423857,100.1471862576143,125,125,125L125,80Z', 'M230,80C205.14718625761432,80,185.00000000000003,100.1471862576143,185.00000000000003,125C185.00000000000003,149.85281374238568,205.14718625761432,170,230.00000000000003,170C254.8528137423857,170,275,149.85281374238573,275,125.00000000000001L275,80Z', 'M80,230C104.85281374238569,230.00000000000003,125,250.14718625761432,125,275L125,230Z', 'M230,230C230.00000000000003,205.14718625761432,250.14718625761432,185.00000000000003,275,185.00000000000003C299.8528137423857,185.00000000000003,320,205.14718625761432,320,230.00000000000003C320,254.8528137423857,299.8528137423857,275,275,275L275,230Z', 'M0,0C5.522847498307938,-5.522847498307931,14.47715250169207,-5.522847498307931,20.000000000000004,3.<API key>.522847498307936,5.522847498307938,25.522847498307936,14.477152501692064,20.000000000000004,20Z', 'M0,0C-5.522847498307931,5.522847498307935,-5.522847498307933,14.477152501692064,0,20C5.522847498307933,25.522847498307936,14.47715250169206,25.522847498307936,19.999999999999996,20.000000000000004Z' ]; tape('pathParse should parse svg path', t => { const s1 = 'M1,1L1,2'; const s2 = 'M 1 1 L 1 2'; const s3 = 'M 1,1 L 1 2'; const p = [['M',1,1], ['L',1,2]]; t.deepEqual(pathParse(s1), p); t.deepEqual(pathParse(s2), p); t.deepEqual(pathParse(s3), p); t.end(); }); tape('pathParse should handle repeated arguments', t => { const s = 'M 1 1 L 1 2 3 4'; const p = [['M',1,1], ['L',1,2], ['L',3,4]]; t.deepEqual(pathParse(s), p); t.end(); }); tape('pathParse should skip NaN parameters', t => { const s = 'M 1 1 L 1 x'; const p = [['M',1,1], ['L',1]]; t.deepEqual(pathParse(s), p); t.end(); }); tape('pathParse should handle concatenated decimals', t => { const s = 'M.5.5l.3.3'; const p = [['M',.5,.5], ['l',.3,.3]]; t.deepEqual(pathParse(s), p); t.end(); }); tape('pathParse should handle implicit M lineTo', t => { const s = 'M0,0 1,1 2,2'; const p = [['M',0,0], ['L',1,1], ['L',2,2]]; t.deepEqual(pathParse(s), p); t.end(); }); tape('pathParse should handle implicit m lineTo', t => { const s = 'm0,0 1,1 2,2'; const p = [['m',0,0], ['l',1,1], ['l',2,2]]; t.deepEqual(pathParse(s), p); t.end(); }); tape('boundContext should calculate paths bounds', t => { for (let i=0; i<paths.length; ++i) { const p = pathParse(paths[i]); const b = bound(p, new Bounds()); t.equal(b.x1, bounds[i].x1); t.equal(b.x2, bounds[i].x2); t.equal(b.y1, bounds[i].y1); t.equal(b.y2, bounds[i].y2); } t.end(); }); tape('pathRender should render paths', t => { var ctx, p; for (let i=0; i<paths.length; ++i) { p = pathParse(paths[i]); pathRender(ctx = context(), p, 0, 0); t.ok(vega.pathEqual(ctx+'', output[i]), 'path: ' + paths[i]); } t.end(); }); tape('pathRender should translate paths', t => { const ctx = context(); pathRender(ctx, pathParse(paths[1]), 10, 50); t.equal(ctx+'', 'M20,60L30,80'); t.end(); }); tape('pathRender should scale paths', t => { const ctx = context(); pathRender(ctx, pathParse(paths[1]), 0, 0, 2, 0.5); t.equal(ctx+'', 'M20,5L40,15'); t.end(); });
package node import ( "bytes" "strings" "github.com/freeconf/yang/meta" "github.com/freeconf/yang/val" ) type Path struct { meta meta.Definition key []val.Value parent *Path } func NewRootPath(m meta.Definition) *Path { return &Path{meta: m} } func NewListItemPath(parent *Path, m *meta.List, key []val.Value) *Path { return &Path{parent: parent, meta: m, key: key} } func (path *Path) SetKey(key []val.Value) *Path { return &Path{parent: path.parent, meta: path.meta, key: key} } func NewContainerPath(parent *Path, m meta.HasDefinitions) *Path { return &Path{parent: parent, meta: m} } func (path *Path) Parent() *Path { return path.parent } func (path *Path) MetaParent() meta.Path { if path.parent == nil { // subtle difference returning nil and interface reference to nil struct. // by rights in go, all callers should check for interface check for nil and nil interface // so this hack some-what contributes to the bad practice of not doing so. return nil } return path.parent } func (path *Path) Meta() meta.Definition { return path.meta } func (path *Path) Key() []val.Value { return path.key } func (seg *Path) StringNoModule() string { return seg.str(false) } func (seg *Path) String() string { return seg.str(true) } func (seg *Path) str(showModule bool) string { l := seg.Len() if !showModule { l } strs := make([]string, l) p := seg var b bytes.Buffer for i := l - 1; i >= 0; i b.Reset() p.toBuffer(&b) strs[i] = b.String() p = p.parent } return strings.Join(strs, "/") } func (seg *Path) toBuffer(b *bytes.Buffer) { if seg.meta == nil { return } if b.Len() > 0 { b.WriteRune('/') } b.WriteString(seg.meta.Ident()) if len(seg.key) > 0 { b.WriteRune('=') for i, k := range seg.key { if i != 0 { b.WriteRune(',') } b.WriteString(k.String()) } } } func (a *Path) EqualNoKey(b *Path) bool { if a.Len() != b.Len() { return false } sa := a sb := b // work up as comparing children are most likely to lead to differences faster for sa != nil { if !sa.equalSegment(sb, false) { return false } sa = sa.parent sb = sb.parent } return true } func (a *Path) Equal(b *Path) bool { if a.Len() != b.Len() { return false } sa := a sb := b // work up as comparing children are most likely to lead to differences faster for sa != nil { if !sa.equalSegment(sb, true) { return false } sa = sa.parent sb = sb.parent } return true } func (path *Path) Len() (len int) { p := path for p != nil { len++ p = p.parent } return } func (a *Path) equalSegment(b *Path, compareKey bool) bool { if a.meta == nil { if b.meta != nil { return false } if a.meta.Ident() != b.meta.Ident() { return false } } if compareKey { if len(a.key) != len(b.key) { return false } for i, k := range a.key { if !val.Equal(k, b.key[i]) { return false } } } return true } func (path *Path) Segments() []*Path { segs := make([]*Path, path.Len()) p := path for i := len(segs) - 1; i >= 0; i segs[i] = p p = p.parent } return segs }
<?php namespace app\components; use Yii; use app\models\Auth; use app\models\User; use yii\authclient\ClientInterface; use yii\helpers\ArrayHelper; /** * AuthHandler handles successful authentication via Yii auth component */ class AuthHandler { /** * @var ClientInterface */ private $client; /** * AuthHandler constructor. * @param ClientInterface $client */ public function __construct(ClientInterface $client) { $this->client = $client; } /** * Handles by the $client */ public function handle() { $attributes = $this->client->getUserAttributes(); $email = ArrayHelper::getValue($attributes, 'email'); $id = ArrayHelper::getValue($attributes, 'id'); $nickname = ArrayHelper::getValue($attributes, 'login'); $fullname = ArrayHelper::getValue($attributes, 'name'); if ($this->client->getName() == 'twitter') { $nickname = ArrayHelper::getValue($attributes, 'screen_name'); } if ($this->client->getName() == 'facebook') { $nickname = ArrayHelper::getValue($attributes, 'id'); } /** @var Auth $auth */ $auth = Auth::find()->where([ 'source' => $this->client->getId(), 'source_id' => $id, ])->one(); if (Yii::$app->user->isGuest) { if ($auth) { // login /** @var User $user */ $user = $auth->user; $this->updateUserInfo($user); Yii::$app->user->login($user, Yii::$app->params['user.rememberMeDuration']); } else { // signup if ($email !== null && User::find()->where(['email' => $email])->exists()) { Yii::$app->getSession()->setFlash('error', [ Yii::t('app', "User with the same email as in {client} account already exists but isn't linked to it. Login using email first to link it.", ['client' => $this->client->getTitle()]), ]); } else { $user = new User(); $user->username = $nickname; $user->fullname = $fullname; $user->password = \Yii::$app->security-><API key>(6); if ($this->client->getName() == 'twitter') { $user->twitter = $nickname; } if ($this->client->getName() == 'facebook') { $user->facebook = $nickname; $user->email = $email; } if ($this->client->getName() == 'github') { $user->github = $nickname; $user->email = $email; } $user->generateAuthKey(); $user-><API key>(); $transaction = User::getDb()->beginTransaction(); if ($user->save()) { $auth = new Auth([ 'user_id' => $user->id, 'source' => $this->client->getId(), 'source_id' => (string)$id, ]); if ($auth->save()) { $transaction->commit(); Yii::$app->user->login($user, Yii::$app->params['user.rememberMeDuration']); } else { Yii::$app->getSession()->setFlash('error', [ Yii::t('app', 'Unable to save {client} account: {errors}', [ 'client' => $this->client->getTitle(), 'errors' => json_encode($auth->getErrors()), ]), ]); } } else { Yii::$app->getSession()->setFlash('error', [ Yii::t('app', 'Unable to save user: {errors}', [ 'client' => $this->client->getTitle(), 'errors' => json_encode($user->getErrors(), <API key>), ]), ]); } } } } else { // user already logged in if (!$auth) { // add auth provider $auth = new Auth([ 'user_id' => Yii::$app->user->id, 'source' => $this->client->getId(), 'source_id' => (string)$attributes['id'], ]); if ($auth->save()) { /** @var User $user */ $user = $auth->user; $this->updateUserInfo($user); Yii::$app->getSession()->setFlash('success', [ Yii::t('app', 'Linked {client} account.', [ 'client' => $this->client->getTitle() ]), ]); } else { Yii::$app->getSession()->setFlash('error', [ Yii::t('app', 'Unable to link {client} account: {errors}', [ 'client' => $this->client->getTitle(), 'errors' => json_encode($auth->getErrors()), ]), ]); } } else { // there's existing auth if ($auth->user_id == Yii::$app->user->id) { $transaction = Auth::getDb()->beginTransaction(); if ($auth->delete()) { $user = $auth->user; $user->{$this->client->getId()} = null; if ($user->save()) { $transaction->commit(); Yii::$app->getSession()->setFlash('success', [ Yii::t('app', 'Social network {client} has been successfully disabled.', ['client' => $this->client->getTitle()]), ]); } } } else { Yii::$app->getSession()->setFlash('error', [ Yii::t('app', 'Unable to link {client} account. There is another user using it.', ['client' => $this->client->getTitle()]), ]); } } } } /** * @param User $user */ private function updateUserInfo(User $user) { $attributes = $this->client->getUserAttributes(); if ($this->client->getName() == 'github') { $user->github = ArrayHelper::getValue($attributes, 'login'); } if ($this->client->getName() == 'twitter') { $user-><TwitterConsumerkey>::getValue($attributes, 'screen_name'); } if ($this->client->getName() == 'facebook') { $user->facebook = ArrayHelper::getValue($attributes, 'id'); } if (!$user->fullname) { $user->fullname = ArrayHelper::getValue($attributes, 'name'); } $user->save(); } }
#ifndef <API key> #define <API key> #include "base/basictypes.h" #include "ppapi/c/pp_instance.h" namespace content { // This interface provides functions for querying instance state for resource // host implementations. It allows us to mock out some of these interactions // for testing, as well as limit the dependencies on the webkit layer. class <API key> { public: virtual ~<API key>() {} // Returns true if the given instance is valid for the host. virtual bool IsValidInstance(PP_Instance instance) = 0; // Returns true if the given instance is considered to be currently // processing a user gesture or the plugin module has the "override user // gesture" flag set (in which case it can always do things normally // restricted by user gestures). Returns false if the instance is invalid or // if there is no current user gesture. virtual bool HasUserGesture(PP_Instance instance) = 0; }; } // namespace content #endif // <API key>
<?php defined('SYSPATH') or die('No direct script access.'); class Kohana_HTML { /** * @var array preferred order of attributes */ public static $attribute_order = array ( 'action', 'method', 'type', 'id', 'name', 'value', 'href', 'src', 'width', 'height', 'cols', 'rows', 'size', 'maxlength', 'rel', 'media', 'accept-charset', 'accept', 'tabindex', 'accesskey', 'alt', 'title', 'class', 'style', 'selected', 'checked', 'readonly', 'disabled', ); /** * @var boolean automatically target external URLs to a new window? */ public static $windowed_urls = FALSE; /** * Convert special characters to HTML entities. All untrusted content * should be passed through this method to prevent XSS injections. * * echo HTML::chars($username); * * @param string string to convert * @param boolean encode existing entities * @return string */ public static function chars($value, $double_encode = TRUE) { return htmlspecialchars( (string) $value, ENT_QUOTES, Kohana::$charset, $double_encode); } /** * Convert all applicable characters to HTML entities. All characters * that cannot be represented in HTML with the current character set * will be converted to entities. * * echo HTML::entities($username); * * @param string string to convert * @param boolean encode existing entities * @return string */ public static function entities($value, $double_encode = TRUE) { return htmlentities( (string) $value, ENT_QUOTES, Kohana::$charset, $double_encode); } /** * Create HTML link anchors. Note that the title is not escaped, to allow * HTML elements within links (images, etc). * * echo HTML::anchor('/user/profile', 'My Profile'); * * @param string URL or URI string * @param string link text * @param array HTML anchor attributes * @param mixed protocol to pass to URL::base() * @param boolean include the index page * @return string * @uses URL::base * @uses URL::site * @uses HTML::attributes */ public static function anchor($uri, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = FALSE) { if ($title === NULL) { // Use the URI as the title $title = $uri; } if ($uri === '') { // Only use the base URL $uri = URL::base($protocol, $index); } else { if (strpos($uri, '://') !== FALSE) { if (HTML::$windowed_urls === TRUE AND empty($attributes['target'])) { // Make the link open in a new window $attributes['target'] = '_blank'; } } elseif ($uri[0] !== ' { // Make the URI absolute for non-id anchors $uri = URL::site($uri, $protocol, $index); } } // Add the sanitized link to the attributes $attributes['href'] = $uri; return '<a'.HTML::attributes($attributes).'>'.$title.'</a>'; } /** * Creates an HTML anchor to a file. Note that the title is not escaped, * to allow HTML elements within links (images, etc). * * echo HTML::file_anchor('media/doc/user_guide.pdf', 'User Guide'); * * @param string name of file to link to * @param string link text * @param array HTML anchor attributes * @param mixed protocol to pass to URL::base() * @param boolean include the index page * @return string * @uses URL::base * @uses HTML::attributes */ public static function file_anchor($file, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = FALSE) { if ($title === NULL) { // Use the file name as the title $title = basename($file); } // Add the file link to the attributes $attributes['href'] = URL::base($protocol, $index).$file; return '<a'.HTML::attributes($attributes).'>'.$title.'</a>'; } /** * Generates an obfuscated version of a string. Text passed through this * method is less likely to be read by web crawlers and robots, which can * be helpful for spam prevention, but can prevent legitimate robots from * reading your content. * * echo HTML::obfuscate($text); * * @param string string to obfuscate * @return string * @since 3.0.3 */ public static function obfuscate($string) { $safe = ''; foreach (str_split($string) as $letter) { switch (rand(1, 3)) { // HTML entity code case 1: $safe .= '&#'.ord($letter).';'; break; // Hex character code case 2: $safe .= '&#x'.dechex(ord($letter)).';'; break; // Raw (no) encoding case 3: $safe .= $letter; } } return $safe; } /** * Generates an obfuscated version of an email address. Helps prevent spam * robots from finding email addresses. * * echo HTML::email($address); * * @param string email address * @return string * @uses HTML::obfuscate */ public static function email($email) { // Make sure the at sign is always obfuscated return str_replace('@', '&#64;', HTML::obfuscate($email)); } /** * Creates an email (mailto:) anchor. Note that the title is not escaped, * to allow HTML elements within links (images, etc). * * echo HTML::mailto($address); * * @param string email address to send to * @param string link text * @param array HTML anchor attributes * @return string * @uses HTML::email * @uses HTML::attributes */ public static function mailto($email, $title = NULL, array $attributes = NULL) { // Obfuscate email address $email = HTML::email($email); if ($title === NULL) { // Use the email address as the title $title = $email; } return '<a href="&#109;&#097;&#105;&#108;&#116;&#111;&#058;'.$email.'"'.HTML::attributes($attributes).'>'.$title.'</a>'; } /** * Creates a style sheet link element. * * echo HTML::style('media/css/screen.css'); * * @param string file name * @param array default attributes * @param mixed protocol to pass to URL::base() * @param boolean include the index page * @return string * @uses URL::base * @uses HTML::attributes */ public static function style($file, array $attributes = NULL, $protocol = NULL, $index = FALSE) { if (strpos($file, ': { // Add the base URL $file = URL::base($protocol, $index).$file; } // Set the stylesheet link $attributes['href'] = $file; // Set the stylesheet rel $attributes['rel'] = 'stylesheet'; // Set the stylesheet type $attributes['type'] = 'text/css'; return '<link'.HTML::attributes($attributes).' />'; } /** * Creates a script link. * * echo HTML::script('media/js/jquery.min.js'); * * @param string file name * @param array default attributes * @param mixed protocol to pass to URL::base() * @param boolean include the index page * @return string * @uses URL::base * @uses HTML::attributes */ public static function script($file, array $attributes = NULL, $protocol = NULL, $index = FALSE) { if (strpos($file, ': { // Add the base URL $file = URL::base($protocol, $index).$file; } // Set the script link $attributes['src'] = $file; // Set the script type $attributes['type'] = 'text/javascript'; return '<script'.HTML::attributes($attributes).'></script>'; } /** * Creates a image link. * * echo HTML::image('media/img/logo.png', array('alt' => 'My Company')); * * @param string file name * @param array default attributes * @param mixed protocol to pass to URL::base() * @param boolean include the index page * @return string * @uses URL::base * @uses HTML::attributes */ public static function image($file, array $attributes = NULL, $protocol = NULL, $index = FALSE) { if (strpos($file, ': { // Add the base URL $file = URL::base($protocol, $index).$file; } // Add the image link $attributes['src'] = $file; return '<img'.HTML::attributes($attributes).' />'; } /** * Compiles an array of HTML attributes into an attribute string. * Attributes will be sorted using HTML::$attribute_order for consistency. * * echo '<div'.HTML::attributes($attrs).'>'.$content.'</div>'; * * @param array attribute list * @return string */ public static function attributes(array $attributes = NULL) { if (empty($attributes)) return ''; $sorted = array(); foreach (HTML::$attribute_order as $key) { if (isset($attributes[$key])) { // Add the attribute to the sorted list $sorted[$key] = $attributes[$key]; } } // Combine the sorted attributes $attributes = $sorted + $attributes; $compiled = ''; foreach ($attributes as $key => $value) { if ($value === NULL) { // Skip attributes that have NULL values continue; } if (is_int($key)) { // Assume non-associative keys are mirrored attributes $key = $value; } // Add the attribute value $compiled .= ' '.$key.'="'.HTML::chars($value).'"'; } return $compiled; } } // End html
<?php /** * Adminhtml paypal settlement reports grid block * * @category Mage * @package Mage_Paypal * @author Magento Core Team <core@magentocommerce.com> */ class <API key> extends <API key> { /** * Prepare grid container, add additional buttons */ public function __construct() { $this->_blockGroup = 'paypal'; $this->_controller = '<API key>'; $this->_headerText = Mage::helper('paypal')->__('PayPal Settlement Reports'); parent::__construct(); $this->_removeButton('add'); $message = Mage::helper('paypal')->__('Connecting to PayPal SFTP server to fetch new reports. Are you sure you want to proceed?'); $this->_addButton('fetch', array( 'label' => Mage::helper('paypal')->__('Fetch Updates'), 'onclick' => "confirmSetLocation('{$message}', '{$this->getUrl('*/*/fetch')}')", 'class' => 'task' )); } }
#include <linux/err.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/rtc.h> #include <linux/spinlock.h> #include <linux/types.h> #include <linux/log2.h> #include <asm/div64.h> #include <asm/io.h> #include <asm/uaccess.h> MODULE_AUTHOR("Yoichi Yuasa <yuasa@linux-mips.org>"); MODULE_DESCRIPTION("NEC VR4100 series RTC driver"); MODULE_LICENSE("GPL v2"); /* RTC 1 registers */ #define ETIMELREG 0x00 #define ETIMEMREG 0x02 #define ETIMEHREG 0x04 /* RFU */ #define ECMPLREG 0x08 #define ECMPMREG 0x0a #define ECMPHREG 0x0c /* RFU */ #define RTCL1LREG 0x10 #define RTCL1HREG 0x12 #define RTCL1CNTLREG 0x14 #define RTCL1CNTHREG 0x16 #define RTCL2LREG 0x18 #define RTCL2HREG 0x1a #define RTCL2CNTLREG 0x1c #define RTCL2CNTHREG 0x1e /* RTC 2 registers */ #define TCLKLREG 0x00 #define TCLKHREG 0x02 #define TCLKCNTLREG 0x04 #define TCLKCNTHREG 0x06 /* RFU */ #define RTCINTREG 0x1e #define TCLOCK_INT 0x08 #define RTCLONG2_INT 0x04 #define RTCLONG1_INT 0x02 #define ELAPSEDTIME_INT 0x01 #define RTC_FREQUENCY 32768 #define MAX_PERIODIC_RATE 6553 static void __iomem *rtc1_base; static void __iomem *rtc2_base; #define rtc1_read(offset) readw(rtc1_base + (offset)) #define rtc1_write(offset, value) writew((value), rtc1_base + (offset)) #define rtc2_read(offset) readw(rtc2_base + (offset)) #define rtc2_write(offset, value) writew((value), rtc2_base + (offset)) static unsigned long epoch = 1970; /* Jan 1 1970 00:00:00 */ static DEFINE_SPINLOCK(rtc_lock); static char rtc_name[] = "RTC"; static unsigned long periodic_count; static unsigned int alarm_enabled; static int aie_irq; static int pie_irq; static inline unsigned long read_elapsed_second(void) { unsigned long first_low, first_mid, first_high; unsigned long second_low, second_mid, second_high; do { first_low = rtc1_read(ETIMELREG); first_mid = rtc1_read(ETIMEMREG); first_high = rtc1_read(ETIMEHREG); second_low = rtc1_read(ETIMELREG); second_mid = rtc1_read(ETIMEMREG); second_high = rtc1_read(ETIMEHREG); } while (first_low != second_low || first_mid != second_mid || first_high != second_high); return (first_high << 17) | (first_mid << 1) | (first_low >> 15); } static inline void <API key>(unsigned long sec) { spin_lock_irq(&rtc_lock); rtc1_write(ETIMELREG, (uint16_t)(sec << 15)); rtc1_write(ETIMEMREG, (uint16_t)(sec >> 1)); rtc1_write(ETIMEHREG, (uint16_t)(sec >> 17)); spin_unlock_irq(&rtc_lock); } static void vr41xx_rtc_release(struct device *dev) { spin_lock_irq(&rtc_lock); rtc1_write(ECMPLREG, 0); rtc1_write(ECMPMREG, 0); rtc1_write(ECMPHREG, 0); rtc1_write(RTCL1LREG, 0); rtc1_write(RTCL1HREG, 0); spin_unlock_irq(&rtc_lock); disable_irq(aie_irq); disable_irq(pie_irq); } static int <API key>(struct device *dev, struct rtc_time *time) { unsigned long epoch_sec, elapsed_sec; epoch_sec = mktime(epoch, 1, 1, 0, 0, 0); elapsed_sec = read_elapsed_second(); rtc_time_to_tm(epoch_sec + elapsed_sec, time); return 0; } static int vr41xx_rtc_set_time(struct device *dev, struct rtc_time *time) { unsigned long epoch_sec, current_sec; epoch_sec = mktime(epoch, 1, 1, 0, 0, 0); current_sec = mktime(time->tm_year + 1900, time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec); <API key>(current_sec - epoch_sec); return 0; } static int <API key>(struct device *dev, struct rtc_wkalrm *wkalrm) { unsigned long low, mid, high; struct rtc_time *time = &wkalrm->time; spin_lock_irq(&rtc_lock); low = rtc1_read(ECMPLREG); mid = rtc1_read(ECMPMREG); high = rtc1_read(ECMPHREG); wkalrm->enabled = alarm_enabled; spin_unlock_irq(&rtc_lock); rtc_time_to_tm((high << 17) | (mid << 1) | (low >> 15), time); return 0; } static int <API key>(struct device *dev, struct rtc_wkalrm *wkalrm) { unsigned long alarm_sec; struct rtc_time *time = &wkalrm->time; alarm_sec = mktime(time->tm_year + 1900, time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec); spin_lock_irq(&rtc_lock); if (alarm_enabled) disable_irq(aie_irq); rtc1_write(ECMPLREG, (uint16_t)(alarm_sec << 15)); rtc1_write(ECMPMREG, (uint16_t)(alarm_sec >> 1)); rtc1_write(ECMPHREG, (uint16_t)(alarm_sec >> 17)); if (wkalrm->enabled) enable_irq(aie_irq); alarm_enabled = wkalrm->enabled; spin_unlock_irq(&rtc_lock); return 0; } static int <API key>(struct device *dev, int freq) { u64 count; if (!is_power_of_2(freq)) return -EINVAL; count = RTC_FREQUENCY; do_div(count, freq); spin_lock_irq(&rtc_lock); periodic_count = count; rtc1_write(RTCL1LREG, periodic_count); rtc1_write(RTCL1HREG, periodic_count >> 16); spin_unlock_irq(&rtc_lock); return 0; } static int <API key>(struct device *dev, int enabled) { if (enabled) enable_irq(pie_irq); else disable_irq(pie_irq); return 0; } static int vr41xx_rtc_ioctl(struct device *dev, unsigned int cmd, unsigned long arg) { switch (cmd) { case RTC_AIE_ON: spin_lock_irq(&rtc_lock); if (!alarm_enabled) { enable_irq(aie_irq); alarm_enabled = 1; } spin_unlock_irq(&rtc_lock); break; case RTC_AIE_OFF: spin_lock_irq(&rtc_lock); if (alarm_enabled) { disable_irq(aie_irq); alarm_enabled = 0; } spin_unlock_irq(&rtc_lock); break; case RTC_EPOCH_READ: return put_user(epoch, (unsigned long __user *)arg); case RTC_EPOCH_SET: /* Doesn't support before 1900 */ if (arg < 1900) return -EINVAL; epoch = arg; break; default: return -ENOIOCTLCMD; } return 0; } static irqreturn_t <API key>(int irq, void *dev_id) { struct platform_device *pdev = (struct platform_device *)dev_id; struct rtc_device *rtc = <API key>(pdev); rtc2_write(RTCINTREG, ELAPSEDTIME_INT); rtc_update_irq(rtc, 1, RTC_AF); return IRQ_HANDLED; } static irqreturn_t rtclong1_interrupt(int irq, void *dev_id) { struct platform_device *pdev = (struct platform_device *)dev_id; struct rtc_device *rtc = <API key>(pdev); unsigned long count = periodic_count; rtc2_write(RTCINTREG, RTCLONG1_INT); rtc1_write(RTCL1LREG, count); rtc1_write(RTCL1HREG, count >> 16); rtc_update_irq(rtc, 1, RTC_PF); return IRQ_HANDLED; } static const struct rtc_class_ops vr41xx_rtc_ops = { .release = vr41xx_rtc_release, .ioctl = vr41xx_rtc_ioctl, .read_time = <API key>, .set_time = vr41xx_rtc_set_time, .read_alarm = <API key>, .set_alarm = <API key>, .irq_set_freq = <API key>, .irq_set_state = <API key>, }; static int __devinit rtc_probe(struct platform_device *pdev) { struct resource *res; struct rtc_device *rtc; int retval; if (pdev->num_resources != 4) return -EBUSY; res = <API key>(pdev, IORESOURCE_MEM, 0); if (!res) return -EBUSY; rtc1_base = ioremap(res->start, res->end - res->start + 1); if (!rtc1_base) return -EBUSY; res = <API key>(pdev, IORESOURCE_MEM, 1); if (!res) { retval = -EBUSY; goto err_rtc1_iounmap; } rtc2_base = ioremap(res->start, res->end - res->start + 1); if (!rtc2_base) { retval = -EBUSY; goto err_rtc1_iounmap; } rtc = rtc_device_register(rtc_name, &pdev->dev, &vr41xx_rtc_ops, THIS_MODULE); if (IS_ERR(rtc)) { retval = PTR_ERR(rtc); goto err_iounmap_all; } rtc->max_user_freq = MAX_PERIODIC_RATE; spin_lock_irq(&rtc_lock); rtc1_write(ECMPLREG, 0); rtc1_write(ECMPMREG, 0); rtc1_write(ECMPHREG, 0); rtc1_write(RTCL1LREG, 0); rtc1_write(RTCL1HREG, 0); spin_unlock_irq(&rtc_lock); aie_irq = platform_get_irq(pdev, 0); if (aie_irq <= 0) { retval = -EBUSY; goto <API key>; } retval = request_irq(aie_irq, <API key>, IRQF_DISABLED, "elapsed_time", pdev); if (retval < 0) goto <API key>; pie_irq = platform_get_irq(pdev, 1); if (pie_irq <= 0) goto err_free_irq; retval = request_irq(pie_irq, rtclong1_interrupt, IRQF_DISABLED, "rtclong1", pdev); if (retval < 0) goto err_free_irq; <API key>(pdev, rtc); disable_irq(aie_irq); disable_irq(pie_irq); printk(KERN_INFO "rtc: Real Time Clock of NEC VR4100 series\n"); return 0; err_free_irq: free_irq(aie_irq, pdev); <API key>: <API key>(rtc); err_iounmap_all: iounmap(rtc2_base); rtc2_base = NULL; err_rtc1_iounmap: iounmap(rtc1_base); rtc1_base = NULL; return retval; } static int __devexit rtc_remove(struct platform_device *pdev) { struct rtc_device *rtc; rtc = <API key>(pdev); if (rtc) <API key>(rtc); <API key>(pdev, NULL); free_irq(aie_irq, pdev); free_irq(pie_irq, pdev); if (rtc1_base) iounmap(rtc1_base); if (rtc2_base) iounmap(rtc2_base); return 0; } /* work with hotplug and coldplug */ MODULE_ALIAS("platform:RTC"); static struct platform_driver rtc_platform_driver = { .probe = rtc_probe, .remove = __devexit_p(rtc_remove), .driver = { .name = rtc_name, .owner = THIS_MODULE, }, }; static int __init vr41xx_rtc_init(void) { return <API key>(&rtc_platform_driver); } static void __exit vr41xx_rtc_exit(void) { <API key>(&rtc_platform_driver); } module_init(vr41xx_rtc_init); module_exit(vr41xx_rtc_exit);
class <API key> < ActiveRecord::Migration[5.1] def up execute "ALTER TABLE batch_uploads ALTER COLUMN created_at SET DEFAULT CURRENT_TIMESTAMP" end def down execute "ALTER TABLE batch_uploads ALTER COLUMN created_at SET DEFAULT CURRENT_TIMESTAMP '2010-08-31 04:17:31.209032'" end end
import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore from pyqtgraph.parametertree import Parameter, ParameterTree from pyqtgraph.parametertree import types as pTypes import pyqtgraph.configfile import numpy as np import user import collections import sys, os class RelativityGUI(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.animations = [] self.animTimer = QtCore.QTimer() self.animTimer.timeout.connect(self.stepAnimation) self.animTime = 0 self.animDt = .016 self.lastAnimTime = 0 self.setupGUI() self.objectGroup = ObjectGroupParam() self.params = Parameter.create(name='params', type='group', children=[ dict(name='Load Preset..', type='list', values=[]), #dict(name='Unit System', type='list', values=['', 'MKS']), dict(name='Duration', type='float', value=10.0, step=0.1, limits=[0.1, None]), dict(name='Reference Frame', type='list', values=[]), dict(name='Animate', type='bool', value=True), dict(name='Animation Speed', type='float', value=1.0, dec=True, step=0.1, limits=[0.0001, None]), dict(name='Recalculate Worldlines', type='action'), dict(name='Save', type='action'), dict(name='Load', type='action'), self.objectGroup, ]) self.tree.setParameters(self.params, showTop=False) self.params.param('Recalculate Worldlines').sigActivated.connect(self.recalculate) self.params.param('Save').sigActivated.connect(self.save) self.params.param('Load').sigActivated.connect(self.load) self.params.param('Load Preset..').sigValueChanged.connect(self.loadPreset) self.params.sigTreeStateChanged.connect(self.treeChanged) ## read list of preset configs presetDir = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'presets') if os.path.exists(presetDir): presets = [os.path.splitext(p)[0] for p in os.listdir(presetDir)] self.params.param('Load Preset..').setLimits(['']+presets) def setupGUI(self): self.layout = QtGui.QVBoxLayout() self.layout.setContentsMargins(0,0,0,0) self.setLayout(self.layout) self.splitter = QtGui.QSplitter() self.splitter.setOrientation(QtCore.Qt.Horizontal) self.layout.addWidget(self.splitter) self.tree = ParameterTree(showHeader=False) self.splitter.addWidget(self.tree) self.splitter2 = QtGui.QSplitter() self.splitter2.setOrientation(QtCore.Qt.Vertical) self.splitter.addWidget(self.splitter2) self.worldlinePlots = pg.<API key>() self.splitter2.addWidget(self.worldlinePlots) self.animationPlots = pg.<API key>() self.splitter2.addWidget(self.animationPlots) self.splitter2.setSizes([int(self.height()*0.8), int(self.height()*0.2)]) self.inertWorldlinePlot = self.worldlinePlots.addPlot() self.refWorldlinePlot = self.worldlinePlots.addPlot() self.inertAnimationPlot = self.animationPlots.addPlot() self.inertAnimationPlot.setAspectLocked(1) self.refAnimationPlot = self.animationPlots.addPlot() self.refAnimationPlot.setAspectLocked(1) self.inertAnimationPlot.setXLink(self.inertWorldlinePlot) self.refAnimationPlot.setXLink(self.refWorldlinePlot) def recalculate(self): ## build 2 sets of clocks clocks1 = collections.OrderedDict() clocks2 = collections.OrderedDict() for cl in self.params.param('Objects'): clocks1.update(cl.buildClocks()) clocks2.update(cl.buildClocks()) ## Inertial simulation dt = self.animDt * self.params['Animation Speed'] sim1 = Simulation(clocks1, ref=None, duration=self.params['Duration'], dt=dt) sim1.run() sim1.plot(self.inertWorldlinePlot) self.inertWorldlinePlot.autoRange(padding=0.1) ## reference simulation ref = self.params['Reference Frame'] dur = clocks1[ref].refData['pt'][-1] ## decide how long to run the reference simulation sim2 = Simulation(clocks2, ref=clocks2[ref], duration=dur, dt=dt) sim2.run() sim2.plot(self.refWorldlinePlot) self.refWorldlinePlot.autoRange(padding=0.1) ## create animations self.refAnimationPlot.clear() self.inertAnimationPlot.clear() self.animTime = 0 self.animations = [Animation(sim1), Animation(sim2)] self.inertAnimationPlot.addItem(self.animations[0]) self.refAnimationPlot.addItem(self.animations[1]) ## create lines representing all that is visible to a particular reference #self.inertSpaceline = Spaceline(sim1, ref) #self.refSpaceline = Spaceline(sim2) self.inertWorldlinePlot.addItem(self.animations[0].items[ref].spaceline()) self.refWorldlinePlot.addItem(self.animations[1].items[ref].spaceline()) def setAnimation(self, a): if a: self.lastAnimTime = pg.ptime.time() self.animTimer.start(self.animDt*1000) else: self.animTimer.stop() def stepAnimation(self): now = pg.ptime.time() dt = (now-self.lastAnimTime) * self.params['Animation Speed'] self.lastAnimTime = now self.animTime += dt if self.animTime > self.params['Duration']: self.animTime = 0 for a in self.animations: a.restart() for a in self.animations: a.stepTo(self.animTime) def treeChanged(self, *args): clocks = [] for c in self.params.param('Objects'): clocks.extend(c.clockNames()) #for param, change, data in args[1]: #if change == 'childAdded': self.params.param('Reference Frame').setLimits(clocks) self.setAnimation(self.params['Animate']) def save(self): fn = str(pg.QtGui.QFileDialog.getSaveFileName(self, "Save State..", "untitled.cfg", "Config Files (*.cfg)")) if fn == '': return state = self.params.saveState() pg.configfile.writeConfigFile(state, fn) def load(self): fn = str(pg.QtGui.QFileDialog.getOpenFileName(self, "Save State..", "", "Config Files (*.cfg)")) if fn == '': return state = pg.configfile.readConfigFile(fn) self.loadState(state) def loadPreset(self, param, preset): if preset == '': return path = os.path.abspath(os.path.dirname(__file__)) fn = os.path.join(path, 'presets', preset+".cfg") state = pg.configfile.readConfigFile(fn) self.loadState(state) def loadState(self, state): if 'Load Preset..' in state['children']: del state['children']['Load Preset..']['limits'] del state['children']['Load Preset..']['value'] self.params.param('Objects').clearChildren() self.params.restoreState(state, removeChildren=False) self.recalculate() class ObjectGroupParam(pTypes.GroupParameter): def __init__(self): pTypes.GroupParameter.__init__(self, name="Objects", addText="Add New..", addList=['Clock', 'Grid']) def addNew(self, typ): if typ == 'Clock': self.addChild(ClockParam()) elif typ == 'Grid': self.addChild(GridParam()) class ClockParam(pTypes.GroupParameter): def __init__(self, **kwds): defs = dict(name="Clock", autoIncrementName=True, renamable=True, removable=True, children=[ dict(name='Initial Position', type='float', value=0.0, step=0.1), #dict(name='V0', type='float', value=0.0, step=0.1), AccelerationGroup(), dict(name='Rest Mass', type='float', value=1.0, step=0.1, limits=[1e-9, None]), dict(name='Color', type='color', value=(100,100,150)), dict(name='Size', type='float', value=0.5), dict(name='Vertical Position', type='float', value=0.0, step=0.1), ]) #defs.update(kwds) pTypes.GroupParameter.__init__(self, **defs) self.restoreState(kwds, removeChildren=False) def buildClocks(self): x0 = self['Initial Position'] y0 = self['Vertical Position'] color = self['Color'] m = self['Rest Mass'] size = self['Size'] prog = self.param('Acceleration').generate() c = Clock(x0=x0, m0=m, y0=y0, color=color, prog=prog, size=size) return {self.name(): c} def clockNames(self): return [self.name()] pTypes.<API key>('Clock', ClockParam) class GridParam(pTypes.GroupParameter): def __init__(self, **kwds): defs = dict(name="Grid", autoIncrementName=True, renamable=True, removable=True, children=[ dict(name='Number of Clocks', type='int', value=5, limits=[1, None]), dict(name='Spacing', type='float', value=1.0, step=0.1), ClockParam(name='ClockTemplate'), ]) #defs.update(kwds) pTypes.GroupParameter.__init__(self, **defs) self.restoreState(kwds, removeChildren=False) def buildClocks(self): clocks = {} template = self.param('ClockTemplate') spacing = self['Spacing'] for i in range(self['Number of Clocks']): c = template.buildClocks().values()[0] c.x0 += i * spacing clocks[self.name() + '%02d' % i] = c return clocks def clockNames(self): return [self.name() + '%02d' % i for i in range(self['Number of Clocks'])] pTypes.<API key>('Grid', GridParam) class AccelerationGroup(pTypes.GroupParameter): def __init__(self, **kwds): defs = dict(name="Acceleration", addText="Add Command..") pTypes.GroupParameter.__init__(self, **defs) self.restoreState(kwds, removeChildren=False) def addNew(self): nextTime = 0.0 if self.hasChildren(): nextTime = self.children()[-1]['Proper Time'] + 1 self.addChild(Parameter.create(name='Command', autoIncrementName=True, type=None, renamable=True, removable=True, children=[ dict(name='Proper Time', type='float', value=nextTime), dict(name='Acceleration', type='float', value=0.0, step=0.1), ])) def generate(self): prog = [] for cmd in self: prog.append((cmd['Proper Time'], cmd['Acceleration'])) return prog pTypes.<API key>('AccelerationGroup', AccelerationGroup) class Clock(object): nClocks = 0 def __init__(self, x0=0.0, y0=0.0, m0=1.0, v0=0.0, t0=0.0, color=None, prog=None, size=0.5): Clock.nClocks += 1 self.pen = pg.mkPen(color) self.brush = pg.mkBrush(color) self.y0 = y0 self.x0 = x0 self.v0 = v0 self.m0 = m0 self.t0 = t0 self.prog = prog self.size = size def init(self, nPts): ## Keep records of object from inertial frame as well as reference frame self.inertData = np.empty(nPts, dtype=[('x', float), ('t', float), ('v', float), ('pt', float), ('m', float), ('f', float)]) self.refData = np.empty(nPts, dtype=[('x', float), ('t', float), ('v', float), ('pt', float), ('m', float), ('f', float)]) ## Inertial frame variables self.x = self.x0 self.v = self.v0 self.m = self.m0 self.t = 0.0 ## reference clock always starts at 0 self.pt = self.t0 ## proper time starts at t0 ## reference frame variables self.refx = None self.refv = None self.refm = None self.reft = None self.recordFrame(0) def recordFrame(self, i): f = self.force() self.inertData[i] = (self.x, self.t, self.v, self.pt, self.m, f) self.refData[i] = (self.refx, self.reft, self.refv, self.pt, self.refm, f) def force(self, t=None): if len(self.prog) == 0: return 0.0 if t is None: t = self.pt ret = 0.0 for t1,f in self.prog: if t >= t1: ret = f return ret def acceleration(self, t=None): return self.force(t) / self.m0 def accelLimits(self): ## return the proper time values which bound the current acceleration command if len(self.prog) == 0: return -np.inf, np.inf t = self.pt ind = -1 for i, v in enumerate(self.prog): t1,f = v if t >= t1: ind = i if ind == -1: return -np.inf, self.prog[0][0] elif ind == len(self.prog)-1: return self.prog[-1][0], np.inf else: return self.prog[ind][0], self.prog[ind+1][0] def getCurve(self, ref=True): if ref is False: data = self.inertData else: data = self.refData[1:] x = data['x'] y = data['t'] curve = pg.PlotCurveItem(x=x, y=y, pen=self.pen) #x = self.data['x'] - ref.data['x'] #y = self.data['t'] step = 1.0 #mod = self.data['pt'] % step #inds = np.argwhere(abs(mod[1:] - mod[:-1]) > step*0.9) inds = [0] pt = data['pt'] for i in range(1,len(pt)): diff = pt[i] - pt[inds[-1]] if abs(diff) >= step: inds.append(i) inds = np.array(inds) #t = self.data['t'][inds] #x = self.data['x'][inds] pts = [] for i in inds: x = data['x'][i] y = data['t'][i] if i+1 < len(data): dpt = data['pt'][i+1]-data['pt'][i] dt = data['t'][i+1]-data['t'][i] else: dpt = 1 if dpt > 0: c = pg.mkBrush((0,0,0)) else: c = pg.mkBrush((200,200,200)) pts.append({'pos': (x, y), 'brush': c}) points = pg.ScatterPlotItem(pts, pen=self.pen, size=7) return curve, points class Simulation: def __init__(self, clocks, ref, duration, dt): self.clocks = clocks self.ref = ref self.duration = duration self.dt = dt @staticmethod def hypTStep(dt, v0, x0, tau0, g): ## Hyperbolic step. ## If an object has proper acceleration g and starts at position x0 with speed v0 and proper time tau0 ## as seen from an inertial frame, then return the new v, x, tau after time dt has elapsed. if g == 0: return v0, x0 + v0*dt, tau0 + dt * (1. - v0**2)**0.5 v02 = v0**2 g2 = g**2 tinit = v0 / (g * (1 - v02)**0.5) B = (1 + (g2 * (dt+tinit)**2))**0.5 v1 = g * (dt+tinit) / B dtau = (np.arcsinh(g * (dt+tinit)) - np.arcsinh(g * tinit)) / g tau1 = tau0 + dtau x1 = x0 + (1.0 / g) * ( B - 1. / (1.-v02)**0.5 ) return v1, x1, tau1 @staticmethod def tStep(dt, v0, x0, tau0, g): ## Linear step. ## Probably not as accurate as hyperbolic step, but certainly much faster. gamma = (1. - v0**2)**-0.5 dtau = dt / gamma return v0 + dtau * g, x0 + v0*dt, tau0 + dtau @staticmethod def tauStep(dtau, v0, x0, t0, g): ## linear step in proper time of clock. ## If an object has proper acceleration g and starts at position x0 with speed v0 at time t0 ## as seen from an inertial frame, then return the new v, x, t after proper time dtau has elapsed. ## Compute how much t will change given a proper-time step of dtau gamma = (1. - v0**2)**-0.5 if g == 0: dt = dtau * gamma else: v0g = v0 * gamma dt = (np.sinh(dtau * g + np.arcsinh(v0g)) - v0g) / g #return v0 + dtau * g, x0 + v0*dt, t0 + dt v1, x1, t1 = Simulation.hypTStep(dt, v0, x0, t0, g) return v1, x1, t0+dt @staticmethod def hypIntersect(x0r, t0r, vr, x0, t0, v0, g): ## given a reference clock (seen from inertial frame) has rx, rt, and rv, ## and another clock starts at x0, t0, and v0, with acceleration g, ## compute the intersection time of the object clock's hyperbolic path with ## the reference plane. ## I'm sure we can simplify this... if g == 0: ## no acceleration, path is linear (and hyperbola is undefined) #(-t0r + t0 v0 vr - vr x0 + vr x0r)/(-1 + v0 vr) t = (-t0r + t0 *v0 *vr - vr *x0 + vr *x0r)/(-1 + v0 *vr) return t gamma = (1.0-v0**2)**-0.5 sel = (1 if g>0 else 0) + (1 if vr<0 else 0) sel = sel%2 if sel == 0: #(1/(g^2 (-1 + vr^2)))(-g^2 t0r + g gamma vr + g^2 t0 vr^2 - #g gamma v0 vr^2 - g^2 vr x0 + #g^2 vr x0r + \[Sqrt](g^2 vr^2 (1 + gamma^2 (v0 - vr)^2 - vr^2 + #2 g gamma (v0 - vr) (-t0 + t0r + vr (x0 - x0r)) + #g^2 (t0 - t0r + vr (-x0 + x0r))^2))) t = (1./(g**2 *(-1. + vr**2)))*(-g**2 *t0r + g *gamma *vr + g**2 *t0 *vr**2 - g *gamma *v0 *vr**2 - g**2 *vr *x0 + g**2 *vr *x0r + np.sqrt(g**2 *vr**2 *(1. + gamma**2 *(v0 - vr)**2 - vr**2 + 2 *g *gamma *(v0 - vr)* (-t0 + t0r + vr *(x0 - x0r)) + g**2 *(t0 - t0r + vr* (-x0 + x0r))**2))) else: #-(1/(g^2 (-1 + vr^2)))(g^2 t0r - g gamma vr - g^2 t0 vr^2 + #g gamma v0 vr^2 + g^2 vr x0 - #g^2 vr x0r + \[Sqrt](g^2 vr^2 (1 + gamma^2 (v0 - vr)^2 - vr^2 + #2 g gamma (v0 - vr) (-t0 + t0r + vr (x0 - x0r)) + #g^2 (t0 - t0r + vr (-x0 + x0r))^2))) t = -(1./(g**2 *(-1. + vr**2)))*(g**2 *t0r - g *gamma* vr - g**2 *t0 *vr**2 + g *gamma *v0 *vr**2 + g**2* vr* x0 - g**2 *vr *x0r + np.sqrt(g**2* vr**2 *(1. + gamma**2 *(v0 - vr)**2 - vr**2 + 2 *g *gamma *(v0 - vr) *(-t0 + t0r + vr *(x0 - x0r)) + g**2 *(t0 - t0r + vr *(-x0 + x0r))**2))) return t def run(self): nPts = int(self.duration/self.dt)+1 for cl in self.clocks.itervalues(): cl.init(nPts) if self.ref is None: self.runInertial(nPts) else: self.runReference(nPts) def runInertial(self, nPts): clocks = self.clocks dt = self.dt tVals = np.linspace(0, dt*(nPts-1), nPts) for cl in self.clocks.itervalues(): for i in xrange(1,nPts): nextT = tVals[i] while True: tau1, tau2 = cl.accelLimits() x = cl.x v = cl.v tau = cl.pt g = cl.acceleration() v1, x1, tau1 = self.hypTStep(dt, v, x, tau, g) if tau1 > tau2: dtau = tau2-tau cl.v, cl.x, cl.t = self.tauStep(dtau, v, x, cl.t, g) cl.pt = tau2 else: cl.v, cl.x, cl.pt = v1, x1, tau1 cl.t += dt if cl.t >= nextT: cl.refx = cl.x cl.refv = cl.v cl.reft = cl.t cl.recordFrame(i) break def runReference(self, nPts): clocks = self.clocks ref = self.ref dt = self.dt dur = self.duration ## make sure reference clock is not present in the list of clocks--this will be handled separately. clocks = clocks.copy() for k,v in clocks.iteritems(): if v is ref: del clocks[k] break ref.refx = 0 ref.refv = 0 ref.refm = ref.m0 ## These are the set of proper times (in the reference frame) that will be simulated ptVals = np.linspace(ref.pt, ref.pt + dt*(nPts-1), nPts) for i in xrange(1,nPts): ## step reference clock ahead one time step in its proper time nextPt = ptVals[i] ## this is where (when) we want to end up while True: tau1, tau2 = ref.accelLimits() dtau = min(nextPt-ref.pt, tau2-ref.pt) ## do not step past the next command boundary g = ref.acceleration() v, x, t = Simulation.tauStep(dtau, ref.v, ref.x, ref.t, g) ref.pt += dtau ref.v = v ref.x = x ref.t = t ref.reft = ref.pt if ref.pt >= nextPt: break #else: #print "Stepped to", tau2, "instead of", nextPt ref.recordFrame(i) ## determine plane visible to reference clock ## this plane goes through the point ref.x, ref.t and has slope = ref.v ## update all other clocks for cl in clocks.itervalues(): while True: g = cl.acceleration() tau1, tau2 = cl.accelLimits() ##Given current position / speed of clock, determine where it will intersect reference plane #t1 = (ref.v * (cl.x - cl.v * cl.t) + (ref.t - ref.v * ref.x)) / (1. - cl.v) t1 = Simulation.hypIntersect(ref.x, ref.t, ref.v, cl.x, cl.t, cl.v, g) dt1 = t1 - cl.t ## advance clock by correct time step v, x, tau = Simulation.hypTStep(dt1, cl.v, cl.x, cl.pt, g) ## check to see whether we have gone past an acceleration command boundary. ## if so, we must instead advance the clock to the boundary and start again if tau < tau1: dtau = tau1 - cl.pt cl.v, cl.x, cl.t = Simulation.tauStep(dtau, cl.v, cl.x, cl.t, g) cl.pt = tau1-0.000001 continue if tau > tau2: dtau = tau2 - cl.pt cl.v, cl.x, cl.t = Simulation.tauStep(dtau, cl.v, cl.x, cl.t, g) cl.pt = tau2 continue ## Otherwise, record the new values and exit the loop cl.v = v cl.x = x cl.pt = tau cl.t = t1 cl.m = None break ## transform position into reference frame x = cl.x - ref.x t = cl.t - ref.t gamma = (1.0 - ref.v**2) ** -0.5 vg = -ref.v * gamma cl.refx = gamma * (x - ref.v * t) cl.reft = ref.pt # + gamma * (t - ref.v * x) # this term belongs here, but it should always be equal to 0. cl.refv = (cl.v - ref.v) / (1.0 - cl.v * ref.v) cl.refm = None cl.recordFrame(i) t += dt def plot(self, plot): plot.clear() for cl in self.clocks.itervalues(): c, p = cl.getCurve() plot.addItem(c) plot.addItem(p) class Animation(pg.ItemGroup): def __init__(self, sim): pg.ItemGroup.__init__(self) self.sim = sim self.clocks = sim.clocks self.items = {} for name, cl in self.clocks.items(): item = ClockItem(cl) self.addItem(item) self.items[name] = item #self.timer = timer #self.timer.timeout.connect(self.step) #def run(self, run): #if not run: #self.timer.stop() #else: #self.timer.start(self.dt) def restart(self): for cl in self.items.values(): cl.reset() def stepTo(self, t): for i in self.items.values(): i.stepTo(t) class ClockItem(pg.ItemGroup): def __init__(self, clock): pg.ItemGroup.__init__(self) self.size = clock.size self.item = QtGui.<API key>(QtCore.QRectF(0, 0, self.size, self.size)) self.item.translate(-self.size*0.5, -self.size*0.5) self.item.setPen(pg.mkPen(100,100,100)) self.item.setBrush(clock.brush) self.hand = QtGui.QGraphicsLineItem(0, 0, 0, self.size*0.5) self.hand.setPen(pg.mkPen('w')) self.hand.setZValue(10) self.flare = QtGui.<API key>(QtGui.QPolygonF([ QtCore.QPointF(0, -self.size*0.25), QtCore.QPointF(0, self.size*0.25), QtCore.QPointF(self.size*1.5, 0), QtCore.QPointF(0, -self.size*0.25), ])) self.flare.setPen(pg.mkPen('y')) self.flare.setBrush(pg.mkBrush(255,150,0)) self.flare.setZValue(-10) self.addItem(self.hand) self.addItem(self.item) self.addItem(self.flare) self.clock = clock self.i = 1 self._spaceline = None def spaceline(self): if self._spaceline is None: self._spaceline = pg.InfiniteLine() self._spaceline.setPen(self.clock.pen) return self._spaceline def stepTo(self, t): data = self.clock.refData while self.i < len(data)-1 and data['t'][self.i] < t: self.i += 1 while self.i > 1 and data['t'][self.i-1] >= t: self.i -= 1 self.setPos(data['x'][self.i], self.clock.y0) t = data['pt'][self.i] self.hand.setRotation(-0.25 * t * 360.) self.resetTransform() v = data['v'][self.i] gam = (1.0 - v**2)**0.5 self.scale(gam, 1.0) f = data['f'][self.i] self.flare.resetTransform() if f < 0: self.flare.translate(self.size*0.4, 0) else: self.flare.translate(-self.size*0.4, 0) self.flare.scale(-f * (0.5+np.random.random()*0.1), 1.0) if self._spaceline is not None: self._spaceline.setPos(pg.Point(data['x'][self.i], data['t'][self.i])) self._spaceline.setAngle(data['v'][self.i] * 45.) def reset(self): self.i = 1 #class Spaceline(pg.InfiniteLine): #def __init__(self, sim, frame): #self.sim = sim #self.frame = frame #pg.InfiniteLine.__init__(self) #self.setPen(sim.clocks[frame].pen) #def stepTo(self, t): #self.setAngle(0) #pass if __name__ == '__main__': pg.mkQApp() #import pyqtgraph.console #cw = pyqtgraph.console.ConsoleWidget() #cw.show() #cw.catchNextException() win = RelativityGUI() win.setWindowTitle("Relativity!") win.show() win.resize(1100,700) if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() #win.params.param('Objects').restoreState(state, removeChildren=False)
// by DotNetNuke Corporation // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // of the Software. // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion namespace DotNetNuke.Services.Cryptography { public interface <API key> { <summary> simple method that uses basic encryption to safely encode parameters </summary> <param name="message">the text to be encrypted (encoded)</param> <param name="passphrase">the key to perform the encryption</param> <returns>encrypted string</returns> string EncryptParameter(string message, string passphrase); <summary> simple method that uses basic encryption to safely decode parameters </summary> <param name="message">the text to be decrypted (decoded)</param> <param name="passphrase">the key to perform the decryption</param> <returns>decrypted string</returns> string DecryptParameter(string message, string passphrase); <summary> safely encrypt sensitive data </summary> <param name="message">the text to be encrypted</param> <param name="passphrase">the key to perform the encryption</param> <returns>encrypted string</returns> string EncryptString(string message, string passphrase); <summary> safely decrypt sensitive data </summary> <param name="message">the text to be decrypted</param> <param name="passphrase">the key to perform the decryption</param> <returns>decrypted string</returns> string DecryptString(string message, string passphrase); } }
<link href="/App_Plugins/Merchello/Common/Css/merchello.css" rel="stylesheet"> <div data-ng-controller="Merchello.Plugins.Reports.ExportOrders"> <umb-panel> <umb-header> <div class="span4"> <div class="<API key>"> <h1 class="umb-headline">Reports - Export Orders</h1> </div> </div> </umb-header> <merchello-panel> <div class="merchello-pane row-fluid"> <div class="well row-fluid col-xs-10 span10"> <p>Export orders between</p> <<API key> filter-start-date="filterStartDate" filter-end-date="filterEndDate" filter-button-text="Export" filter-with-dates="exportOrders(filterStartDate, filterEndDate)"></<API key>> </div> <div class="clear" /> <div class="pager" data-ng-hide="loaded"> <img src="/umbraco/assets/img/loader.gif" /> </div> </div> </merchello-panel> </umb-panel> </div>
CFLAGS += -g -O0 -I../ttbin LDFLAGS += -L../ttbin -lttbin -lcurl -lc -lgcc -lm SRC = ttbincnv.c \ OUTPUT = ttbincnv $(OUTPUT): $(SRC:.c=.o) ../ttbin/libttbin.a @echo Linking $(OUTPUT)... @$(CC) -o $(OUTPUT) $(SRC:.c=.o) $(LDFLAGS) %.o: %.c @echo Compiling $@... @$(CC) -c $(CFLAGS) $< -o $*.o @$(CC) -MM $(CFLAGS) $< > $*.d @mv -f $*.d $*.d.tmp @sed -e 's|.*:|$*.o:|' <$*.d.tmp >$*.d @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | \ sed -e 's/^ *//' -e 's/$$/:/' >> $*.d @rm -f $*.d.tmp clean: @-rm $(OUTPUT) $(SRC:.c=.o) $(SRC:.c=.d) >/dev/null 2>&1 install: $(OUTPUT) -install -m0755 $(OUTPUT) $(PREFIX)/bin -include *.d
#include "opae_osdep.h" #include "opae_spi.h" static int <API key>(struct altera_spi_device *dev, u32 reg, u32 *val) { u64 ctrl = 0; u64 stat = 0; int loops = SPI_MAX_RETRY; ctrl = NIOS_SPI_RD | ((u64)reg << 32); opae_writeq(ctrl, dev->regs + NIOS_SPI_CTRL); stat = opae_readq(dev->regs + NIOS_SPI_STAT); while (!(stat & NIOS_SPI_VALID) && --loops) stat = opae_readq(dev->regs + NIOS_SPI_STAT); *val = stat & NIOS_SPI_READ_DATA; return loops ? 0 : -ETIMEDOUT; } static int <API key>(struct altera_spi_device *dev, u32 reg, u32 value) { u64 ctrl = 0; u64 stat = 0; int loops = SPI_MAX_RETRY; ctrl |= NIOS_SPI_WR | (u64)reg << 32; ctrl |= value & NIOS_SPI_WRITE_DATA; opae_writeq(ctrl, dev->regs + NIOS_SPI_CTRL); stat = opae_readq(dev->regs + NIOS_SPI_STAT); while (!(stat & NIOS_SPI_VALID) && --loops) stat = opae_readq(dev->regs + NIOS_SPI_STAT); return loops ? 0 : -ETIMEDOUT; } static int spi_indirect_write(struct altera_spi_device *dev, u32 reg, u32 value) { u64 ctrl; opae_writeq(value & WRITE_DATA_MASK, dev->regs + SPI_WRITE); ctrl = CTRL_W | (reg >> 2); opae_writeq(ctrl, dev->regs + SPI_CTRL); return 0; } static int spi_indirect_read(struct altera_spi_device *dev, u32 reg, u32 *val) { u64 tmp; u64 ctrl; ctrl = CTRL_R | (reg >> 2); opae_writeq(ctrl, dev->regs + SPI_CTRL); /** * FIXME: Read one more time to avoid HW timing issue. This is * a short term workaround solution, and must be removed once * hardware fixing is done. */ tmp = opae_readq(dev->regs + SPI_READ); *val = (u32)tmp; return 0; } int spi_reg_write(struct altera_spi_device *dev, u32 reg, u32 value) { return dev->reg_write(dev, reg, value); } int spi_reg_read(struct altera_spi_device *dev, u32 reg, u32 *val) { return dev->reg_read(dev, reg, val); } void spi_cs_activate(struct altera_spi_device *dev, unsigned int chip_select) { spi_reg_write(dev, <API key>, 1 << chip_select); spi_reg_write(dev, ALTERA_SPI_CONTROL, <API key>); } void spi_cs_deactivate(struct altera_spi_device *dev) { spi_reg_write(dev, ALTERA_SPI_CONTROL, 0); } static int spi_flush_rx(struct altera_spi_device *dev) { u32 val = 0; int ret; ret = spi_reg_read(dev, ALTERA_SPI_STATUS, &val); if (ret) return ret; if (val & <API key>) { ret = spi_reg_read(dev, ALTERA_SPI_RXDATA, &val); if (ret) return ret; } return 0; } static unsigned int spi_write_bytes(struct altera_spi_device *dev, int count) { unsigned int val = 0; u16 *p16; u32 *p32; if (dev->txbuf) { switch (dev->data_width) { case 1: val = dev->txbuf[count]; break; case 2: p16 = (u16 *)(dev->txbuf + 2*count); val = *p16; if (dev->endian == SPI_BIG_ENDIAN) val = cpu_to_be16(val); break; case 4: p32 = (u32 *)(dev->txbuf + 4*count); val = *p32; break; } } return val; } static void spi_fill_readbuffer(struct altera_spi_device *dev, unsigned int value, int count) { u16 *p16; u32 *p32; if (dev->rxbuf) { switch (dev->data_width) { case 1: dev->rxbuf[count] = value; break; case 2: p16 = (u16 *)(dev->rxbuf + 2*count); if (dev->endian == SPI_BIG_ENDIAN) *p16 = cpu_to_be16((u16)value); else *p16 = (u16)value; break; case 4: p32 = (u32 *)(dev->rxbuf + 4*count); if (dev->endian == SPI_BIG_ENDIAN) *p32 = cpu_to_be32(value); else *p32 = value; break; } } } static int spi_txrx(struct altera_spi_device *dev) { unsigned int count = 0; u32 rxd; unsigned int tx_data; u32 status; int ret; while (count < dev->len) { tx_data = spi_write_bytes(dev, count); spi_reg_write(dev, ALTERA_SPI_TXDATA, tx_data); while (1) { ret = spi_reg_read(dev, ALTERA_SPI_STATUS, &status); if (ret) return -EIO; if (status & <API key>) break; } ret = spi_reg_read(dev, ALTERA_SPI_RXDATA, &rxd); if (ret) return -EIO; spi_fill_readbuffer(dev, rxd, count); count++; } return 0; } int spi_command(struct altera_spi_device *dev, unsigned int chip_select, unsigned int wlen, void *wdata, unsigned int rlen, void *rdata) { if (((wlen > 0) && !wdata) || ((rlen > 0) && !rdata)) { dev_err(dev, "error on spi command checking\n"); return -EINVAL; } wlen = wlen / dev->data_width; rlen = rlen / dev->data_width; /* flush rx buffer */ spi_flush_rx(dev); spi_cs_activate(dev, chip_select); if (wlen) { dev->txbuf = wdata; dev->rxbuf = rdata; dev->len = wlen; spi_txrx(dev); } if (rlen) { dev->rxbuf = rdata; dev->txbuf = NULL; dev->len = rlen; spi_txrx(dev); } spi_cs_deactivate(dev); return 0; } int spi_write(struct altera_spi_device *dev, unsigned int chip_select, unsigned int wlen, void *wdata) { return spi_command(dev, chip_select, wlen, wdata, 0, NULL); } int spi_read(struct altera_spi_device *dev, unsigned int chip_select, unsigned int rlen, void *rdata) { return spi_command(dev, chip_select, 0, NULL, rlen, rdata); } struct altera_spi_device *altera_spi_alloc(void *base, int type) { struct altera_spi_device *spi_dev = opae_malloc(sizeof(struct altera_spi_device)); if (!spi_dev) return NULL; spi_dev->regs = base; switch (type) { case TYPE_SPI: spi_dev->reg_read = spi_indirect_read; spi_dev->reg_write = spi_indirect_write; break; case TYPE_NIOS_SPI: spi_dev->reg_read = <API key>; spi_dev->reg_write = <API key>; break; default: dev_err(dev, "%s: invalid SPI type\n", __func__); goto error; } return spi_dev; error: altera_spi_release(spi_dev); return NULL; } void altera_spi_init(struct altera_spi_device *spi_dev) { spi_dev->spi_param.info = opae_readq(spi_dev->regs + SPI_CORE_PARAM); spi_dev->data_width = spi_dev->spi_param.data_width / 8; spi_dev->endian = spi_dev->spi_param.endian; spi_dev->num_chipselect = spi_dev->spi_param.num_chipselect; dev_info(spi_dev, "spi param: type=%d, data width:%d, endian:%d, clock_polarity=%d, clock=%dMHz, chips=%d, cpha=%d\n", spi_dev->spi_param.type, spi_dev->data_width, spi_dev->endian, spi_dev->spi_param.clock_polarity, spi_dev->spi_param.clock, spi_dev->num_chipselect, spi_dev->spi_param.clock_phase); if (spi_dev->mutex) pthread_mutex_lock(spi_dev->mutex); /* clear */ spi_reg_write(spi_dev, ALTERA_SPI_CONTROL, 0); spi_reg_write(spi_dev, ALTERA_SPI_STATUS, 0); /* flush rxdata */ spi_flush_rx(spi_dev); if (spi_dev->mutex) <API key>(spi_dev->mutex); } void altera_spi_release(struct altera_spi_device *dev) { if (dev) opae_free(dev); }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:44 ICT 2012 --> <TITLE> <API key>.<API key> (Apache FOP 1.1 API) </TITLE> <META NAME="date" CONTENT="2012-10-16"> <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="<API key>.<API key> (Apache FOP 1.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/fop/layoutmgr/<API key>.<API key>.html" title="class in org.apache.fop.layoutmgr"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/fop/layoutmgr/<API key>.<API key>.html" title="class in org.apache.fop.layoutmgr"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/fop/layoutmgr/<API key>.<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.<API key>.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> <FONT SIZE="-1"> org.apache.fop.layoutmgr</FONT> <BR> Class <API key>.<API key></H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../org/apache/fop/layoutmgr/<API key>.Maker.html" title="class in org.apache.fop.layoutmgr">org.apache.fop.layoutmgr.<API key>.Maker</A> <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.fop.layoutmgr.<API key>.<API key></B> </PRE> <DL> <DT><B>Enclosing class:</B><DD><A HREF="../../../../org/apache/fop/layoutmgr/<API key>.html" title="class in org.apache.fop.layoutmgr"><API key></A></DD> </DL> <HR> <DL> <DT><PRE>public static class <B><API key>.<API key></B><DT>extends <A HREF="../../../../org/apache/fop/layoutmgr/<API key>.Maker.html" title="class in org.apache.fop.layoutmgr"><API key>.Maker</A></DL> </PRE> <P> a layout manager maker <P> <P> <HR> <P> <A NAME="constructor_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../org/apache/fop/layoutmgr/<API key>.<API key>.html#<API key>.<API key>()"><API key>.<API key></A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <A NAME="method_summary"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></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><A HREF="../../../../org/apache/fop/layoutmgr/<API key>.<API key>.html#make(org.apache.fop.fo.FONode, java.util.List)">make</A></B>(<A HREF="../../../../org/apache/fop/fo/FONode.html" title="class in org.apache.fop.fo">FONode</A>&nbsp;node, java.util.List&nbsp;lms)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Create a layout manager.</TD> </TR> </TABLE> &nbsp;<A NAME="<API key>.lang.Object"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="<API key>"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <A NAME="constructor_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="<API key>.<API key>()"></A><H3> <API key>.<API key></H3> <PRE> public <B><API key>.<API key></B>()</PRE> <DL> </DL> <A NAME="method_detail"></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="make(org.apache.fop.fo.FONode, java.util.List)"></A><H3> make</H3> <PRE> public void <B>make</B>(<A HREF="../../../../org/apache/fop/fo/FONode.html" title="class in org.apache.fop.fo">FONode</A>&nbsp;node, java.util.List&nbsp;lms)</PRE> <DL> <DD>Create a layout manager. <P> <DD><DL> <DT><B>Overrides:</B><DD><CODE><A HREF="../../../../org/apache/fop/layoutmgr/<API key>.Maker.html#make(org.apache.fop.fo.FONode, java.util.List)">make</A></CODE> in class <CODE><A HREF="../../../../org/apache/fop/layoutmgr/<API key>.Maker.html" title="class in org.apache.fop.layoutmgr"><API key>.Maker</A></CODE></DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>node</CODE> - the associated FO node<DD><CODE>lms</CODE> - a list of layout managers to which new manager is to be added</DL> </DD> </DL> <HR> <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="<API key>"></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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/<API key>.<API key>.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/fop/layoutmgr/<API key>.<API key>.html" title="class in org.apache.fop.layoutmgr"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/fop/layoutmgr/<API key>.<API key>.html" title="class in org.apache.fop.layoutmgr"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/fop/layoutmgr/<API key>.<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.<API key>.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
require "spec_helper" describe Minidoc do class ValidationsUser < User validates :name, presence: true end describe "#model_name" do it "returns the name of the class" do expect(User.model_name.to_s).to eq "User" end end describe "#to_model" do it "returns itself" do user = User.new expect(user.to_model).to eq user end end describe "#to_key" do it "returns an array of key attributes" do user = User.new user.id = BSON::ObjectId("<API key>") expect(user.to_key).to eq ["<API key>"] end end describe "#to_param" do it "returns a string suitable for use in URLs" do user = User.new user.id = BSON::ObjectId("<API key>") expect(user.to_param).to eq "<API key>" end end describe "#to_partial_path" do it "returns a string which ActionPack could use to look up a partial template" do expect(User.new.to_partial_path).to eq "users/user" end end describe ".<API key>" do it "returns the value of the block when there are no errors" do user = User.create! result = Minidoc.<API key> { User.create!(name: "two") } expect(result.name).to eq "two" end it "returns false when a duplicate key error occurs" do user = User.create! result = Minidoc.<API key> do User.create!(:_id => user.id, name: "two") end expect(result).to eq false end end describe ".new" do it "sets ids before the document is persisted" do user = User.new expect(user.id).to be_a BSON::ObjectId end it "allows you to provide an id" do user = User.new(:_id => BSON::ObjectId("<API key>")) expect(user.id).to eq BSON::ObjectId("<API key>") end end describe "#new_record?" do it "tells you whether the document has been persisted to the database or not" do user = User.new expect(user.new_record?).to eq true user.save expect(user.new_record?).to eq false end end describe "#save" do it "persists the document" do expect { user = User.new user.save }.to change { User.count }.from(0).to(1) end it "doesn't change id when persisted" do user = User.new expect { user.save }.to_not change { user.id } end it "raises Minidoc::DuplicateKey where appropriate" do collection = double expect(User).to receive(:collection).and_return(collection) expect(collection).to receive(:<<).and_raise(Mongo::OperationFailure.new("Duplicate key exception", Minidoc::DuplicateKey::<API key>)) user = User.new expect { user.save }.to raise_error(Minidoc::DuplicateKey) end it "doesn't suppress errors it shouldn't" do collection = double expect(User).to receive(:collection).and_return(collection) expect(collection).to receive(:<<).and_raise(ArgumentError) user = User.new expect { user.save }.to raise_error(ArgumentError) end it "persists changes to the database" do user = User.create(name: "Bryan") expect(user.persisted?).to be true user.name = "Noah" expect(user.name).to eq "Noah" user.save expect(user.reload.name).to eq "Noah" end it "doesn't persist changes when the validations aren't satisfied" do user = ValidationsUser.new expect(user.save).to be false expect(user.new_record?).to be true expect(user.errors[:name]).to eq ["can't be blank"] end it "isn't thrown off when two classes are backed by the same collection" do user = User.create(name: "Bryan", age: 20) user.name = "Noah" expect(user.name).to eq "Noah" user.save user.reload expect(user.name).to eq "Noah" expect(user.age).to eq 20 second_user = SecondUser.find_one(age: 20) expect(user.id).to eq second_user.id second_user.age = 21 expect(second_user.age).to eq 21 second_user.save expect(second_user.reload.age).to eq 21 user.reload expect(user.name).to eq "Noah" expect(user.age).to eq 21 end end describe "#save!" do it "persists the change to the database" do user = User.create!(name: "Bryan") user.name = "Noah" user.save! expect(user.reload.name).to eq "Noah" end it "does not persist the change to the database when a validation is not satisfied" do expect { ValidationsUser.new.save! }.to raise_error(Minidoc::RecordInvalid) end end describe "#valid?" do it "checks that that validations are satisfied" do user = ValidationsUser.new expect(user).to_not be_valid user.name = "Noah" expect(user).to be_valid end end describe "#persisted?" do let(:user) { User.new } it "knows new records are not persisted" do expect(user.persisted?).to eq false end it "knows saved records are persisted" do user.save expect(user.persisted?).to eq true end it "knows deleted records are not persisted" do user.save! user.destroy expect(user.persisted?).to eq false end end describe ".create!" do it "inserts a document into the database" do user = User.create!(name: "Bryan") expect(user.name).to eq "Bryan" expect(user.persisted?).to be true expect(User.count).to eq 1 end it "raises an error when a validation is not satisfied" do expect { ValidationsUser.create! }.to raise_error(Minidoc::RecordInvalid) expect(User.count).to eq 0 end end describe ".create" do it "inserts a document into the database" do user = User.create(name: "Bryan") expect(user.name).to eq "Bryan" expect(User.count).to eq 1 end it "does not insert a document when a validation is not satisfied" do user = ValidationsUser.create expect(user.persisted?).to be false expect(ValidationsUser.count).to eq 0 end end describe "#destroy, #destroyed?" do it "removes the document from the collection, and the document knows it" do user = User.create!(name: "Bryan") expect(user.destroyed?).to eq false user.destroy expect(User.count).to eq 0 expect(user.destroyed?).to eq true end end describe ".delete" do it "removes a document by id" do user = User.create!(name: "Bryan") User.delete(user.id) expect(User.count).to eq 0 expect { user.reload }.to raise_error(Minidoc::<API key>) end end describe "#delete" do it "removes itself from the collection" do user = User.create!(name: "Bryan") user.delete expect(User.count).to eq 0 end end describe "#reload" do it "refreshes the object with any changed data from the underlying database" do user = User.create!(name: "Bryan") expect(user.reload.name).to eq "Bryan" User.collection.update({ :_id => user.id }, name: "Noah") expect(user.name).to eq "Bryan" user.reload expect(user.name).to eq "Noah" end end describe ".set" do it "sets a field on a document with a provided id" do user = User.create!(name: "Bryan") User.set(user.id, name: "Noah") expect(user.name).to eq "Bryan" expect(user.reload.name).to eq "Noah" end it "allows passing an id as a string rather than a BSON::ObjectId" do user = User.create!(name: "Noah") User.set(user.id.to_s, name: "Mike") expect(user.reload.name).to eq "Mike" expect(User.first.name).to eq "Mike" end end describe "#set" do it "changes the field (without needing to call save)" do user = User.create!(name: "Bryan") user.set(name: "Noah") expect(user.name).to eq "Noah" expect(user.reload.name).to eq "Noah" expect(User.first.name).to eq "Noah" end it "allows changing the field, referenced as a string" do user = User.create(name: "Bryan") user.set("name" => "Noah") expect(user.name).to eq "Noah" expect(user.reload.name).to eq "Noah" expect(User.first.name).to eq "Noah" end it "bypasses validations, so be careful" do user = ValidationsUser.create!(name: "Bryan") expect(user).to be_valid user.set(name: nil) user.reload expect(user).to_not be_valid end end describe ".unset" do it "allows removing a field for a document with the provided id" do user = User.create!(name: "Bryan") User.unset(user.id, :name) expect(user.name).to eq "Bryan" expect(user.reload.name).to eq nil expect(User.first.name).to eq nil end it "doesn't mind if the provided id is a string rather than a BSON::ObjectId" do user = User.create!(name: "Bryan") User.unset(user.id.to_s, :name) expect(user.reload.name).to eq nil expect(User.first.name).to eq nil end end describe "#unset" do it "removes a field for a document" do user = User.create!(name: "Bryan") user.unset(:name) expect(user.name).to eq nil expect(user.reload.name).to eq nil expect(User.first.name).to eq nil end it "doesn't mind if you reference the field as a string" do user = User.create!(name: "Bryan") user.unset("name") expect(user.name).to eq nil expect(user.reload.name).to eq nil end end describe "#atomic_set" do it "updates the document (and not others) as long as the provided query is satisfied" do user = User.create!(name: "from", age: 18) other_user = User.create!(name: "from", age: 21) expect(user.atomic_set({ name: "from" }, name: "to")).to be_truthy expect(user.name).to eq "to" expect(user.age).to eq 18 user.reload expect(user.name).to eq "to" expect(user.age).to eq 18 other_user.reload expect(other_user.name).to eq "from" expect(other_user.age).to eq 21 end it "does not update the document when the provided query is not satisfied" do user = User.create!(name: "from", age: 18) expect(user.atomic_set({ name: "not-from" }, name: "to")).to be_falsey expect(user.name).to eq "from" expect(user.age).to eq 18 user.reload expect(user.name).to eq "from" expect(user.age).to eq 18 end end end
/*CSS style sheet*/ @font-face { font-family: 'Quicksand'; font-style: normal; font-weight: 400; src: local('Quicksand Regular'), local('Quicksand-Regular'), url(https://fonts.gstatic.com/s/quicksand/v6/<API key>.woff2) format('woff2'); unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB; } @font-face { font-family: 'Quicksand'; font-style: normal; font-weight: 400; src: local('Quicksand Regular'), local('Quicksand-Regular'), url(https://fonts.gstatic.com/s/quicksand/v6/<API key>.woff2) format('woff2'); unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'Quicksand'; font-style: normal; font-weight: 400; src: local('Quicksand Regular'), local('Quicksand-Regular'), url(https://fonts.gstatic.com/s/quicksand/v6/<API key>.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } /* vietnamese */ @font-face { font-family: 'Quicksand'; font-style: normal; font-weight: 700; src: local('Quicksand Bold'), local('Quicksand-Bold'), url(https://fonts.gstatic.com/s/quicksand/v6/<API key>.woff2) format('woff2'); unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB; } /* latin-ext */ @font-face { font-family: 'Quicksand'; font-style: normal; font-weight: 700; src: local('Quicksand Bold'), local('Quicksand-Bold'), url(https://fonts.gstatic.com/s/quicksand/v6/<API key>.woff2) format('woff2'); unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'Quicksand'; font-style: normal; font-weight: 700; src: local('Quicksand Bold'), local('Quicksand-Bold'), url(https://fonts.gstatic.com/s/quicksand/v6/<API key>.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } #main-wrapper{ width:500px; margin: 0 auto; background:white; padding:5px; border-radius:10px; border: 2px solid #95a5a6; } .avatar{ width:150px; text-align:center; } .myform{ width:450px; margin:0 auto; } .inputvalues{ width:430px; margin:5px auto; padding:2px; } .radiobtns{ margin: 10px; } .selectbox{ margin: 10px; } #login_btn{ margin-top:10px; background-color:#3166ac; padding:5px; color:white; width:100%; text-align:center; font-size:18px; font-weight:bold; font-family:Quicksand; } #register_btn{ margin-bottom:20px; margin-top:10px; background-color:#c34640; padding:5px; color:white; width:100%; text-align:center; font-size:18px; font-family:Quicksand; font-weight:bold; } #signup_btn{ margin-top:10px; background-color:#3166ac; padding:5px; color:white; width:100%; text-align:center; font-size:18px; font-family:Quicksand; font-weight:bold; } #back_btn{ margin-top:10px; background-color:#c34640; padding:5px; color:white; width:30%; text-align:center; font-size:18px; font-weight:bold; font-family:Quicksand; } form{ font-family:Quicksand; } #logout_btn{ margin-top:10px; background-color:#c34640; padding:5px; color:white; width:100%; text-align:center; font-size:18px; font-weight:bold; margin-bottom:20px; font-family:Quicksand; } a{ text-decoration:none; }
import React from 'react' import { shallow } from 'enzyme' import TableCell from '.' const wrap = (props = {}) => shallow(<TableCell {...props} />).dive() it('renders children when passed in', () => { const wrapper = wrap({ children: 'test' }) expect(wrapper.contains('test')).toBe(true) }) it('renders props when passed in', () => { const wrapper = wrap({ id: 'foo' }) expect(wrapper.find({ id: 'foo' })).toHaveLength(1) }) it('renders td by default', () => { const wrapper = wrap() expect(wrapper.find('td')).toHaveLength(1) }) it('renders th when prop heading is passed in', () => { const wrapper = wrap({ heading: true }) expect(wrapper.find('th')).toHaveLength(1) })
# example.js This example illustrates how to specify chunk name in `require.ensure()` and `import()` to separated modules into separate chunks manually. javascript {{example.js}} # templates/ * foo.js * baz.js * bar.js All templates are of this pattern: javascript {{templates/foo.js}} # js/output.js javascript {{js/output.js}} # Info ## Uncompressed {{stdout}} ## Minimized (uglify-js, no zip) {{min:stdout}}
# -*- coding: utf-8 -*- from uamobile.base import UserAgent, Display class EZwebUserAgent(UserAgent): carrier = 'EZweb' short_carrier = 'E' def supports_cookie(self): return True def make_display(self): """ create a Display object. """ env = self.environ try: width, height = map(int, env['<API key>'].split(',', 1)) except (KeyError, ValueError), e: width = None height = None try: color = env['<API key>'] == '1' except KeyError: color = False try: sd = env['<API key>'].split(',', 1) depth = sd[0] and (2 ** int(sd[0])) or 0 except (KeyError, ValueError): depth = None return Display(width=width, height=height, color=color, depth=depth) def is_ezweb(self): return True def get_serialnumber(self): """ return the EZweb subscriber ID. if no subscriber ID is available, returns None. """ try: return self.environ['HTTP_X_UP_SUBNO'] except KeyError: return None serialnumber = property(get_serialnumber) def is_xhtml_compliant(self): """ returns whether it's XHTML compliant or not. """ return self.xhtml_compliant def is_win(self): """ returns whether the agent is CDMA 1X WIN or not. """ return self.device_id[2:3] == '3' def is_wap1(self): return not self.is_wap2() def is_wap2(self): return self.xhtml_compliant
{% extends "analisis/baseanalisis.html" %} {%load staticfiles%} {% load i18n %} {% block extra_js%} <script> $( ".menu5" ).addClass( "active" ); $( ".menu5-3 a" ).append( " <i class='fa fa-check fa-lg'></i>" ); </script> {% endblock extra_js%} {% block contenido %} {% include "analisis/filtros.html" %} <h3>Organizaciones socias para los Proyectos e Innovaciones por Sector</h3> <table class="table table-bordered"> <tbody> {% for key,value in datos.items %} <tr> <td>{{key}}</td> <td> {% for x in value %} {% if x.sector == key %} {{x}}, {% endif %} {% endfor %} </td> </tr> {% endfor %} </tbody> </table> <h3>Distribución de las alianzas para cada sector (%)</h3> <div class="<API key>"> <table class="table table-bordered"> <thead> <tr> <th>Sector</th> {% for sector in sectores %} <th>{{sector}}</th> {% endfor %} <th>Total</th> </tr> </thead> <tbody> {% for x,y in lista_sectores.items %} <tr> <td>{{x}}</td> {% for z in y.0 %} <td> {% for valor in z %} {% if forloop.counter == 1 %} <b>{{valor}}</b> {% else %} <br> ({{valor|floatformat:2}} %) {% endif %} {% endfor %} </td> {% endfor %} <td><b>{{y.1}}</b></td> </tr> {% endfor %} </tbody> <tfoot> <tr> <td>Total</td> {% for x in lista_totales %} <td><b>{{x}}</b></td> {% endfor %} <td><b>{{total}}</b></td> </tr> </tfoot> </table> </div> <style> .menu5{ background: #5d8c3b; } .sidebar-collapse .nav > .menu5 > a { background: none; color: white } .menu5 .menu5-1, .menu5-2, .menu5-3, .menu5-4, .menu5-5{ background: white; } #page-inner{ min-height: 1250px } </style> {% endblock contenido %}
jQuery(function(t){t.datepicker.regional["en-GB"]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional["en-GB"])});
<link href="<?php echo base_url('themes/' . $this->settings['theme'] . '/css/redactor.css'); ?>" rel="stylesheet"> <link href="<?php echo base_url('themes/' . $this->settings['theme'] . '/css/tags.css'); ?>" rel="stylesheet"> <?php if(!$this->input->is_ajax_request()) echo '<br /><br />'; foreach ($post as $p) { ?> <div class="container"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <form action="<?php echo current_url(); ?>" method="post" class="form-horizontal submitForm" data-save="<?php echo phrase('update'); ?>" data-saving="<?php echo phrase('updating'); ?>" data-alert="<?php echo phrase('<API key>'); ?>"> <?php if($this->input->is_ajax_request() && isset($modal)) { ?> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i></button> <h3><i class="fa fa-edit"></i> &nbsp; <?php echo phrase('update_open_letter'); ?></h3> </div> <?php } ?> <div class="modal-body"> <div class="form-group"> <div class="col-sm-12"> <input type="text" name="title" class="form-control input-lg" value="<?php echo htmlspecialchars(set_value('title', $p['title'])); ?>" placeholder="<?php echo phrase('letter_headline'); ?>" /> </div> </div> <div class="form-group"> <div class="col-sm-12"> <input type="text" name="targetName" class="form-control" value="<?php echo htmlspecialchars(set_value('targetName', $p['targetName'])); ?>" placeholder="<?php echo phrase('aimed_to'); ?>" /> </div> </div> <div class="form-group"> <div class="col-sm-12"> <textarea name="targetDetails" class="form-control" placeholder="<?php echo phrase('target_details'); ?>"><?php echo htmlspecialchars(set_value('targetDetails', $p['targetDetails'])); ?></textarea> </div> </div> <div class="form-group"> <div class="col-sm-12"> <textarea name="content" class="redactor form-control" placeholder="<?php echo phrase('<API key>'); ?>"><?php echo set_value('content', $p['content']); ?></textarea> </div> </div> <div class="form-group"> <div class="col-sm-12 statusHolder"> </div> </div> </div> <div class="modal-footer"> <div class="form-group"> <div class="col-xs-6 nomargin text-left"> <?php if($this->input->is_ajax_request() && isset($modal)) { ?> <a href="javascript:void(0)" class="btn btn-default btn-lg" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i> <?php echo phrase('cancel'); ?></a> <?php } else { ?> <a href="<?php echo base_url('user/openletters'); ?>" class="btn btn-default btn-lg ajaxLoad"><i class="fa fa-times"></i> <?php echo phrase('cancel'); ?></a> <?php } ?> </div> <div class="col-xs-6 nomargin"> <input type="hidden" name="hash" value="<?php echo sha1(time()); ?>" /> <button class="btn btn-success btn-lg submitBtn" type="submit"><i class="fa fa-save"></i> <?php echo phrase('update'); ?></button> </div> </div> </div> </form> </div> </div> </div> <?php } ?> <script src="<?php echo base_url('themes/' . $this->settings['theme'] . '/js/redactor.js'); ?>"></script> <script src="<?php echo base_url('themes/' . $this->settings['theme'] . '/js/tags.js'); ?>"></script> <script type="text/javascript"> if($(window).width() > 768) { $('.redactor').redactor({ buttons:["formatting","|","bold","italic","deleted","|","unorderedlist","orderedlist","outdent","indent","|","alignment","|","horizontalrule"], plugins: ['fontcolor'], minHeight: 200 }); } </script>
import { expect } from 'chai'; import { renderComponent } from 'helpers/TestHelper'; import { About } from './index'; describe('<About />', () => { const component = renderComponent(About); it('Renders with correct style', () => { const style = require('./style.css'); expect(component.find(style.About)).to.exist; }); it('Renders header with text', () => { expect(component.find('h4').text()).to.eql('About'); }); });
<!DOCTYPE html> <!--[if IE 8]> <html lang="en" class="ie8"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="UTF-8" /> <title>BCORE Admin Dashboard Template | Timeline Page</title> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <meta content="" name="description" /> <meta content="" name="author" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <![endif] <!-- GLOBAL STYLES --> <!-- GLOBAL STYLES --> <link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.css" /> <link rel="stylesheet" href="assets/css/main.css" /> <link rel="stylesheet" href="assets/css/theme.css" /> <link rel="stylesheet" href="assets/css/MoneAdmin.css" /> <link rel="stylesheet" href="assets/plugins/Font-Awesome/css/font-awesome.css" /> <!--END GLOBAL STYLES <!-- PAGE LEVEL STYLES --> <link rel="stylesheet" href="assets/plugins/timeline/timeline.css" /> <!-- END PAGE LEVEL STYLES --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif] </head> <!-- BEGIN HEAD --> <!-- BEGIN BODY --> <body class="padTop53 " > <!-- MAIN WRAPPER --> <div id="wrap"> <!-- HEADER SECTION --> <div id="top"> <nav class="navbar navbar-inverse navbar-fixed-top " style="padding-top: 10px;"> <a data-original-title="Show/Hide Menu" data-placement="bottom" data-tooltip="tooltip" class="accordion-toggle btn btn-primary btn-sm visible-xs" data-toggle="collapse" href="#menu" id="menu-toggle"> <i class="icon-align-justify"></i> </a> <!-- LOGO SECTION --> <header class="navbar-header"> <a href="index.html" class="navbar-brand"> <img src="assets/img/logo.png" alt="" /></a> </header> <!-- END LOGO SECTION --> <ul class="nav navbar-top-links navbar-right"> <!-- MESSAGES SECTION --> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href=" <span class="label label-success">2</span> <i class="icon-envelope-alt"></i>&nbsp; <i class="icon-chevron-down"></i> </a> <ul class="dropdown-menu dropdown-messages"> <li> <a href=" <div> <strong>John Smith</strong> <span class="pull-right text-muted"> <em>Today</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing. <br /> <span class="label label-primary">Important</span> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <strong>Raphel Jonson</strong> <span class="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing. <br /> <span class="label label-success"> Moderate </span> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <strong>Chi Ley Suk</strong> <span class="pull-right text-muted"> <em>26 Jan 2014</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing. <br /> <span class="label label-danger"> Low </span> </div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href=" <strong>Read All Messages</strong> <i class="icon-angle-right"></i> </a> </li> </ul> </li> <!--END MESSAGES SECTION <!--TASK SECTION <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href=" <span class="label label-danger">5</span> <i class="icon-tasks"></i>&nbsp; <i class="icon-chevron-down"></i> </a> <ul class="dropdown-menu dropdown-tasks"> <li> <a href=" <div> <p> <strong> Profile </strong> <span class="pull-right text-muted">40% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar <API key>" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"> <span class="sr-only">40% Complete (success)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <p> <strong> Pending Tasks </strong> <span class="pull-right text-muted">20% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> <span class="sr-only">20% Complete</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <p> <strong> Work Completed </strong> <span class="pull-right text-muted">60% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar <API key>" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"> <span class="sr-only">60% Complete (warning)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <p> <strong> Summary </strong> <span class="pull-right text-muted">80% Complete</span> </p> <div class="progress progress-striped active"> <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"> <span class="sr-only">80% Complete (danger)</span> </div> </div> </div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href=" <strong>See All Tasks</strong> <i class="icon-angle-right"></i> </a> </li> </ul> </li> <!--END TASK SECTION <!--ALERTS SECTION <li class="chat-panel dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href=" <span class="label label-info">8</span> <i class="icon-comments"></i>&nbsp; <i class="icon-chevron-down"></i> </a> <ul class="dropdown-menu dropdown-alerts"> <li> <a href=" <div> <i class="icon-comment" ></i> New Comment <span class="pull-right text-muted small"> 4 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <i class="icon-twitter info"></i> 3 New Follower <span class="pull-right text-muted small"> 9 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <i class="icon-envelope"></i> Message Sent <span class="pull-right text-muted small" > 20 minutes ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <i class="icon-tasks"></i> New Task <span class="pull-right text-muted small"> 1 Hour ago</span> </div> </a> </li> <li class="divider"></li> <li> <a href=" <div> <i class="icon-upload"></i> Server Rebooted <span class="pull-right text-muted small"> 2 Hour ago</span> </div> </a> </li> <li class="divider"></li> <li> <a class="text-center" href=" <strong>See All Alerts</strong> <i class="icon-angle-right"></i> </a> </li> </ul> </li> <!-- END ALERTS SECTION --> <!--ADMIN SETTINGS SECTIONS <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href=" <i class="icon-user "></i>&nbsp; <i class="icon-chevron-down "></i> </a> <ul class="dropdown-menu dropdown-user"> <li><a href="#"><i class="icon-user"></i> User Profile </a> </li> <li><a href="#"><i class="icon-gear"></i> Settings </a> </li> <li class="divider"></li> <li><a href="login.html"><i class="icon-signout"></i> Logout </a> </li> </ul> </li> <!--END ADMIN SETTINGS </ul> </nav> </div> <!-- END HEADER SECTION --> <!-- MENU SECTION --> <div id="left"> <div class="media user-media well-small"> <a class="user-link" href=" <img class="media-object img-thumbnail user-img" alt="User Picture" src="assets/img/user.gif" /> </a> <br /> <div class="media-body"> <h5 class="media-heading"> Joe Romlin</h5> <ul class="list-unstyled user-info"> <li> <a class="btn btn-success btn-xs btn-circle" style="width: 10px;height: 12px;"></a> Online </li> </ul> </div> <br /> </div> <ul id="menu" class="collapse"> <li class="panel"> <a href="index.html" > <i class="icon-table"></i> Dashboard </a> </li> <li class="panel "> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle" data-target="#component-nav"> <i class="icon-tasks"> </i> UI Elements <span class="pull-right"> <i class="icon-angle-left"></i> </span> &nbsp; <span class="label label-default">10</span>&nbsp; </a> <ul class="collapse" id="component-nav"> <li class=""><a href="button.html"><i class="icon-angle-right"></i> Buttons </a></li> <li class=""><a href="icon.html"><i class="icon-angle-right"></i> Icons </a></li> <li class=""><a href="progress.html"><i class="icon-angle-right"></i> Progress </a></li> <li class=""><a href="tabs_panels.html"><i class="icon-angle-right"></i> Tabs & Panels </a></li> <li class=""><a href="notifications.html"><i class="icon-angle-right"></i> Notification </a></li> <li class=""><a href="more_notifications.html"><i class="icon-angle-right"></i> More Notification </a></li> <li class=""><a href="modals.html"><i class="icon-angle-right"></i> Modals </a></li> <li class=""><a href="wizard.html"><i class="icon-angle-right"></i> Wizard </a></li> <li class=""><a href="sliders.html"><i class="icon-angle-right"></i> Sliders </a></li> <li class=""><a href="typography.html"><i class="icon-angle-right"></i> Typography </a></li> </ul> </li> <li class="panel "> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle collapsed" data-target="#form-nav"> <i class="icon-pencil"></i> Forms <span class="pull-right"> <i class="icon-angle-left"></i> </span> &nbsp; <span class="label label-success">5</span>&nbsp; </a> <ul class="collapse" id="form-nav"> <li class=""><a href="forms_general.html"><i class="icon-angle-right"></i> General </a></li> <li class=""><a href="forms_advance.html"><i class="icon-angle-right"></i> Advance </a></li> <li class=""><a href="forms_validation.html"><i class="icon-angle-right"></i> Validation </a></li> <li class=""><a href="forms_fileupload.html"><i class="icon-angle-right"></i> FileUpload </a></li> <li class=""><a href="forms_editors.html"><i class="icon-angle-right"></i> WYSIWYG / Editor </a></li> </ul> </li> <li class="panel active"> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle" data-target="#pagesr-nav"> <i class="icon-table"></i> Pages <span class="pull-right"> <i class="icon-angle-left"></i> </span> &nbsp; <span class="label label-info">6</span>&nbsp; </a> <ul class="in" id="pagesr-nav"> <li><a href="pages_calendar.html"><i class="icon-angle-right"></i> Calendar </a></li> <li><a href="pages_timeline.html"><i class="icon-angle-right"></i> Timeline </a></li> <li><a href="pages_social.html"><i class="icon-angle-right"></i> Social </a></li> <li><a href="pages_pricing.html"><i class="icon-angle-right"></i> Pricing </a></li> <li><a href="pages_offline.html"><i class="icon-angle-right"></i> Offline </a></li> <li><a href="pages_uc.html"><i class="icon-angle-right"></i> Under Construction </a></li> </ul> </li> <li class="panel"> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle" data-target="#chart-nav"> <i class="icon-bar-chart"></i> Charts <span class="pull-right"> <i class="icon-angle-left"></i> </span> &nbsp; <span class="label label-danger">4</span>&nbsp; </a> <ul class="collapse" id="chart-nav"> <li><a href="charts_line.html"><i class="icon-angle-right"></i> Line Charts </a></li> <li><a href="charts_bar.html"><i class="icon-angle-right"></i> Bar Charts</a></li> <li><a href="charts_pie.html"><i class="icon-angle-right"></i> Pie Charts </a></li> <li><a href="charts_other.html"><i class="icon-angle-right"></i> other Charts </a></li> </ul> </li> <li class="panel"> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle" data-target="#DDL-nav"> <i class=" icon-sitemap"></i> 3 Level Menu <span class="pull-right"> <i class="icon-angle-left"></i> </span> </a> <ul class="collapse" id="DDL-nav"> <li> <a href="#" data-parent="#DDL-nav" data-toggle="collapse" class="accordion-toggle" data-target="#DDL1-nav"> <i class="icon-sitemap"></i>&nbsp; Demo Link 1 <span class="pull-right" style="margin-right: 20px;"> <i class="icon-angle-left"></i> </span> </a> <ul class="collapse" id="DDL1-nav"> <li> <a href="#"><i class="icon-angle-right"></i> Demo Link 1 </a> </li> <li> <a href="#"><i class="icon-angle-right"></i> Demo Link 2 </a></li> <li> <a href="#"><i class="icon-angle-right"></i> Demo Link 3 </a></li> </ul> </li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 2 </a></li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 3 </a></li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 4 </a></li> </ul> </li> <li class="panel"> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle" data-target="#DDL4-nav"> <i class=" <API key>"></i> 4 Level Menu <span class="pull-right"> <i class="icon-angle-left"></i> </span> </a> <ul class="collapse" id="DDL4-nav"> <li> <a href="#" data-parent="DDL4-nav" data-toggle="collapse" class="accordion-toggle" data-target="#DDL4_1-nav"> <i class="icon-sitemap"></i>&nbsp; Demo Link 1 <span class="pull-right" style="margin-right: 20px;"> <i class="icon-angle-left"></i> </span> </a> <ul class="collapse" id="DDL4_1-nav"> <li> <a href="#" data-parent="#DDL4_1-nav" data-toggle="collapse" class="accordion-toggle" data-target="#DDL4_2-nav"> <i class="icon-sitemap"></i>&nbsp; Demo Link 1 <span class="pull-right" style="margin-right: 20px;"> <i class="icon-angle-left"></i> </span> </a> <ul class="collapse" id="DDL4_2-nav"> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 1 </a></li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 2 </a></li> </ul> </li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 2 </a></li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 3 </a></li> </ul> </li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 2 </a></li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 3 </a></li> <li><a href="#"><i class="icon-angle-right"></i> Demo Link 4 </a></li> </ul> </li> <li class="panel"> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle" data-target="#error-nav"> <i class="icon-warning-sign"></i> Error Pages <span class="pull-right"> <i class="icon-angle-left"></i> </span> &nbsp; <span class="label label-warning">5</span>&nbsp; </a> <ul class="collapse" id="error-nav"> <li><a href="errors_403.html"><i class="icon-angle-right"></i> Error 403 </a></li> <li><a href="errors_404.html"><i class="icon-angle-right"></i> Error 404 </a></li> <li><a href="errors_405.html"><i class="icon-angle-right"></i> Error 405 </a></li> <li><a href="errors_500.html"><i class="icon-angle-right"></i> Error 500 </a></li> <li><a href="errors_503.html"><i class="icon-angle-right"></i> Error 503 </a></li> </ul> </li> <li><a href="gallery.html"><i class="icon-film"></i> Image Gallery </a></li> <li><a href="tables.html"><i class="icon-table"></i> Data Tables </a></li> <li><a href="maps.html"><i class="icon-map-marker"></i> Maps </a></li> <li><a href="grid.html"><i class="icon-columns"></i> Grid </a></li> <li class="panel"> <a href="#" data-parent="#menu" data-toggle="collapse" class="accordion-toggle" data-target="#blank-nav"> <i class="icon-check-empty"></i> Blank Pages <span class="pull-right"> <i class="icon-angle-left"></i> </span> &nbsp; <span class="label label-success">2</span>&nbsp; </a> <ul class="collapse" id="blank-nav"> <li><a href="blank.html"><i class="icon-angle-right"></i> Blank Page One </a></li> <li><a href="blank2.html"><i class="icon-angle-right"></i> Blank Page Two </a></li> </ul> </li> <li><a href="login.html"><i class="icon-signin"></i> Login Page </a></li> </ul> </div> <!--END MENU SECTION <!--PAGE CONTENT <div id="content"> <div class="inner"> <div class="row"> <div class="col-lg-12"> <h2> TimeLine Page </h2> </div> </div> <hr /> <div class="row"> <div class="col-lg-12"> <div class="panel panel-primary"> <div class="panel-heading"> <i class="fa fa-clock-o fa-fw"></i> Timeline </div> <div class="panel-body"> <ul class="timeline"> <li> <div class="timeline-badge success"> <i class=" icon-pencil"></i> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4 class="timeline-title">Timeline Event</h4> <p> <small class="text-muted"><i class="icon-check icon-2x"></i>11 hours ago via Twitter</small> </p> </div> <div class="timeline-body"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-badge warning"> <i class="icon-credit-card"></i> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4 class="timeline-title">Timeline Event</h4> </div> <div class="timeline-body"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in metus eu lectus aliquet egestas.</p> </div> </div> </li> <li> <div class="timeline-badge danger"> <i class="icon-map-marker"></i> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4 class="timeline-title">Timeline Event</h4> </div> <div class="timeline-body"> <p>Lorem ipsum dolor sit scelerisque vulputate. Aliquam in metus eu lectus aliquet egestas.</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-badge"> <i class="icon-envelope-alt"></i> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4 class="timeline-title">Timeline Event</h4> </div> <div class="timeline-body"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in metus eu lectus aliquet egestas.</p> </div> </div> </li> <li> <div class="timeline-badge info"> <i class="icon-check"></i> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4 class="timeline-title">Timeline Event</h4> </div> <div class="timeline-body"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in metus eu lectus aliquet egestas.</p> <hr /> <div class="btn-group"> <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action</a> </li> <li><a href="#">Another action</a> </li> <li><a href="#">Something else here</a> </li> <li class="divider"></li> <li><a href="#">Separated link</a> </li> </ul> </div> </div> </div> </li> </ul> </div> </div> </div> </div> </div> </div> <!--END PAGE CONTENT </div> <!--END MAIN WRAPPER <!-- FOOTER --> <div id="footer"> <p>&copy; binarytheme &nbsp;2014 &nbsp;</p> </div> <!--END FOOTER <!-- GLOBAL SCRIPTS --> <script src="assets/plugins/jquery-2.0.3.min.js"></script> <script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script> <script src="assets/plugins/modernizr-2.6.2-respond-1.1.0.min.js"></script> <!-- END GLOBAL SCRIPTS --> </body> <!-- END BODY --> </html>
package com.groupon.jenkins.dotci.notifiers; import com.fasterxml.jackson.databind.ObjectMapper; import com.groupon.jenkins.dynamic.build.DynamicBuild; import com.groupon.jenkins.notifications.PostBuildNotifier; import hudson.Extension; import hudson.model.BuildListener; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; @Extension public class WebhookNotifier extends PostBuildNotifier { private static final Logger LOGGER = Logger.getLogger(WebhookNotifier.class.getName()); public WebhookNotifier() { super("webhook"); } @Override protected Type getType() { return PostBuildNotifier.Type.ALL; } @Override protected boolean notify(DynamicBuild build, BuildListener listener) { Map<String, ?> options = (Map<String, ?>) getOptions(); HttpClient client = getHttpClient(); String requestUrl = (String) options.get("url"); PostMethod post = new PostMethod(requestUrl); Map<String, String> payload = (Map<String, String>) options.get("payload"); ObjectMapper objectMapper = new ObjectMapper(); try { String payloadJson = objectMapper.writeValueAsString(payload); StringRequestEntity requestEntity = new StringRequestEntity(payloadJson, "application/json", "UTF-8"); post.setRequestEntity(requestEntity); int statusCode = client.executeMethod(post); listener.getLogger().println("Posted Paylod " + payloadJson + " to " + requestUrl + " with response code " + statusCode); } catch (Exception e) { listener.getLogger().print("Failed to make a POST to webhook. Check Jenkins logs for exceptions."); LOGGER.log(Level.WARNING, "Error posting to webhook", e); return false; } finally { post.releaseConnection(); } return false; } protected HttpClient getHttpClient() { return new HttpClient(); } }
# Facades - [Introduction](#introduction) - [Explanation](#explanation) - [Practical Usage](#practical-usage) - [Creating Facades](#creating-facades) - [Mocking Facades](#mocking-facades) - [Facade Class Reference](#<API key>) <a name="introduction"></a> ## Introduction Facades provide a "static" interface to classes that are available in the application's [IoC container](/docs/ioc). Laravel ships with many facades, and you have probably been using them without even knowing it! Laravel "facades" serve as "static proxies" to underlying classes in the IoC container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. Occasionally, You may wish to create your own facades for your applications and packages, so let's explore the concept, development and usage of these classes. > **Note:** Before digging into facades, it is strongly recommended that you become very familiar with the Laravel [IoC container](/docs/ioc). <a name="explanation"></a> ## Explanation In the context of a Laravel application, a facade is a class that provides access to an object from the container. The machinery that makes this work is in the `Facade` class. Laravel's facades, and any custom facades you create, will extend the base `Facade` class. Your facade class only needs to implement a single method: `getFacadeAccessor`. It's the `getFacadeAccessor` method's job to define what to resolve from the container. The `Facade` base class makes use of the `__callStatic()` magic-method to defer calls from your facade to the resolved object. So, when you make a facade call like `Cache::get`, Laravel resolves the Cache manager class out of the IoC container and calls the `get` method on the class. In technical terms, Laravel Facades are a convenient syntax for using the Laravel IoC container as a service locator. <a name="practical-usage"></a> ## Practical Usage In the example below, a call is made to the Laravel cache system. By glancing at this code, one might assume that the static method `get` is being called on the `Cache` class. $value = Cache::get('key'); However, if we look at that `Illuminate\Support\Facades\Cache` class, you'll see that there is no static method `get`: class Cache extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'cache'; } } The Cache class extends the base `Facade` class and defines a method `getFacadeAccessor()`. Remember, this method's job is to return the name of an IoC binding. When a user references any static method on the `Cache` facade, Laravel resolves the `cache` binding from the IoC container and runs the requested method (in this case, `get`) against that object. So, our `Cache::get` call could be re-written like so: $value = $app->make('cache')->get('key'); <a name="creating-facades"></a> ## Creating Facades Creating a facade for your own application or package is simple. You only need 3 things: - An IoC binding - A facade class. - A facade alias configuration. Let's look at an example. Here, we have a class defined as `PaymentGateway\Payment`. namespace PaymentGateway; class Payment { public function process() { } } This class might live in your `app/models` directory, or any other directory that Composer knows how to auto-load. We need to be able to resolve this class from the IoC container. So, let's add a binding: App::bind('payment', function() { return new \PaymentGateway\Payment; }); A great place to register this binding would be to create a new [service provider](/docs/ioc#service-providers) named `<API key>`, and add this binding to the `register` method. You can then configure Laravel to load your service provider from the `app/config/app.php` configuration file. Next, we can create our own facade class: use Illuminate\Support\Facades\Facade; class Payment extends Facade { protected static function getFacadeAccessor() { return 'payment'; } } Finally, if we wish, we can add an alias for our facade to the `aliases` array in the `app/config/app.php` configuration file. Now, we can call the `process` method on an instance of the `Payment` class. Payment::process(); A Note On Auto-Loading Aliases Classes in the `aliases` array are not available in some instances because [PHP will not attempt to autoload undefined type-hinted classes](https://bugs.php.net/bug.php?id=39003). If `\ServiceWrapper\ApiTimeoutException` is aliased to `ApiTimeoutException`, a `catch(ApiTimeoutException $e)` outside of the namespace `\ServiceWrapper` will never catch the exception, even if one is thrown. A similar problem is found in Models which have type hints to aliased classes. The only workaround is to forego aliasing and `use` the classes you wish to type hint at the top of each file which requires them. <a name="mocking-facades"></a> ## Mocking Facades Unit testing is an important aspect of why facades work the way that they do. In fact, testability is the primary reason for facades to even exist. For more information, check out the [mocking facades](/docs/testing#mocking-facades) section of the documentation. <a name="<API key>"></a> ## Facade Class Reference Below you will find every facade and its underlying class. This is a useful tool for quickly digging into the API documentation for a given facade root. The [IoC binding](/docs/ioc) key is also included where applicable. Facade | Class | IoC Binding App | [Illuminate\Foundation\Application](http://laravel.com/api/4.1/Illuminate/Foundation/Application.html) | `app` Artisan | [Illuminate\Console\Application](http://laravel.com/api/4.1/Illuminate/Console/Application.html) | `artisan` Auth | [Illuminate\Auth\AuthManager](http://laravel.com/api/4.1/Illuminate/Auth/AuthManager.html) | `auth` Auth (Instance) | [Illuminate\Auth\Guard](http://laravel.com/api/4.1/Illuminate/Auth/Guard.html) | Blade | [Illuminate\View\Compilers\BladeCompiler](http://laravel.com/api/4.1/Illuminate/View/Compilers/BladeCompiler.html) | `blade.compiler` Cache | [Illuminate\Cache\Repository](http://laravel.com/api/4.1/Illuminate/Cache/Repository.html) | `cache` Config | [Illuminate\Config\Repository](http://laravel.com/api/4.1/Illuminate/Config/Repository.html) | `config` Cookie | [Illuminate\Cookie\CookieJar](http://laravel.com/api/4.1/Illuminate/Cookie/CookieJar.html) | `cookie` Crypt | [Illuminate\Encryption\Encrypter](http://laravel.com/api/4.1/Illuminate/Encryption/Encrypter.html) | `encrypter` DB | [Illuminate\Database\DatabaseManager](http://laravel.com/api/4.1/Illuminate/Database/DatabaseManager.html) | `db` DB (Instance) | [Illuminate\Database\Connection](http://laravel.com/api/4.1/Illuminate/Database/Connection.html) | Event | [Illuminate\Events\Dispatcher](http://laravel.com/api/4.1/Illuminate/Events/Dispatcher.html) | `events` File | [Illuminate\Filesystem\Filesystem](http://laravel.com/api/4.1/Illuminate/Filesystem/Filesystem.html) | `files` Form | [Illuminate\Html\FormBuilder](http://laravel.com/api/4.1/Illuminate/Html/FormBuilder.html) | `form` Hash | [Illuminate\Hashing\HasherInterface](http://laravel.com/api/4.1/Illuminate/Hashing/HasherInterface.html) | `hash` HTML | [Illuminate\Html\HtmlBuilder](http://laravel.com/api/4.1/Illuminate/Html/HtmlBuilder.html) | `html` Input | [Illuminate\Http\Request](http://laravel.com/api/4.1/Illuminate/Http/Request.html) | `request` Lang | [Illuminate\Translation\Translator](http://laravel.com/api/4.1/Illuminate/Translation/Translator.html) | `translator` Log | [Illuminate\Log\Writer](http://laravel.com/api/4.1/Illuminate/Log/Writer.html) | `log` Mail | [Illuminate\Mail\Mailer](http://laravel.com/api/4.1/Illuminate/Mail/Mailer.html) | `mailer` Paginator | [Illuminate\Pagination\Factory](http://laravel.com/api/4.1/Illuminate/Pagination/Factory.html) | `paginator` Paginator (Instance) | [Illuminate\Pagination\Paginator](http://laravel.com/api/4.1/Illuminate/Pagination/Paginator.html) | Password | [Illuminate\Auth\Reminders\PasswordBroker](http://laravel.com/api/4.1/Illuminate/Auth/Reminders/PasswordBroker.html) | `auth.reminder` Queue | [Illuminate\Queue\QueueManager](http://laravel.com/api/4.1/Illuminate/Queue/QueueManager.html) | `queue` Queue (Instance) | [Illuminate\Queue\QueueInterface](http://laravel.com/api/4.1/Illuminate/Queue/QueueInterface.html) | Queue (Base Class) | [Illuminate\Queue\Queue](http://laravel.com/api/4.1/Illuminate/Queue/Queue.html) | Redirect | [Illuminate\Routing\Redirector](http://laravel.com/api/4.1/Illuminate/Routing/Redirector.html) | `redirect` Redis | [Illuminate\Redis\Database](http://laravel.com/api/4.1/Illuminate/Redis/Database.html) | `redis` Request | [Illuminate\Http\Request](http://laravel.com/api/4.1/Illuminate/Http/Request.html) | `request` Response | [Illuminate\Support\Facades\Response](http://laravel.com/api/4.1/Illuminate/Support/Facades/Response.html) | Route | [Illuminate\Routing\Router](http://laravel.com/api/4.1/Illuminate/Routing/Router.html) | `router` Schema | [Illuminate\Database\Schema\Blueprint](http://laravel.com/api/4.1/Illuminate/Database/Schema/Blueprint.html) | Session | [Illuminate\Session\SessionManager](http://laravel.com/api/4.1/Illuminate/Session/SessionManager.html) | `session` Session (Instance) | [Illuminate\Session\Store](http://laravel.com/api/4.1/Illuminate/Session/Store.html) | SSH | [Illuminate\Remote\RemoteManager](http://laravel.com/api/4.1/Illuminate/Remote/RemoteManager.html) | `remote` SSH (Instance) | [Illuminate\Remote\Connection](http://laravel.com/api/4.1/Illuminate/Remote/Connection.html) | URL | [Illuminate\Routing\UrlGenerator](http://laravel.com/api/4.1/Illuminate/Routing/UrlGenerator.html) | `url` Validator | [Illuminate\Validation\Factory](http://laravel.com/api/4.1/Illuminate/Validation/Factory.html) | `validator` Validator (Instance) | [Illuminate\Validation\Validator](http://laravel.com/api/4.1/Illuminate/Validation/Validator.html) View | [Illuminate\View\Factory](http://laravel.com/api/4.1/Illuminate/View/Factory.html) | `view` View (Instance) | [Illuminate\View\View](http://laravel.com/api/4.1/Illuminate/View/View.html) |
<?php namespace SocialiteProviders\Manager\Stubs; use Laravel\Socialite\Two\AbstractProvider; class OAuth2ProviderStub extends AbstractProvider { protected $test = 'test'; /** * {@inheritdoc} */ protected function getAuthUrl($state) { return 'test'; } /** * {@inheritdoc} */ protected function getTokenUrl() { return $this->test; } /** * {@inheritdoc} */ protected function getUserByToken($token) { return [$this->test]; } /** * {@inheritdoc} */ protected function mapUserToObject(array $user) { return $this->test; } }
package org.spongepowered.api.data.manipulator.block; import org.spongepowered.api.block.tileentity.Comparator; import org.spongepowered.api.block.tileentity.DaylightDetector; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.data.manipulator.IntData; /** * Represents a {@link TileEntity} that is signaling a redstone output. * Usually applicable to {@link Comparator}s and {@link DaylightDetector}s. */ public interface SignaledOutputData extends IntData<SignaledOutputData> { /** * Gets the output signal strength. * * @return The signal strength */ int getOutputSignal(); /** * Sets the output signal strength. * * @param signal The new signal strength * @return This instance, for chaining */ SignaledOutputData setOutputSignal(int signal); }
/* body_sw.cpp */ /* This file is part of: */ /* GODOT ENGINE */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* included in all copies or substantial portions of the Software. */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "body_sw.h" #include "area_sw.h" #include "space_sw.h" void BodySW::_update_inertia() { if (get_space() && !inertia_update_list.in_list()) get_space()-><API key>(&inertia_update_list); } void BodySW::<API key>() { center_of_mass = get_transform().basis.xform(<API key>); <API key> = get_transform().basis * <API key>; // update inertia tensor Basis tb = <API key>; Basis tbt = tb.transposed(); tb.scale(_inv_inertia); _inv_inertia_tensor = tb * tbt; } void BodySW::update_inertias() { //update shapes and motions switch (mode) { case PhysicsServer::BODY_MODE_RIGID: { //update tensor for all shapes, not the best way but should be somehow OK. (inspired from bullet) real_t total_area = 0; for (int i = 0; i < get_shape_count(); i++) { total_area += get_shape_area(i); } // We have to recompute the center of mass <API key>.zero(); for (int i = 0; i < get_shape_count(); i++) { real_t area = get_shape_area(i); real_t mass = area * this->mass / total_area; // NOTE: we assume that the shape origin is also its center of mass <API key> += mass * get_shape_transform(i).origin; } <API key> /= mass; // Recompute the inertia tensor Basis inertia_tensor; inertia_tensor.set_zero(); for (int i = 0; i < get_shape_count(); i++) { const ShapeSW *shape = get_shape(i); real_t area = get_shape_area(i); real_t mass = area * this->mass / total_area; Basis <API key> = shape-><API key>(mass).to_diagonal_matrix(); Transform shape_transform = get_shape_transform(i); Basis shape_basis = shape_transform.basis.orthonormalized(); // NOTE: we don't take the scale of collision shapes into account when computing the inertia tensor! <API key> = shape_basis * <API key> * shape_basis.transposed(); Vector3 shape_origin = shape_transform.origin - <API key>; inertia_tensor += <API key> + (Basis() * shape_origin.dot(shape_origin) - shape_origin.outer(shape_origin)) * mass; } // Compute the principal axes of inertia <API key> = inertia_tensor.diagonalize().transposed(); _inv_inertia = inertia_tensor.get_main_diagonal().inverse(); if (mass) _inv_mass = 1.0 / mass; else _inv_mass = 0; } break; case PhysicsServer::BODY_MODE_KINEMATIC: case PhysicsServer::BODY_MODE_STATIC: { _inv_inertia_tensor.set_zero(); _inv_mass = 0; } break; case PhysicsServer::BODY_MODE_CHARACTER: { _inv_inertia_tensor.set_zero(); _inv_mass = 1.0 / mass; } break; } //_update_shapes(); <API key>(); } void BodySW::set_active(bool p_active) { if (active == p_active) return; active = p_active; if (!p_active) { if (get_space()) get_space()-><API key>(&active_list); } else { if (mode == PhysicsServer::BODY_MODE_STATIC) return; //static bodies can't become active if (get_space()) get_space()-><API key>(&active_list); //still_time=0; } /* if (!space) return; for(int i=0;i<get_shape_count();i++) { Shape &s=shapes[i]; if (s.bpid>0) { get_space()->get_broadphase()->set_active(s.bpid,active); } } */ } void BodySW::set_param(PhysicsServer::BodyParameter p_param, real_t p_value) { switch (p_param) { case PhysicsServer::BODY_PARAM_BOUNCE: { bounce = p_value; } break; case PhysicsServer::BODY_PARAM_FRICTION: { friction = p_value; } break; case PhysicsServer::BODY_PARAM_MASS: { ERR_FAIL_COND(p_value <= 0); mass = p_value; _update_inertia(); } break; case PhysicsServer::<API key>: { gravity_scale = p_value; } break; case PhysicsServer::<API key>: { linear_damp = p_value; } break; case PhysicsServer::<API key>: { angular_damp = p_value; } break; default: {} } } real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const { switch (p_param) { case PhysicsServer::BODY_PARAM_BOUNCE: { return bounce; } break; case PhysicsServer::BODY_PARAM_FRICTION: { return friction; } break; case PhysicsServer::BODY_PARAM_MASS: { return mass; } break; case PhysicsServer::<API key>: { return gravity_scale; } break; case PhysicsServer::<API key>: { return linear_damp; } break; case PhysicsServer::<API key>: { return angular_damp; } break; default: {} } return 0; } void BodySW::set_mode(PhysicsServer::BodyMode p_mode) { PhysicsServer::BodyMode prev = mode; mode = p_mode; switch (p_mode) { //CLEAR UP EVERYTHING IN CASE IT NOT WORKS! case PhysicsServer::BODY_MODE_STATIC: case PhysicsServer::BODY_MODE_KINEMATIC: { _set_inv_transform(get_transform().affine_inverse()); _inv_mass = 0; _set_static(p_mode == PhysicsServer::BODY_MODE_STATIC); //set_active(p_mode==PhysicsServer::BODY_MODE_KINEMATIC); set_active(p_mode == PhysicsServer::BODY_MODE_KINEMATIC && contacts.size()); linear_velocity = Vector3(); angular_velocity = Vector3(); if (mode == PhysicsServer::BODY_MODE_KINEMATIC && prev != mode) { <API key> = true; } } break; case PhysicsServer::BODY_MODE_RIGID: { _inv_mass = mass > 0 ? (1.0 / mass) : 0; _set_static(false); } break; case PhysicsServer::BODY_MODE_CHARACTER: { _inv_mass = mass > 0 ? (1.0 / mass) : 0; _set_static(false); } break; } _update_inertia(); /* if (get_space()) _update_queries(); */ } PhysicsServer::BodyMode BodySW::get_mode() const { return mode; } void BodySW::_shapes_changed() { _update_inertia(); } void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant &p_variant) { switch (p_state) { case PhysicsServer::<API key>: { if (mode == PhysicsServer::BODY_MODE_KINEMATIC) { new_transform = p_variant; //wakeup_neighbours(); set_active(true); if (<API key>) { _set_transform(p_variant); _set_inv_transform(get_transform().affine_inverse()); <API key> = false; } } else if (mode == PhysicsServer::BODY_MODE_STATIC) { _set_transform(p_variant); _set_inv_transform(get_transform().affine_inverse()); wakeup_neighbours(); } else { Transform t = p_variant; t.orthonormalize(); new_transform = get_transform(); //used as old to compute motion if (new_transform == t) break; _set_transform(t); _set_inv_transform(get_transform().inverse()); } wakeup(); } break; case PhysicsServer::<API key>: { /* if (mode==PhysicsServer::BODY_MODE_STATIC) break; */ linear_velocity = p_variant; wakeup(); } break; case PhysicsServer::<API key>: { /* if (mode!=PhysicsServer::BODY_MODE_RIGID) break; */ angular_velocity = p_variant; wakeup(); } break; case PhysicsServer::BODY_STATE_SLEEPING: { if (mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC) break; bool do_sleep = p_variant; if (do_sleep) { linear_velocity = Vector3(); //<API key>=Vector3(); angular_velocity = Vector3(); //<API key>=Vector3(); set_active(false); } else { if (mode != PhysicsServer::BODY_MODE_STATIC) set_active(true); } } break; case PhysicsServer::<API key>: { can_sleep = p_variant; if (mode == PhysicsServer::BODY_MODE_RIGID && !active && !can_sleep) set_active(true); } break; } } Variant BodySW::get_state(PhysicsServer::BodyState p_state) const { switch (p_state) { case PhysicsServer::<API key>: { return get_transform(); } break; case PhysicsServer::<API key>: { return linear_velocity; } break; case PhysicsServer::<API key>: { return angular_velocity; } break; case PhysicsServer::BODY_STATE_SLEEPING: { return !is_active(); } break; case PhysicsServer::<API key>: { return can_sleep; } break; } return Variant(); } void BodySW::set_space(SpaceSW *p_space) { if (get_space()) { if (inertia_update_list.in_list()) get_space()-><API key>(&inertia_update_list); if (active_list.in_list()) get_space()-><API key>(&active_list); if (<API key>.in_list()) get_space()-><API key>(&<API key>); } _set_space(p_space); if (get_space()) { _update_inertia(); if (active) get_space()-><API key>(&active_list); /* _update_queries(); if (is_active()) { active=false; set_active(true); } */ } first_integration = true; } void BodySW::<API key>(const AreaSW *p_area) { if (p_area->is_gravity_point()) { if (p_area-><API key>() > 0) { Vector3 v = p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin(); gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area-><API key>() + 1, 2)); } else { gravity += (p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin()).normalized() * p_area->get_gravity(); } } else { gravity += p_area->get_gravity_vector() * p_area->get_gravity(); } area_linear_damp += p_area->get_linear_damp(); area_angular_damp += p_area->get_angular_damp(); } void BodySW::integrate_forces(real_t p_step) { if (mode == PhysicsServer::BODY_MODE_STATIC) return; AreaSW *def_area = get_space()->get_default_area(); // AreaSW *damp_area = def_area; ERR_FAIL_COND(!def_area); int ac = areas.size(); bool stopped = false; gravity = Vector3(0, 0, 0); area_linear_damp = 0; area_angular_damp = 0; if (ac) { areas.sort(); const AreaCMP *aa = &areas[0]; // damp_area = aa[ac-1].area; for (int i = ac - 1; i >= 0 && !stopped; i PhysicsServer::<API key> mode = aa[i].area-><API key>(); switch (mode) { case PhysicsServer::<API key>: case PhysicsServer::<API key>: { <API key>(aa[i].area); stopped = mode == PhysicsServer::<API key>; } break; case PhysicsServer::<API key>: case PhysicsServer::<API key>: { gravity = Vector3(0, 0, 0); area_angular_damp = 0; area_linear_damp = 0; <API key>(aa[i].area); stopped = mode == PhysicsServer::<API key>; } break; default: {} } } } if (!stopped) { <API key>(def_area); } gravity *= gravity_scale; // If less than 0, override dampenings with that of the Body if (angular_damp >= 0) area_angular_damp = angular_damp; /* else area_angular_damp=damp_area->get_angular_damp(); */ if (linear_damp >= 0) area_linear_damp = linear_damp; /* else area_linear_damp=damp_area->get_linear_damp(); */ Vector3 motion; bool do_motion = false; if (mode == PhysicsServer::BODY_MODE_KINEMATIC) { //compute motion, angular and etc. velocities from prev transform linear_velocity = (new_transform.origin - get_transform().origin) / p_step; //compute a FAKE angular velocity, not so easy Basis rot = new_transform.basis.orthonormalized().transposed() * get_transform().basis.orthonormalized(); Vector3 axis; real_t angle; rot.get_axis_angle(axis, angle); axis.normalize(); angular_velocity = axis.normalized() * (angle / p_step); motion = new_transform.origin - get_transform().origin; do_motion = true; } else { if (!<API key> && !first_integration) { //overridden by direct state query Vector3 force = gravity * mass; force += applied_force; Vector3 torque = applied_torque; real_t damp = 1.0 - p_step * area_linear_damp; if (damp < 0) // reached zero in the given time damp = 0; real_t angular_damp = 1.0 - p_step * area_angular_damp; if (angular_damp < 0) // reached zero in the given time angular_damp = 0; linear_velocity *= damp; angular_velocity *= angular_damp; linear_velocity += _inv_mass * force * p_step; angular_velocity += _inv_inertia_tensor.xform(torque) * p_step; } if (continuous_cd) { motion = linear_velocity * p_step; do_motion = true; } } applied_force = Vector3(); applied_torque = Vector3(); first_integration = false; //motion=linear_velocity*p_step; <API key> = Vector3(); <API key> = Vector3(); if (do_motion) { //shapes temporarily extend for raycast <API key>(motion); } def_area = NULL; // clear the area, so it is set in the next frame contact_count = 0; } void BodySW::<API key>(real_t p_step) { if (mode == PhysicsServer::BODY_MODE_STATIC) return; if (fi_callback) get_space()-><API key>(&<API key>); if (mode == PhysicsServer::BODY_MODE_KINEMATIC) { _set_transform(new_transform, false); _set_inv_transform(new_transform.affine_inverse()); if (contacts.size() == 0 && linear_velocity == Vector3() && angular_velocity == Vector3()) set_active(false); //stopped moving, deactivate return; } //apply axis lock if (axis_lock != PhysicsServer::<API key>) { int axis = axis_lock - 1; for (int i = 0; i < 3; i++) { if (i == axis) { linear_velocity[i] = 0; <API key>[i] = 0; } else { angular_velocity[i] = 0; <API key>[i] = 0; } } } Vector3 <API key> = angular_velocity + <API key>; real_t ang_vel = <API key>.length(); Transform transform = get_transform(); if (ang_vel != 0.0) { Vector3 ang_vel_axis = <API key> / ang_vel; Basis rot(ang_vel_axis, ang_vel * p_step); Basis identity3(1, 0, 0, 0, 1, 0, 0, 0, 1); transform.origin += ((identity3 - rot) * transform.basis).xform(<API key>); transform.basis = rot * transform.basis; transform.orthonormalize(); } Vector3 <API key> = linear_velocity + <API key>; /*for(int i=0;i<3;i++) { if (axis_lock&(1<<i)) { transform.origin[i]=0.0; } }*/ transform.origin += <API key> * p_step; _set_transform(transform); _set_inv_transform(get_transform().inverse()); <API key>(); /* if (fi_callback) { get_space()-><API key>(&<API key>); */ } /* void BodySW::simulate_motion(const Transform& p_xform,real_t p_step) { Transform inv_xform = p_xform.affine_inverse(); if (!get_space()) { _set_transform(p_xform); _set_inv_transform(inv_xform); return; } //compute a FAKE linear velocity - this is easy linear_velocity=(p_xform.origin - get_transform().origin)/p_step; //compute a FAKE angular velocity, not so easy Matrix3 rot=get_transform().basis.orthonormalized().transposed() * p_xform.basis.orthonormalized(); Vector3 axis; real_t angle; rot.get_axis_angle(axis,angle); axis.normalize(); angular_velocity=axis.normalized() * (angle/p_step); linear_velocity = (p_xform.origin - get_transform().origin)/p_step; if (!<API key>.in_list())// - callalways, so lv and av are cleared && (state_query || direct_state_query)) get_space()-><API key>(&<API key>); simulated_motion=true; _set_transform(p_xform); } */ void BodySW::wakeup_neighbours() { for (Map<ConstraintSW *, int>::Element *E = constraint_map.front(); E; E = E->next()) { const ConstraintSW *c = E->key(); BodySW **n = c->get_body_ptr(); int bc = c->get_body_count(); for (int i = 0; i < bc; i++) { if (i == E->get()) continue; BodySW *b = n[i]; if (b->mode != PhysicsServer::BODY_MODE_RIGID) continue; if (!b->is_active()) b->set_active(true); } } } void BodySW::call_queries() { if (fi_callback) { <API key> *dbs = <API key>::singleton; dbs->body = this; Variant v = dbs; Object *obj = ObjectDB::get_instance(fi_callback->id); if (!obj) { <API key>(0, StringName()); } else { const Variant *vp[2] = { &v, &fi_callback->udata }; Variant::CallError ce; int argc = (fi_callback->udata.get_type() == Variant::NIL) ? 1 : 2; obj->call(fi_callback->method, vp, argc, ce); } } } bool BodySW::sleep_test(real_t p_step) { if (mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC) return true; else if (mode == PhysicsServer::BODY_MODE_CHARACTER) return !active; // characters don't sleep unless asked to sleep else if (!can_sleep) return false; if (Math::abs(angular_velocity.length()) < get_space()-><API key>() && Math::abs(linear_velocity.length_squared()) < get_space()-><API key>() * get_space()-><API key>()) { still_time += p_step; return still_time > get_space()-><API key>(); } else { still_time = 0; //maybe this should be set to 0 on set_active? return false; } } void BodySW::<API key>(ObjectID p_id, const StringName &p_method, const Variant &p_udata) { if (fi_callback) { memdelete(fi_callback); fi_callback = NULL; } if (p_id != 0) { fi_callback = memnew(<API key>); fi_callback->id = p_id; fi_callback->method = p_method; fi_callback->udata = p_udata; } } BodySW::BodySW() : CollisionObjectSW(TYPE_BODY), active_list(this), inertia_update_list(this), <API key>(this) { mode = PhysicsServer::BODY_MODE_RIGID; active = true; mass = 1; //_inv_inertia=Transform(); _inv_mass = 1; bounce = 0; friction = 1; <API key> = false; //applied_torque=0; island_step = 0; island_next = NULL; island_list_next = NULL; <API key> = false; first_integration = false; _set_static(false); contact_count = 0; gravity_scale = 1.0; linear_damp = -1; angular_damp = -1; area_angular_damp = 0; area_linear_damp = 0; still_time = 0; continuous_cd = false; can_sleep = false; fi_callback = NULL; axis_lock = PhysicsServer::<API key>; } BodySW::~BodySW() { if (fi_callback) memdelete(fi_callback); } <API key> *<API key>::singleton = NULL; <API key> *<API key>::get_space_state() { return body->get_space()->get_direct_state(); }
package cloudca import ( "encoding/json" "github.com/cloud-ca/go-cloudca/api" "github.com/cloud-ca/go-cloudca/services" ) type Service struct { Name string `json:"name,omitempty"` Capabilities map[string]interface{} `json:"capabilities,omitempty"` } type Network struct { Id string `json:"id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` VpcId string `json:"vpcId,omitempty"` NetworkOfferingId string `json:"networkOfferingId,omitempty"` NetworkAclId string `json:"networkAclId,omitempty"` NetworkAclName string `json:"networkAclName,omitempty"` ZoneId string `json:"zoneid,omitempty"` ZoneName string `json:"zonename,omitempty"` Cidr string `json:"cidr,omitempty"` Type string `json:"type,omitempty"` State string `json:"state,omitempty"` Gateway string `json:"gateway,omitempty"` IsSystem bool `json:"issystem,omitempty"` Domain string `json:"domain,omitempty"` DomainId string `json:"domainid,omitempty"` Project string `json:"project,omitempty"` ProjectId string `json:"projectid,omitempty"` Services []Service `json:"service,omitempty"` } type NetworkService interface { Get(id string) (*Network, error) List() ([]Network, error) ListOfVpc(vpcId string) ([]Network, error) ListWithOptions(options map[string]string) ([]Network, error) Create(network Network, options map[string]string) (*Network, error) Update(id string, network Network) (*Network, error) Delete(id string) (bool, error) ChangeAcl(id string, aclId string) (bool, error) } type NetworkApi struct { entityService services.EntityService } func NewNetworkService(apiClient api.ApiClient, serviceCode string, environmentName string) NetworkService { return &NetworkApi{ entityService: services.NewEntityService(apiClient, serviceCode, environmentName, NETWORK_ENTITY_TYPE), } } func parseNetwork(data []byte) *Network { network := Network{} json.Unmarshal(data, &network) return &network } func parseNetworkList(data []byte) []Network { networks := []Network{} json.Unmarshal(data, &networks) return networks } //Get network with the specified id for the current environment func (networkApi *NetworkApi) Get(id string) (*Network, error) { data, err := networkApi.entityService.Get(id, map[string]string{}) if err != nil { return nil, err } return parseNetwork(data), nil } //List all networks for the current environment func (networkApi *NetworkApi) List() ([]Network, error) { return networkApi.ListWithOptions(map[string]string{}) } //List all networks of a vpc for the current environment func (networkApi *NetworkApi) ListOfVpc(vpcId string) ([]Network, error) { return networkApi.ListWithOptions(map[string]string{ vpcId: vpcId, }) } //List all networks for the current environment. Can use options to do sorting and paging. func (networkApi *NetworkApi) ListWithOptions(options map[string]string) ([]Network, error) { data, err := networkApi.entityService.List(options) if err != nil { return nil, err } return parseNetworkList(data), nil } func (networkApi *NetworkApi) Create(network Network, options map[string]string) (*Network, error) { send, merr := json.Marshal(network) if merr != nil { return nil, merr } body, err := networkApi.entityService.Create(send, options) if err != nil { return nil, err } return parseNetwork(body), nil } func (networkApi *NetworkApi) Update(id string, network Network) (*Network, error) { send, merr := json.Marshal(network) if merr != nil { return nil, merr } body, err := networkApi.entityService.Update(id, send, map[string]string{}) if err != nil { return nil, err } return parseNetwork(body), nil } func (networkApi *NetworkApi) Delete(id string) (bool, error) { _, err := networkApi.entityService.Delete(id, []byte{}, map[string]string{}) return err == nil, err } func (networkApi *NetworkApi) ChangeAcl(id string, aclId string) (bool, error) { send, merr := json.Marshal(Network{ NetworkAclId: aclId, }) if merr != nil { return false, merr } _, err := networkApi.entityService.Execute(id, "replace", send, map[string]string{}) return err == nil, err }
> Resolve the path to the user's global .gitconfig. ## Install with [npm](npmjs.org) bash npm i git-config-path --save ## Usage js var gitConfigPath = require('git-config-path'); //=> '/Users/jonschlinkert/.gitconfig' ## Related projects * [parse-git-config](https://github.com/jonschlinkert/parse-git-config): Parse `.git/config` into a JavaScript object. sync or async. ## Running tests Install dev dependencies. bash npm i -d && npm test ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/git-config-path/issues) ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) Copyright (c) 2015 Jon Schlinkert Released under the MIT license *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on March 04, 2015._
var JobsList = React.createClass({displayName: "JobsList", getInitialState: function() { return { data: JobStore.getState(), } } , componentDidMount: function() { amplify.subscribe( 'JobStore.change', this._handleChange ) } , componentDidUnmound: function() { amplify.unsubscribe( 'JobStore.change', this._handleChange ) } , render: function() { var job = { 'title': 'Raphael', 'desc': 'abc' } return ( React.createElement(JobItem, {job: job}) ); } , _handleChange: function(data) { this.setState({data: data}) } }); var JobItem = React.createClass({displayName: "JobItem", render: function() { return ( React.createElement("div", {className: "panel panel-default"}, React.createElement("div", {className: "panel-heading"}, this.props.job.title), React.createElement("div", {className: "panel-body"}, this.props.job.desc ) ) ) } })
#!/bin/bash # install system dependencies: # - aspcud for opam (on OS X; installed via apt on Linux) # - awscli (to talk to AWS) # - modern node (for yarn and npm) # - yarn DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" case "$TRAVIS_OS_NAME" in osx) printf "travis_fold:start:brew_install\nInstalling brew\n" brew update brew install aspcud awscli yarn printf "travis_fold:end:brew_install\n" ;; *) ;; esac source "$DIR/setup_node.sh"
var _reactJsxDevRuntime = require("react/jsx-dev-runtime"); var _jsxFileName = "<CWD>\\packages\\<API key>\\test\\fixtures\\windows\\<API key>\\input.js"; var x = /*#__PURE__*/_reactJsxDevRuntime.jsxDEV(React.Fragment, {}, 'foo', false, { fileName: _jsxFileName, lineNumber: 1, columnNumber: 9 }, this);
import unittest from circular_buffer import ( CircularBuffer, BufferFullException, <API key> ) class CircularBufferTest(unittest.TestCase): def <API key>(self): buf = CircularBuffer(1) with self.assertRaises(<API key>): buf.read() def <API key>(self): buf = CircularBuffer(1) buf.write('1') self.assertEqual('1', buf.read()) with self.assertRaises(<API key>): buf.read() def <API key>(self): buf = CircularBuffer(2) buf.write('1') buf.write('2') self.assertEqual(buf.read(), '1') self.assertEqual(buf.read(), '2') with self.assertRaises(<API key>): buf.read() def <API key>(self): buf = CircularBuffer(3) for c in '123': buf.write(c) buf.clear() with self.assertRaises(<API key>): buf.read() buf.write('1') buf.write('2') self.assertEqual(buf.read(), '1') buf.write('3') self.assertEqual(buf.read(), '2') def <API key>(self): buf = CircularBuffer(2) buf.write('1') self.assertEqual(buf.read(), '1') buf.write('2') self.assertEqual(buf.read(), '2') def <API key>(self): buf = CircularBuffer(3) buf.write('1') buf.write('2') buf.read() buf.write('3') buf.read() self.assertEqual(buf.read(), '3') def <API key>(self): buf = CircularBuffer(2) buf.write('1') buf.write('2') with self.assertRaises(BufferFullException): buf.write('A') def <API key>(self): buf = CircularBuffer(2) buf.write('1') buf.write('2') buf.overwrite('A') self.assertEqual(buf.read(), '2') self.assertEqual(buf.read(), 'A') with self.assertRaises(<API key>): buf.read() def <API key>(self): buf = CircularBuffer(2) buf.overwrite('1') buf.overwrite('2') self.assertEqual(buf.read(), '1') self.assertEqual(buf.read(), '2') with self.assertRaises(<API key>): buf.read() def <API key>(self): buf = CircularBuffer(5) for c in '123': buf.write(c) buf.read() buf.read() buf.write('4') buf.read() for c in '5678': buf.write(c) buf.overwrite('A') buf.overwrite('B') self.assertEqual(buf.read(), '6') self.assertEqual(buf.read(), '7') self.assertEqual(buf.read(), '8') self.assertEqual(buf.read(), 'A') self.assertEqual(buf.read(), 'B') with self.assertRaises(<API key>): buf.read() if __name__ == '__main__': unittest.main()
package mn import ( "encoding/json" "errors" "fmt" "log" ) type Switch struct { Name string Ports Links Controller string } func (this Switch) String() string { out, err := json.MarshalIndent(this, "", " ") if err != nil { panic(err) } return string(out) } func NewSwitch(name ...string) (*Switch, error) { this := &Switch{ Name: "", Ports: make(Links, 0), } if len(name) == 0 || name[0] == "" { this.Name = switchname() } else { this.Name = name[0] } if this.Exists() { return this, nil } if err := this.Create(); err != nil { return this, err } return this, nil } func (this *Switch) UnmarshalJSON(b []byte) error { type tmp Switch s := tmp{} if err := json.Unmarshal(b, &s); err != nil { return err } this.Name = s.Name this.Ports = s.Ports if !this.Exists() { if err := this.Create(); err != nil { return err } } if s.Controller != "" { if err := this.SetController(s.Controller); err != nil { return err } } return nil } func (this *Switch) Create() error { out, err := RunCommand("ovs-vsctl", "add-br", this.Name) if err != nil { return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) } return nil } func (this *Switch) Exists() bool { _, err := RunCommand("ovs-vsctl", "br-exists", this.Name) return err == nil } func (this *Switch) AddLink(l Link) error { if l.patch { return this.AddPatchPort(l) } return this.AddPort(l) } func (this *Switch) AddPort(l Link) error { out, err := RunCommand("ovs-vsctl", "add-port", this.Name, l.Name) if err != nil { return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) } this.Ports = append(this.Ports, l) return nil } func (this *Switch) AddPatchPort(l Link) error { if out, err := RunCommand("ovs-vsctl", "add-port", this.NodeName(), l.Name); err != nil { return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) } if out, err := RunCommand("ovs-vsctl", "set", "interface", l.Name, "type=patch"); err != nil { return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) } if out, err := RunCommand("ovs-vsctl", "set", "interface", l.Name, "options:peer="+l.Peer.Name); err != nil { return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) } l = l.SetState("UP") this.Ports = append(this.Ports, l) return nil } func (this *Switch) SetController(addr string) error { if out, err := RunCommand("ovs-vsctl", "set-controller", this.NodeName(), addr); err != nil { return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) } // if out, err := RunCommand("ovs-vsctl", "set", "bridge", this.NodeName(), "protocols=OpenFlow13"); err != nil { // return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) // if out, err := RunCommand("ovs-vsctl", "set", "bridge", this.NodeName()); err != nil { // return errors.New(fmt.Sprintf("Error: %v, output: %s", err, out)) return nil } func (this Switch) Release() error { out, err := RunCommand("ovs-vsctl", "del-br", this.Name) if err != nil { log.Println("Unable to delete bridge", this.Name, err, out) } return nil } func (this Switch) NodeName() string { return this.Name } func (this Switch) NetNs() *NetNs { return nil } func (this Switch) LinksCount() int { return len(this.Ports) } func (this Switch) GetCidr(peer Peer) string { return this.Ports.LinkByPeer(peer).Cidr } func (this Switch) GetHwAddr(peer Peer) string { return this.Ports.LinkByPeer(peer).HwAddr } func (this Switch) GetState(peer Peer) string { return this.Ports.LinkByPeer(peer).State } func (this Switch) GetLinks() Links { return this.Ports }
#include "dcmtk/config/osconfig.h" #include "dcmtk/dcmjpeg/djdecext.h" #include "dcmtk/dcmjpeg/djcparam.h" #include "dcmtk/dcmjpeg/djrploss.h" #include "dcmtk/dcmjpeg/djdijg8.h" #include "dcmtk/dcmjpeg/djdijg12.h" DJDecoderExtended::DJDecoderExtended() : DJCodecDecoder() { } DJDecoderExtended::~DJDecoderExtended() { } E_TransferSyntax DJDecoderExtended::<API key>() const { return EXS_JPEGProcess2_4; } DJDecoder *DJDecoderExtended::<API key>( const <API key> * /* toRepParam */, const DJCodecParameter *cp, Uint8 bitsPerSample, OFBool isYBR) const { if (bitsPerSample > 8) return new <API key>(*cp, isYBR); else return new DJDecompressIJG8Bit(*cp, isYBR); }
var streams = require('./main') , assert = require('assert') , stream = require('stream') ; var source = new stream.Stream() , dest = new stream.Stream() , buffered = new streams.BufferedStream() ; source.readable = true dest.writable = true source.pause = function () { throw new Error("Pause should not be called") } source.pipe(buffered) var i = 0; while (i !== 100) { source.emit("data", "asdf") i++ } assert.ok(buffered.chunks.length === 100); i = 0; dest.write = function () { i++ } buffered.pipe(dest) assert.ok(i === 100);
#include <sys/queue.h> #include <stdio.h> #include <errno.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <stdarg.h> #include <inttypes.h> #include <rte_byteorder.h> #include <rte_common.h> #include <rte_pci.h> #include <rte_atomic.h> #include <rte_eal.h> #include <rte_ether.h> #include <ethdev_driver.h> #include <ethdev_pci.h> #include <rte_malloc.h> #include <rte_memzone.h> #include <rte_dev.h> #include "ice_dcf.h" #include "ice_rxtx.h" #define ICE_DCF_AQ_LEN 32 #define ICE_DCF_AQ_BUF_SZ 4096 #define <API key> 200 #define <API key> 2 /* msecs */ #define <API key> \ (sizeof(struct <API key>) + \ IAVF_MAX_VF_VSI * sizeof(struct <API key>)) static __rte_always_inline int <API key>(struct ice_dcf_hw *hw, enum virtchnl_ops op, uint8_t *req_msg, uint16_t req_msglen) { return <API key>(&hw->avf, op, IAVF_SUCCESS, req_msg, req_msglen, NULL); } static int <API key>(struct ice_dcf_hw *hw, enum virtchnl_ops op, uint8_t *rsp_msgbuf, uint16_t rsp_buflen, uint16_t *rsp_msglen) { struct iavf_arq_event_info event; enum virtchnl_ops v_op; int i = 0; int err; event.buf_len = rsp_buflen; event.msg_buf = rsp_msgbuf; do { err = <API key>(&hw->avf, &event, NULL); if (err != IAVF_SUCCESS) goto again; v_op = rte_le_to_cpu_32(event.desc.cookie_high); if (v_op != op) goto again; if (rsp_msglen != NULL) *rsp_msglen = event.msg_len; return rte_le_to_cpu_32(event.desc.cookie_low); again: rte_delay_ms(<API key>); } while (i++ < <API key>); return -EIO; } static __rte_always_inline void <API key>(struct ice_dcf_hw *hw, struct dcf_virtchnl_cmd *cmd) { rte_spinlock_lock(&hw->vc_cmd_queue_lock); TAILQ_REMOVE(&hw->vc_cmd_queue, cmd, next); rte_spinlock_unlock(&hw->vc_cmd_queue_lock); } static __rte_always_inline void ice_dcf_vc_cmd_set(struct ice_dcf_hw *hw, struct dcf_virtchnl_cmd *cmd) { cmd->v_ret = IAVF_ERR_NOT_READY; cmd->rsp_msglen = 0; cmd->pending = 1; rte_spinlock_lock(&hw->vc_cmd_queue_lock); TAILQ_INSERT_TAIL(&hw->vc_cmd_queue, cmd, next); rte_spinlock_unlock(&hw->vc_cmd_queue_lock); } static __rte_always_inline int ice_dcf_vc_cmd_send(struct ice_dcf_hw *hw, struct dcf_virtchnl_cmd *cmd) { return <API key>(&hw->avf, cmd->v_op, IAVF_SUCCESS, cmd->req_msg, cmd->req_msglen, NULL); } static __rte_always_inline void <API key>(struct ice_dcf_hw *hw, struct iavf_arq_event_info *info) { struct dcf_virtchnl_cmd *cmd; enum virtchnl_ops v_op; enum iavf_status v_ret; uint16_t aq_op; aq_op = rte_le_to_cpu_16(info->desc.opcode); if (unlikely(aq_op != <API key>)) { PMD_DRV_LOG(ERR, "Request %u is not supported yet", aq_op); return; } v_op = rte_le_to_cpu_32(info->desc.cookie_high); if (v_op == VIRTCHNL_OP_EVENT) { if (hw->vc_event_msg_cb != NULL) hw->vc_event_msg_cb(hw, info->msg_buf, info->msg_len); return; } v_ret = rte_le_to_cpu_32(info->desc.cookie_low); rte_spinlock_lock(&hw->vc_cmd_queue_lock); TAILQ_FOREACH(cmd, &hw->vc_cmd_queue, next) { if (cmd->v_op == v_op && cmd->pending) { cmd->v_ret = v_ret; cmd->rsp_msglen = RTE_MIN(info->msg_len, cmd->rsp_buflen); if (likely(cmd->rsp_msglen != 0)) rte_memcpy(cmd->rsp_msgbuf, info->msg_buf, cmd->rsp_msglen); /* prevent compiler reordering */ <API key>(); cmd->pending = 0; break; } } rte_spinlock_unlock(&hw->vc_cmd_queue_lock); } static void <API key>(struct ice_dcf_hw *hw) { struct iavf_arq_event_info info; uint16_t pending = 1; int ret; info.buf_len = ICE_DCF_AQ_BUF_SZ; info.msg_buf = hw->arq_buf; while (pending && !hw->resetting) { ret = <API key>(&hw->avf, &info, &pending); if (ret != IAVF_SUCCESS) break; <API key>(hw, &info); } } static int <API key>(struct ice_dcf_hw *hw) { #define <API key> 1 #define <API key> 1 struct <API key> version, *pver; int err; version.major = <API key>; version.minor = <API key>; err = <API key>(hw, VIRTCHNL_OP_VERSION, (uint8_t *)&version, sizeof(version)); if (err) { PMD_INIT_LOG(ERR, "Failed to send OP_VERSION"); return err; } pver = &hw->virtchnl_version; err = <API key>(hw, VIRTCHNL_OP_VERSION, (uint8_t *)pver, sizeof(*pver), NULL); if (err) { PMD_INIT_LOG(ERR, "Failed to get response of OP_VERSION"); return -1; } PMD_INIT_LOG(DEBUG, "Peer PF API version: %u.%u", pver->major, pver->minor); if (pver->major < <API key> || (pver->major == <API key> && pver->minor < <API key>)) { PMD_INIT_LOG(ERR, "VIRTCHNL API version should not be lower than (%u.%u)", <API key>, <API key>); return -1; } else if (pver->major > <API key> || (pver->major == <API key> && pver->minor > <API key>)) { PMD_INIT_LOG(ERR, "PF/VF API version mismatch:(%u.%u)-(%u.%u)", pver->major, pver->minor, <API key>, <API key>); return -1; } PMD_INIT_LOG(DEBUG, "Peer is supported PF host"); return 0; } static int <API key>(struct ice_dcf_hw *hw) { uint32_t caps; int err, i; caps = <API key> | <API key> | <API key> | VIRTCHNL_VF_CAP_DCF | <API key> | <API key> | <API key> | <API key>; err = <API key>(hw, <API key>, (uint8_t *)&caps, sizeof(caps)); if (err) { PMD_DRV_LOG(ERR, "Failed to send msg OP_GET_VF_RESOURCE"); return err; } err = <API key>(hw, <API key>, (uint8_t *)hw->vf_res, <API key>, NULL); if (err) { PMD_DRV_LOG(ERR, "Failed to get response of OP_GET_VF_RESOURCE"); return -1; } <API key>(&hw->avf, hw->vf_res); hw->vsi_res = NULL; for (i = 0; i < hw->vf_res->num_vsis; i++) { if (hw->vf_res->vsi_res[i].vsi_type == VIRTCHNL_VSI_SRIOV) hw->vsi_res = &hw->vf_res->vsi_res[i]; } if (!hw->vsi_res) { PMD_DRV_LOG(ERR, "no LAN VSI found"); return -1; } hw->vsi_id = hw->vsi_res->vsi_id; PMD_DRV_LOG(DEBUG, "VSI ID is %u", hw->vsi_id); return 0; } static int <API key>(struct ice_dcf_hw *hw) { struct <API key> *vsi_map; uint32_t valid_msg_len; uint16_t len; int err; err = <API key>(hw, <API key>, NULL, 0); if (err) { PMD_DRV_LOG(ERR, "Failed to send msg OP_DCF_GET_VSI_MAP"); return err; } err = <API key>(hw, <API key>, hw->arq_buf, ICE_DCF_AQ_BUF_SZ, &len); if (err) { PMD_DRV_LOG(ERR, "Failed to get response of OP_DCF_GET_VSI_MAP"); return err; } vsi_map = (struct <API key> *)hw->arq_buf; valid_msg_len = (vsi_map->num_vfs - 1) * sizeof(vsi_map->vf_vsi[0]) + sizeof(*vsi_map); if (len != valid_msg_len) { PMD_DRV_LOG(ERR, "invalid vf vsi map response with length %u", len); return -EINVAL; } if (hw->num_vfs != 0 && hw->num_vfs != vsi_map->num_vfs) { PMD_DRV_LOG(ERR, "The number VSI map (%u) doesn't match the number of VFs (%u)", vsi_map->num_vfs, hw->num_vfs); return -EINVAL; } len = vsi_map->num_vfs * sizeof(vsi_map->vf_vsi[0]); if (!hw->vf_vsi_map) { hw->vf_vsi_map = rte_zmalloc("vf_vsi_ctx", len, 0); if (!hw->vf_vsi_map) { PMD_DRV_LOG(ERR, "Failed to alloc memory for VSI context"); return -ENOMEM; } hw->num_vfs = vsi_map->num_vfs; hw->pf_vsi_id = vsi_map->pf_vsi; } if (!memcmp(hw->vf_vsi_map, vsi_map->vf_vsi, len)) { PMD_DRV_LOG(DEBUG, "VF VSI map doesn't change"); return 1; } rte_memcpy(hw->vf_vsi_map, vsi_map->vf_vsi, len); return 0; } static int <API key>(struct ice_dcf_hw *hw) { int err; if (hw->resetting) return 0; err = <API key>(hw, <API key>, NULL, 0); if (err) { PMD_DRV_LOG(ERR, "Failed to send msg OP_DCF_DISABLE"); return err; } err = <API key>(hw, <API key>, hw->arq_buf, ICE_DCF_AQ_BUF_SZ, NULL); if (err) { PMD_DRV_LOG(ERR, "Failed to get response of OP_DCF_DISABLE %d", err); return -1; } return 0; } static int <API key>(struct ice_dcf_hw *hw) { #define <API key> 50 struct iavf_hw *avf = &hw->avf; int i, reset; for (i = 0; i < <API key>; i++) { reset = IAVF_READ_REG(avf, IAVF_VFGEN_RSTAT) & <API key>; reset = reset >> <API key>; if (reset == <API key> || reset == <API key>) break; rte_delay_ms(20); } if (i >= <API key>) return -1; return 0; } static inline void ice_dcf_enable_irq0(struct ice_dcf_hw *hw) { struct iavf_hw *avf = &hw->avf; /* Enable admin queue interrupt trigger */ IAVF_WRITE_REG(avf, <API key>, <API key>); IAVF_WRITE_REG(avf, <API key>, <API key> | <API key> | <API key>); IAVF_WRITE_FLUSH(avf); } static inline void <API key>(struct ice_dcf_hw *hw) { struct iavf_hw *avf = &hw->avf; /* Disable all interrupt types */ IAVF_WRITE_REG(avf, <API key>, 0); IAVF_WRITE_REG(avf, <API key>, <API key>); IAVF_WRITE_FLUSH(avf); } static void <API key>(void *param) { struct ice_dcf_hw *hw = param; <API key>(hw); <API key>(hw); ice_dcf_enable_irq0(hw); } int <API key>(struct ice_dcf_hw *hw, struct dcf_virtchnl_cmd *cmd) { int i = 0; int err; if ((cmd->req_msg && !cmd->req_msglen) || (!cmd->req_msg && cmd->req_msglen) || (cmd->rsp_msgbuf && !cmd->rsp_buflen) || (!cmd->rsp_msgbuf && cmd->rsp_buflen)) return -EINVAL; rte_spinlock_lock(&hw->vc_cmd_send_lock); ice_dcf_vc_cmd_set(hw, cmd); err = ice_dcf_vc_cmd_send(hw, cmd); if (err) { PMD_DRV_LOG(ERR, "fail to send cmd %d", cmd->v_op); goto ret; } do { if (!cmd->pending) break; rte_delay_ms(<API key>); } while (i++ < <API key>); if (cmd->v_ret != IAVF_SUCCESS) { err = -1; PMD_DRV_LOG(ERR, "No response (%d times) or return failure (%d) for cmd %d", i, cmd->v_ret, cmd->v_op); } ret: <API key>(hw, cmd); rte_spinlock_unlock(&hw->vc_cmd_send_lock); return err; } int ice_dcf_send_aq_cmd(void *dcf_hw, struct ice_aq_desc *desc, void *buf, uint16_t buf_size) { struct dcf_virtchnl_cmd desc_cmd, buff_cmd; struct ice_dcf_hw *hw = dcf_hw; int err = 0; int i = 0; if ((buf && !buf_size) || (!buf && buf_size) || buf_size > ICE_DCF_AQ_BUF_SZ) return -EINVAL; desc_cmd.v_op = <API key>; desc_cmd.req_msglen = sizeof(*desc); desc_cmd.req_msg = (uint8_t *)desc; desc_cmd.rsp_buflen = sizeof(*desc); desc_cmd.rsp_msgbuf = (uint8_t *)desc; if (buf == NULL) return <API key>(hw, &desc_cmd); desc->flags |= rte_cpu_to_le_16(ICE_AQ_FLAG_BUF); buff_cmd.v_op = <API key>; buff_cmd.req_msglen = buf_size; buff_cmd.req_msg = buf; buff_cmd.rsp_buflen = buf_size; buff_cmd.rsp_msgbuf = buf; rte_spinlock_lock(&hw->vc_cmd_send_lock); ice_dcf_vc_cmd_set(hw, &desc_cmd); ice_dcf_vc_cmd_set(hw, &buff_cmd); if (ice_dcf_vc_cmd_send(hw, &desc_cmd) || ice_dcf_vc_cmd_send(hw, &buff_cmd)) { err = -1; PMD_DRV_LOG(ERR, "fail to send OP_DCF_CMD_DESC/BUFF"); goto ret; } do { if (!desc_cmd.pending && !buff_cmd.pending) break; rte_delay_ms(<API key>); } while (i++ < <API key>); if (desc_cmd.v_ret != IAVF_SUCCESS || buff_cmd.v_ret != IAVF_SUCCESS) { err = -1; PMD_DRV_LOG(ERR, "No response (%d times) or return failure (desc: %d / buff: %d)", i, desc_cmd.v_ret, buff_cmd.v_ret); } ret: <API key>(hw, &desc_cmd); <API key>(hw, &buff_cmd); rte_spinlock_unlock(&hw->vc_cmd_send_lock); return err; } int <API key>(struct ice_dcf_hw *hw) { struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(hw->eth_dev); int i = 0; int err = -1; rte_spinlock_lock(&hw->vc_cmd_send_lock); rte_intr_disable(pci_dev->intr_handle); <API key>(hw); for (;;) { if (<API key>(hw) == 0 && <API key>(hw) >= 0) { err = 0; break; } if (++i >= <API key>) break; rte_delay_ms(<API key>); } rte_intr_enable(pci_dev->intr_handle); ice_dcf_enable_irq0(hw); rte_spinlock_unlock(&hw->vc_cmd_send_lock); return err; } static int <API key>(struct ice_dcf_hw *hw) { int err; err = <API key>(hw, <API key>, NULL, 0); if (err) { PMD_INIT_LOG(ERR, "Failed to send <API key>"); return -1; } err = <API key>(hw, <API key>, (uint8_t *)&hw->supported_rxdid, sizeof(uint64_t), NULL); if (err) { PMD_INIT_LOG(ERR, "Failed to get response of <API key>"); return -1; } return 0; } int ice_dcf_init_hw(struct rte_eth_dev *eth_dev, struct ice_dcf_hw *hw) { struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev); int ret, size; hw->resetting = false; hw->avf.hw_addr = pci_dev->mem_resource[0].addr; hw->avf.back = hw; hw->avf.bus.bus_id = pci_dev->addr.bus; hw->avf.bus.device = pci_dev->addr.devid; hw->avf.bus.func = pci_dev->addr.function; hw->avf.device_id = pci_dev->id.device_id; hw->avf.vendor_id = pci_dev->id.vendor_id; hw->avf.subsystem_device_id = pci_dev->id.subsystem_device_id; hw->avf.subsystem_vendor_id = pci_dev->id.subsystem_vendor_id; hw->avf.aq.num_arq_entries = ICE_DCF_AQ_LEN; hw->avf.aq.num_asq_entries = ICE_DCF_AQ_LEN; hw->avf.aq.arq_buf_size = ICE_DCF_AQ_BUF_SZ; hw->avf.aq.asq_buf_size = ICE_DCF_AQ_BUF_SZ; rte_spinlock_init(&hw->vc_cmd_send_lock); rte_spinlock_init(&hw->vc_cmd_queue_lock); TAILQ_INIT(&hw->vc_cmd_queue); hw->arq_buf = rte_zmalloc("arq_buf", ICE_DCF_AQ_BUF_SZ, 0); if (hw->arq_buf == NULL) { PMD_INIT_LOG(ERR, "unable to allocate AdminQ buffer memory"); goto err; } ret = iavf_set_mac_type(&hw->avf); if (ret) { PMD_INIT_LOG(ERR, "set_mac_type failed: %d", ret); goto err; } ret = <API key>(hw); if (ret) { PMD_INIT_LOG(ERR, "VF is still resetting"); goto err; } ret = iavf_init_adminq(&hw->avf); if (ret) { PMD_INIT_LOG(ERR, "init_adminq failed: %d", ret); goto err; } if (<API key>(hw)) { PMD_INIT_LOG(ERR, "check_api version failed"); goto err_api; } hw->vf_res = rte_zmalloc("vf_res", <API key>, 0); if (hw->vf_res == NULL) { PMD_INIT_LOG(ERR, "unable to allocate vf_res memory"); goto err_api; } if (<API key>(hw)) { PMD_INIT_LOG(ERR, "Failed to get VF resource"); goto err_alloc; } if (<API key>(hw) < 0) { PMD_INIT_LOG(ERR, "Failed to get VF VSI map"); <API key>(hw); goto err_alloc; } /* Allocate memory for RSS info */ if (hw->vf_res->vf_cap_flags & <API key>) { hw->rss_key = rte_zmalloc(NULL, hw->vf_res->rss_key_size, 0); if (!hw->rss_key) { PMD_INIT_LOG(ERR, "unable to allocate rss_key memory"); goto err_alloc; } hw->rss_lut = rte_zmalloc("rss_lut", hw->vf_res->rss_lut_size, 0); if (!hw->rss_lut) { PMD_INIT_LOG(ERR, "unable to allocate rss_lut memory"); goto err_rss; } } if (hw->vf_res->vf_cap_flags & <API key>) { if (<API key>(hw) != 0) { PMD_INIT_LOG(ERR, "failed to do get supported rxdid"); goto err_rss; } } if (hw->vf_res->vf_cap_flags & <API key>) { <API key>(eth_dev); size = sizeof(struct <API key> *) * hw->num_vfs; hw->qos_bw_cfg = rte_zmalloc("qos_bw_cfg", size, 0); if (!hw->qos_bw_cfg) { PMD_INIT_LOG(ERR, "no memory for qos_bw_cfg"); goto err_rss; } } hw->eth_dev = eth_dev; <API key>(pci_dev->intr_handle, <API key>, hw); rte_intr_enable(pci_dev->intr_handle); ice_dcf_enable_irq0(hw); return 0; err_rss: rte_free(hw->rss_key); rte_free(hw->rss_lut); err_alloc: rte_free(hw->vf_res); err_api: <API key>(&hw->avf); err: rte_free(hw->arq_buf); return -1; } void ice_dcf_uninit_hw(struct rte_eth_dev *eth_dev, struct ice_dcf_hw *hw) { struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev); struct rte_intr_handle *intr_handle = pci_dev->intr_handle; if (hw->vf_res->vf_cap_flags & <API key>) if (hw->tm_conf.committed) { ice_dcf_clear_bw(hw); <API key>(eth_dev); } <API key>(hw); rte_intr_disable(intr_handle); <API key>(intr_handle, <API key>, hw); <API key>(hw); <API key>(&hw->avf); rte_free(hw->arq_buf); hw->arq_buf = NULL; rte_free(hw->vf_vsi_map); hw->vf_vsi_map = NULL; rte_free(hw->vf_res); hw->vf_res = NULL; rte_free(hw->rss_lut); hw->rss_lut = NULL; rte_free(hw->rss_key); hw->rss_key = NULL; rte_free(hw->qos_bw_cfg); hw->qos_bw_cfg = NULL; rte_free(hw->ets_config); hw->ets_config = NULL; } static int <API key>(struct ice_dcf_hw *hw) { struct virtchnl_rss_key *rss_key; struct dcf_virtchnl_cmd args; int len, err; len = sizeof(*rss_key) + hw->vf_res->rss_key_size - 1; rss_key = rte_zmalloc("rss_key", len, 0); if (!rss_key) return -ENOMEM; rss_key->vsi_id = hw->vsi_res->vsi_id; rss_key->key_len = hw->vf_res->rss_key_size; rte_memcpy(rss_key->key, hw->rss_key, hw->vf_res->rss_key_size); args.v_op = <API key>; args.req_msglen = len; args.req_msg = (uint8_t *)rss_key; args.rsp_msglen = 0; args.rsp_buflen = 0; args.rsp_msgbuf = NULL; args.pending = 0; err = <API key>(hw, &args); if (err) PMD_INIT_LOG(ERR, "Failed to execute OP_CONFIG_RSS_KEY"); rte_free(rss_key); return err; } static int <API key>(struct ice_dcf_hw *hw) { struct virtchnl_rss_lut *rss_lut; struct dcf_virtchnl_cmd args; int len, err; len = sizeof(*rss_lut) + hw->vf_res->rss_lut_size - 1; rss_lut = rte_zmalloc("rss_lut", len, 0); if (!rss_lut) return -ENOMEM; rss_lut->vsi_id = hw->vsi_res->vsi_id; rss_lut->lut_entries = hw->vf_res->rss_lut_size; rte_memcpy(rss_lut->lut, hw->rss_lut, hw->vf_res->rss_lut_size); args.v_op = <API key>; args.req_msglen = len; args.req_msg = (uint8_t *)rss_lut; args.rsp_msglen = 0; args.rsp_buflen = 0; args.rsp_msgbuf = NULL; args.pending = 0; err = <API key>(hw, &args); if (err) PMD_INIT_LOG(ERR, "Failed to execute OP_CONFIG_RSS_LUT"); rte_free(rss_lut); return err; } int ice_dcf_init_rss(struct ice_dcf_hw *hw) { struct rte_eth_dev *dev = hw->eth_dev; struct rte_eth_rss_conf *rss_conf; uint8_t i, j, nb_q; int ret; rss_conf = &dev->data->dev_conf.rx_adv_conf.rss_conf; nb_q = dev->data->nb_rx_queues; if (!(hw->vf_res->vf_cap_flags & <API key>)) { PMD_DRV_LOG(DEBUG, "RSS is not supported"); return -ENOTSUP; } if (dev->data->dev_conf.rxmode.mq_mode != RTE_ETH_MQ_RX_RSS) { PMD_DRV_LOG(WARNING, "RSS is enabled by PF by default"); /* set all lut items to default queue */ memset(hw->rss_lut, 0, hw->vf_res->rss_lut_size); return <API key>(hw); } /* In IAVF, RSS enablement is set by PF driver. It is not supported * to set based on rss_conf->rss_hf. */ /* configure RSS key */ if (!rss_conf->rss_key) /* Calculate the default hash key */ for (i = 0; i < hw->vf_res->rss_key_size; i++) hw->rss_key[i] = (uint8_t)rte_rand(); else rte_memcpy(hw->rss_key, rss_conf->rss_key, RTE_MIN(rss_conf->rss_key_len, hw->vf_res->rss_key_size)); /* init RSS LUT table */ for (i = 0, j = 0; i < hw->vf_res->rss_lut_size; i++, j++) { if (j >= nb_q) j = 0; hw->rss_lut[i] = j; } /* send virtchnl ops to configure RSS */ ret = <API key>(hw); if (ret) return ret; ret = <API key>(hw); if (ret) return ret; return 0; } #define IAVF_RXDID_LEGACY_0 0 #define IAVF_RXDID_LEGACY_1 1 #define <API key> 22 int <API key>(struct ice_dcf_hw *hw) { struct ice_rx_queue **rxq = (struct ice_rx_queue **)hw->eth_dev->data->rx_queues; struct ice_tx_queue **txq = (struct ice_tx_queue **)hw->eth_dev->data->tx_queues; struct <API key> *vc_config; struct <API key> *vc_qp; struct dcf_virtchnl_cmd args; uint16_t i, size; int err; size = sizeof(*vc_config) + sizeof(vc_config->qpair[0]) * hw->num_queue_pairs; vc_config = rte_zmalloc("cfg_queue", size, 0); if (!vc_config) return -ENOMEM; vc_config->vsi_id = hw->vsi_res->vsi_id; vc_config->num_queue_pairs = hw->num_queue_pairs; for (i = 0, vc_qp = vc_config->qpair; i < hw->num_queue_pairs; i++, vc_qp++) { vc_qp->txq.vsi_id = hw->vsi_res->vsi_id; vc_qp->txq.queue_id = i; if (i < hw->eth_dev->data->nb_tx_queues) { vc_qp->txq.ring_len = txq[i]->nb_tx_desc; vc_qp->txq.dma_ring_addr = txq[i]->tx_ring_dma; } vc_qp->rxq.vsi_id = hw->vsi_res->vsi_id; vc_qp->rxq.queue_id = i; if (i >= hw->eth_dev->data->nb_rx_queues) continue; vc_qp->rxq.max_pkt_size = rxq[i]->max_pkt_len; vc_qp->rxq.ring_len = rxq[i]->nb_rx_desc; vc_qp->rxq.dma_ring_addr = rxq[i]->rx_ring_dma; vc_qp->rxq.databuffer_size = rxq[i]->rx_buf_len; #ifndef <API key> if (hw->vf_res->vf_cap_flags & <API key> && hw->supported_rxdid & BIT(<API key>)) { vc_qp->rxq.rxdid = <API key>; PMD_DRV_LOG(NOTICE, "request RXDID == %d in " "Queue[%d]", vc_qp->rxq.rxdid, i); } else { PMD_DRV_LOG(ERR, "RXDID 16 is not supported"); return -EINVAL; } #else if (hw->vf_res->vf_cap_flags & <API key> && hw->supported_rxdid & BIT(IAVF_RXDID_LEGACY_0)) { vc_qp->rxq.rxdid = IAVF_RXDID_LEGACY_0; PMD_DRV_LOG(NOTICE, "request RXDID == %d in " "Queue[%d]", vc_qp->rxq.rxdid, i); } else { PMD_DRV_LOG(ERR, "RXDID == 0 is not supported"); return -EINVAL; } #endif <API key>(rxq[i], vc_qp->rxq.rxdid); } memset(&args, 0, sizeof(args)); args.v_op = <API key>; args.req_msg = (uint8_t *)vc_config; args.req_msglen = size; err = <API key>(hw, &args); if (err) PMD_DRV_LOG(ERR, "Failed to execute command of" " <API key>"); rte_free(vc_config); return err; } int <API key>(struct ice_dcf_hw *hw) { struct <API key> *map_info; struct virtchnl_vector_map *vecmap; struct dcf_virtchnl_cmd args; int len, i, err; len = sizeof(struct <API key>) + sizeof(struct virtchnl_vector_map) * hw->nb_msix; map_info = rte_zmalloc("map_info", len, 0); if (!map_info) return -ENOMEM; map_info->num_vectors = hw->nb_msix; for (i = 0; i < hw->nb_msix; i++) { vecmap = &map_info->vecmap[i]; vecmap->vsi_id = hw->vsi_res->vsi_id; vecmap->rxitr_idx = 0; vecmap->vector_id = hw->msix_base + i; vecmap->txq_map = 0; vecmap->rxq_map = hw->rxq_map[hw->msix_base + i]; } memset(&args, 0, sizeof(args)); args.v_op = <API key>; args.req_msg = (u8 *)map_info; args.req_msglen = len; err = <API key>(hw, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command OP_CONFIG_IRQ_MAP"); rte_free(map_info); return err; } int <API key>(struct ice_dcf_hw *hw, uint16_t qid, bool rx, bool on) { struct <API key> queue_select; struct dcf_virtchnl_cmd args; int err; memset(&queue_select, 0, sizeof(queue_select)); queue_select.vsi_id = hw->vsi_res->vsi_id; if (rx) queue_select.rx_queues |= 1 << qid; else queue_select.tx_queues |= 1 << qid; memset(&args, 0, sizeof(args)); if (on) args.v_op = <API key>; else args.v_op = <API key>; args.req_msg = (u8 *)&queue_select; args.req_msglen = sizeof(queue_select); err = <API key>(hw, &args); if (err) PMD_DRV_LOG(ERR, "Failed to execute command of %s", on ? "OP_ENABLE_QUEUES" : "OP_DISABLE_QUEUES"); return err; } int <API key>(struct ice_dcf_hw *hw) { struct <API key> queue_select; struct dcf_virtchnl_cmd args; int err; if (hw->resetting) return 0; memset(&queue_select, 0, sizeof(queue_select)); queue_select.vsi_id = hw->vsi_res->vsi_id; queue_select.rx_queues = BIT(hw->eth_dev->data->nb_rx_queues) - 1; queue_select.tx_queues = BIT(hw->eth_dev->data->nb_tx_queues) - 1; memset(&args, 0, sizeof(args)); args.v_op = <API key>; args.req_msg = (u8 *)&queue_select; args.req_msglen = sizeof(queue_select); err = <API key>(hw, &args); if (err) PMD_DRV_LOG(ERR, "Failed to execute command of OP_DISABLE_QUEUES"); return err; } int ice_dcf_query_stats(struct ice_dcf_hw *hw, struct virtchnl_eth_stats *pstats) { struct <API key> q_stats; struct dcf_virtchnl_cmd args; int err; memset(&q_stats, 0, sizeof(q_stats)); q_stats.vsi_id = hw->vsi_res->vsi_id; args.v_op = <API key>; args.req_msg = (uint8_t *)&q_stats; args.req_msglen = sizeof(q_stats); args.rsp_msglen = sizeof(*pstats); args.rsp_msgbuf = (uint8_t *)pstats; args.rsp_buflen = sizeof(*pstats); err = <API key>(hw, &args); if (err) { PMD_DRV_LOG(ERR, "fail to execute command OP_GET_STATS"); return err; } return 0; } int <API key>(struct ice_dcf_hw *hw, bool add) { struct <API key> *list; struct rte_ether_addr *addr; struct dcf_virtchnl_cmd args; int len, err = 0; if (hw->resetting) { if (!add) return 0; PMD_DRV_LOG(ERR, "fail to add all MACs for VF resetting"); return -EIO; } len = sizeof(struct <API key>); addr = hw->eth_dev->data->mac_addrs; len += sizeof(struct virtchnl_ether_addr); list = rte_zmalloc(NULL, len, 0); if (!list) { PMD_DRV_LOG(ERR, "fail to allocate memory"); return -ENOMEM; } rte_memcpy(list->list[0].addr, addr->addr_bytes, sizeof(addr->addr_bytes)); PMD_DRV_LOG(DEBUG, "add/rm mac:" <API key>, <API key>(addr)); list->vsi_id = hw->vsi_res->vsi_id; list->num_elements = 1; memset(&args, 0, sizeof(args)); args.v_op = add ? <API key> : <API key>; args.req_msg = (uint8_t *)list; args.req_msglen = len; err = <API key>(hw, &args); if (err) PMD_DRV_LOG(ERR, "fail to execute command %s", add ? "<API key>" : "<API key>"); rte_free(list); return err; }
<?php namespace Anomaly\TagsFieldType\Validation; use Anomaly\Streams\Platform\Ui\Form\FormBuilder; class FilterValidator { /** * Handle the validation. * * @param FormBuilder $builder * @param $attribute * @param $value * @return bool */ public function handle(FormBuilder $builder, $attribute, $value) { $field = $builder-><API key>($attribute); $filters = (array)array_get($field->getConfig(), 'filter', []); if (!$filters || !$value) { return true; } foreach ($value as $tag) { $passes = true; foreach ($filters as $filter) { if (!$this->passes($tag, $filter)) { $passes = false; } } if (!$passes) { return false; } } return true; } /** * Return if a tag passes the filter. * * @param $tag * @param $filter * @return bool */ protected function passes($tag, $filter) { if (str_contains($filter, '*')) { return str_contains($tag, $filter); } switch ($filter) { case '<API key>': return filter_var($tag, <API key>) !== false; case 'FILTER_VALIDATE_URL': return filter_var($tag, FILTER_VALIDATE_URL) !== false; case 'FILTER_VALIDATE_IP': return filter_var($tag, FILTER_VALIDATE_IP) !== false; default: return true; } } }
module Shoulda module Matchers module ActionController # @private class RouteParams PARAMS_TO_SYMBOLIZE = %i{ format } def initialize(args) @args = args end def normalize if <API key>? <API key> else stringify_params end end protected attr_reader :args def <API key>? args[0].is_a?(String) end def <API key> controller, action = args[0].split(' params = (args[1] || {}).merge(controller: controller, action: action) normalize_values(params) end def stringify_params normalize_values(args[0]) end def normalize_values(hash) hash.each_with_object({}) do |(key, value), hash_copy| hash_copy[key] = <API key>(key, value) end end def <API key>(key, value) if PARAMS_TO_SYMBOLIZE.include?(key) value.to_sym else stringify(value) end end def stringify(value) if value.is_a?(Array) value.map(&:to_param) else value.to_param end end end end end end
require 'spec_helper' describe Gatherer::Expansion do it "can be created with a title" do expansion = Gatherer::Expansion.new(title: "Phelddagrif") expansion.title.should == "Phelddagrif" end it "can be created with an abbreviation" do expansion = Gatherer::Expansion.new(abbreviation: "DRP") expansion.abbreviation.should == "DRP" end end
if (Object.const_defined?("Formtastic") && Gem.loaded_specs["formtastic"].version.version[0,1].to_i > 1) class RichInput < ::Formtastic::Inputs::TextInput def to_html scope_type = object_name scope_id = object.id editor_options = Rich.options(options[:config], scope_type, scope_id) input_wrapping do label_html << builder.text_area(method, input_html_options) << "<script>CKEDITOR.replace('#{dom_id}', #{editor_options.to_json.html_safe});</script>".html_safe end end end end
# Be sure to restart your server when you modify this file. # Your secret key is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # You can use `rake secret` to generate a secure secret key. # Make sure your secret_key_base is kept private # if you're sharing your code publicly. Rubygamedev::Application.config.secret_key_base = '467c33ca9481c483179ae5a517d6530d64e5b31c6719de4e509e8f882b870008d79adcce034c70fc5cdd4ab102f949bad2134a9a3bb5d91332052ff2e2b71652'
# -*- coding: utf-8 -*- from __future__ import print_function # Form implementation generated from reading ui file './acq4/devices/MockClamp/devTemplate.ui' # Created: Thu May 29 10:20:36 2014 # by: PyQt4 UI code generator 4.9.4 # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MockClampDevGui(object): def setupUi(self, MockClampDevGui): MockClampDevGui.setObjectName(_fromUtf8("MockClampDevGui")) MockClampDevGui.resize(459, 243) self.gridLayout = QtGui.QGridLayout(MockClampDevGui) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.groupBox_2 = QtGui.QGroupBox(MockClampDevGui) self.groupBox_2.setObjectName(_fromUtf8("groupBox_2")) self.gridLayout_3 = QtGui.QGridLayout(self.groupBox_2) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.vcModeRadio = QtGui.QRadioButton(self.groupBox_2) self.vcModeRadio.setObjectName(_fromUtf8("vcModeRadio")) self.horizontalLayout.addWidget(self.vcModeRadio) self.i0ModeRadio = QtGui.QRadioButton(self.groupBox_2) self.i0ModeRadio.setObjectName(_fromUtf8("i0ModeRadio")) self.horizontalLayout.addWidget(self.i0ModeRadio) self.icModeRadio = QtGui.QRadioButton(self.groupBox_2) self.icModeRadio.setObjectName(_fromUtf8("icModeRadio")) self.horizontalLayout.addWidget(self.icModeRadio) self.gridLayout_3.addLayout(self.horizontalLayout, 0, 0, 1, 2) self.label_3 = QtGui.QLabel(self.groupBox_2) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout_3.addWidget(self.label_3, 1, 0, 1, 1) self.vcHoldingSpin = SpinBox(self.groupBox_2) self.vcHoldingSpin.setObjectName(_fromUtf8("vcHoldingSpin")) self.gridLayout_3.addWidget(self.vcHoldingSpin, 1, 1, 1, 1) self.label_4 = QtGui.QLabel(self.groupBox_2) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout_3.addWidget(self.label_4, 2, 0, 1, 1) self.icHoldingSpin = SpinBox(self.groupBox_2) self.icHoldingSpin.setObjectName(_fromUtf8("icHoldingSpin")) self.gridLayout_3.addWidget(self.icHoldingSpin, 2, 1, 1, 1) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_3.addItem(spacerItem, 4, 0, 1, 1) self.label_6 = QtGui.QLabel(self.groupBox_2) self.label_6.setObjectName(_fromUtf8("label_6")) self.gridLayout_3.addWidget(self.label_6, 3, 0, 1, 1) self.pipOffsetSpin = SpinBox(self.groupBox_2) self.pipOffsetSpin.setObjectName(_fromUtf8("pipOffsetSpin")) self.gridLayout_3.addWidget(self.pipOffsetSpin, 3, 1, 1, 1) self.gridLayout.addWidget(self.groupBox_2, 0, 0, 1, 1) self.groupBox = QtGui.QGroupBox(MockClampDevGui) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.gridLayout_2 = QtGui.QGridLayout(self.groupBox) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.label = QtGui.QLabel(self.groupBox) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1) self.pipCapSpin = SpinBox(self.groupBox) self.pipCapSpin.setObjectName(_fromUtf8("pipCapSpin")) self.gridLayout_2.addWidget(self.pipCapSpin, 0, 1, 1, 2) self.label_2 = QtGui.QLabel(self.groupBox) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_2.addWidget(self.label_2, 1, 0, 1, 1) self.pipResSpin = SpinBox(self.groupBox) self.pipResSpin.setObjectName(_fromUtf8("pipResSpin")) self.gridLayout_2.addWidget(self.pipResSpin, 1, 1, 1, 2) self.label_5 = QtGui.QLabel(self.groupBox) self.label_5.setObjectName(_fromUtf8("label_5")) self.gridLayout_2.addWidget(self.label_5, 2, 0, 1, 1) self.pipJunctPotSpin = SpinBox(self.groupBox) self.pipJunctPotSpin.setObjectName(_fromUtf8("pipJunctPotSpin")) self.gridLayout_2.addWidget(self.pipJunctPotSpin, 2, 1, 1, 2) self.pipBathRadio = QtGui.QRadioButton(self.groupBox) self.pipBathRadio.setObjectName(_fromUtf8("pipBathRadio")) self.gridLayout_2.addWidget(self.pipBathRadio, 3, 0, 1, 3) self.pipAttachRadio = QtGui.QRadioButton(self.groupBox) self.pipAttachRadio.setObjectName(_fromUtf8("pipAttachRadio")) self.gridLayout_2.addWidget(self.pipAttachRadio, 5, 0, 1, 2) self.pipWholeRadio = QtGui.QRadioButton(self.groupBox) self.pipWholeRadio.setObjectName(_fromUtf8("pipWholeRadio")) self.gridLayout_2.addWidget(self.pipWholeRadio, 5, 2, 1, 1) spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_2.addItem(spacerItem1, 6, 0, 1, 1) self.comboBox = QtGui.QComboBox(self.groupBox) self.comboBox.setObjectName(_fromUtf8("comboBox")) self.comboBox.addItem(_fromUtf8("")) self.comboBox.addItem(_fromUtf8("")) self.comboBox.addItem(_fromUtf8("")) self.gridLayout_2.addWidget(self.comboBox, 4, 1, 1, 2) self.label_7 = QtGui.QLabel(self.groupBox) self.label_7.setObjectName(_fromUtf8("label_7")) self.gridLayout_2.addWidget(self.label_7, 4, 0, 1, 1) self.gridLayout.addWidget(self.groupBox, 0, 1, 1, 1) self.retranslateUi(MockClampDevGui) QtCore.QMetaObject.connectSlotsByName(MockClampDevGui) def retranslateUi(self, MockClampDevGui): MockClampDevGui.setWindowTitle(QtGui.QApplication.translate("MockClampDevGui", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_2.setTitle(QtGui.QApplication.translate("MockClampDevGui", "Clamp", None, QtGui.QApplication.UnicodeUTF8)) self.vcModeRadio.setText(QtGui.QApplication.translate("MockClampDevGui", "VC", None, QtGui.QApplication.UnicodeUTF8)) self.i0ModeRadio.setText(QtGui.QApplication.translate("MockClampDevGui", "I=0", None, QtGui.QApplication.UnicodeUTF8)) self.icModeRadio.setText(QtGui.QApplication.translate("MockClampDevGui", "IC", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("MockClampDevGui", "VC Holding", None, QtGui.QApplication.UnicodeUTF8)) self.label_4.setText(QtGui.QApplication.translate("MockClampDevGui", "IC Holding", None, QtGui.QApplication.UnicodeUTF8)) self.label_6.setText(QtGui.QApplication.translate("MockClampDevGui", "Pipette Offset", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox.setTitle(QtGui.QApplication.translate("MockClampDevGui", "Pipette", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MockClampDevGui", "Capacitance", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("MockClampDevGui", "Resistance", None, QtGui.QApplication.UnicodeUTF8)) self.label_5.setText(QtGui.QApplication.translate("MockClampDevGui", "Junct. Pot.", None, QtGui.QApplication.UnicodeUTF8)) self.pipBathRadio.setText(QtGui.QApplication.translate("MockClampDevGui", "Bath", None, QtGui.QApplication.UnicodeUTF8)) self.pipAttachRadio.setText(QtGui.QApplication.translate("MockClampDevGui", "On Cell", None, QtGui.QApplication.UnicodeUTF8)) self.pipWholeRadio.setText(QtGui.QApplication.translate("MockClampDevGui", "Whole Cell", None, QtGui.QApplication.UnicodeUTF8)) self.comboBox.setItemText(0, QtGui.QApplication.translate("MockClampDevGui", "HH", None, QtGui.QApplication.UnicodeUTF8)) self.comboBox.setItemText(1, QtGui.QApplication.translate("MockClampDevGui", "Type II", None, QtGui.QApplication.UnicodeUTF8)) self.comboBox.setItemText(2, QtGui.QApplication.translate("MockClampDevGui", "Type I", None, QtGui.QApplication.UnicodeUTF8)) self.label_7.setText(QtGui.QApplication.translate("MockClampDevGui", "Cell", None, QtGui.QApplication.UnicodeUTF8)) from acq4.pyqtgraph import SpinBox