answer
stringlengths
15
1.25M
window.joypad2rouesID = 0; (function() { var joypad2rouesWidget = function (settings) { var self = this; var thisjoypad2rouesID = window.joypad2rouesID++; var titleElement = $('<h2 class="section-title"></h2>'); var joypad2rouesElement = $('<div id="joypad2roues-' + thisjoypad2rouesID + '" style="margin-left: 50px;"></div>' + '<span id="value1_legend-' + thisjoypad2rouesID + '">Consigne vitesse longitudinale (cm/s): </span>' + '<span id="value1-' + thisjoypad2rouesID + '">0</span><br />' + '<span id="value2_legend-' + thisjoypad2rouesID + '">Consigne vitesse de rotation (deg/s): </span>' + '<span id="value2-' + thisjoypad2rouesID + '">0</span><br />'); var joypad2rouesObject; var rendered = false; var joypad2roues; var currentSettings = settings; var vxref = 0; var xiref = 0; // var socket; // var event; // function discardSocket() { // // Disconnect datasource websocket // if (socket) { // socket.disconnect(); // function connectToServer(mySettings) { // // If the communication is on serial port, the event name is the serial port name, // // otherwise it is 'message' // // Get the type (serial port or socket) and the settings // var hostDatasourceType = freeboard.getDatasourceType(mySettings.datasourcename); // var <API key> = freeboard.<API key>(mySettings.datasourcename); // if (hostDatasourceType == "serialport") { // // Get the name of serial port (on Linux based OS, take the name after the last /) // event = (<API key>.port).split("/").pop(); // else if (hostDatasourceType == "websocket") { // // Type = socket // event = 'message'; // else { // alert(_t("Datasource type not supported by this widget")); // socket = io.connect(host,{'forceNew':true}); // // Events // socket.on('connect', function() { // console.info("Connecting to server at: %s", host); // socket.on('connect_error', function(object) { // console.error("It was not possible to connect to server at: %s", host); // socket.on('reconnect_error', function(object) { // console.error("Still was not possible to re-connect to server at: %s", host); // socket.on('reconnect_failed', function(object) { // console.error("Re-connection to server failed at: %s", host); // discardSocket(); function sendData() { // Send data // console.log("vxref: ", vxref); // console.log("xiref: ", xiref); toSend = {}; toSend[currentSettings.variablevxref] = parseInt(vxref.toFixed(0)); //socket.emit(event, JSON.stringify(toSend)); sessionStorage.setItem(currentSettings.variablevxref, toSend[currentSettings.variablevxref]); toSend = {}; toSend[currentSettings.variablexiref] = parseInt(xiref.toFixed(0)); //socket.emit(event, JSON.stringify(toSend)); sessionStorage.setItem(currentSettings.variablexiref, toSend[currentSettings.variablexiref]); } function createjoypad2roues(mySettings) { if (!rendered) { return; } //connectToServer(mySettings); //joypad2rouesElement.empty(); gain_longi = (_.isUndefined(mySettings.gain_longi) ? 1 : mySettings.gain_longi); gain_rot = (_.isUndefined(mySettings.gain_rot) ? 1 : mySettings.gain_rot); // In case the Raphael paper already exists, we remove it try{ joypad2roues.remove(); } catch (error) { console.log(error); console.log("It seems that the paper doesn't exist yet..."); } joypad2roues = Raphael('joypad2roues-' + thisjoypad2rouesID, 170, 170); joypad2roues.image("./img/joypad_fond.png", 5, 5, 160, 160); joypad2roues.image("./img/joypad_exclusion.png", 0, 0, 170, 170); var <API key> = joypad2roues.image("./img/joypad_centre.png", 0, 0, 170, 170); // Send data at the creation sendData(); cart2pol = function(x,y) { var r, theta; r = Math.sqrt(Math.pow(x,2)+Math.pow(y,2)); theta = -Math.atan2(y,x); return {r: r, theta: theta}; }; pol2cart = function (r,theta) { var x, y; x = r*Math.cos(-theta); y = r*Math.sin(-theta); return {x: x, y: y}; }; dragger = function () { this.ox = this.attr("x"); this.oy = this.attr("y"); }; move = function (dx, dy) { var att, pol, r, theta, cart; pol = cart2pol(this.ox + dx,this.oy + dy); if (pol.r < 65) { att = {x: this.ox + dx, y: this.oy + dy}; this.attr(att); } else { cart = pol2cart(65, pol.theta); att = {x: cart.x, y: cart.y}; this.attr(att); } vxref_calc = pol.r; vxref_calc = Math.min(vxref_calc,70); vxref_calc = Math.max(vxref_calc-30,0); vxref_calc = vxref_calc*0.5/40; xiref_calc = (pol.theta*180/Math.PI); if (xiref_calc<0) { xiref_calc = 90; vxref_calc = -vxref_calc; } vxref = gain_longi * 100*(vxref_calc.toFixed(2)); $("#value1-" + thisjoypad2rouesID).html(vxref.toFixed(0)); xiref = gain_rot * (-(180. - 2. * xiref_calc)); $("#value2-" + thisjoypad2rouesID).html(xiref.toFixed(0)); sendData(); }; up = function () { att = {x: 0, y: 0}; this.animate(att,1000,"backOut"); vxref = 0; xiref = 0; $("#value1-" + thisjoypad2rouesID).html(vxref.toFixed(0)); $("#value2-" + thisjoypad2rouesID).html(xiref.toFixed(0)); sendData(); }; <API key>.drag(move, dragger, up); } this.render = function (element) { rendered = true; $(element).append(titleElement).append(joypad2rouesElement); createjoypad2roues(currentSettings); }; this.onSettingsChanged = function (newSettings) { // if (newSettings.datasourcename != currentSettings.datasourcename) { // discardSocket(); // connectToServer(newSettings); currentSettings = newSettings; createjoypad2roues(currentSettings); titleElement.html(currentSettings.title); }; this.<API key> = function (settingName, newValue) { }; this.onDispose = function () { //socket.close(); }; this.getHeight = function () { return 4; }; this.onSettingsChanged(settings); }; freeboard.loadWidgetPlugin({ type_name: "joypad2roues", display_name: "Joypad 2 roues", "external_scripts": [ "extensions/thirdparty/raphael.2.1.0.min.js" //"extensions/thirdparty/socket.io-1.3.5.js" ], settings: [ { name: "title", display_name: "Title", type: "text" }, // name: "datasourcename", // display_name: _t("Datasource"), // type: "text", // description: _t("You *must* create first a datasource with the same name") { name: "variablevxref", display_name: _t("Variable vxref"), type: "calculated", description: _t("Variable correspondant à la consigne de vitesse longitudinale") }, { name: "gain_longi", display_name: _t("Gain en longitudinal"), type: "text", default_value: 1, description: _t("Facteur de multiplication sur la consigne longitudinale. Celle-ci vaut 0.5 m/s au maximum quand le gain est égal à 1") }, { name: "variablexiref", display_name: _t("Variable xiref"), type: "calculated", description: _t("Variable correspondant à la consigne de vitesse de rotation") }, { name: "gain_rot", display_name: _t("Gain en rotation"), type: "text", default_value: 1, description: _t("Facteur de multiplication sur la consigne de rotation. Celle-ci est comprise entre -180 et 180 deg/s quand le gain est égal à 1") } ], newInstance: function (settings, newInstanceCallback) { newInstanceCallback(new joypad2rouesWidget(settings)); } }); }());
using System; using System.Diagnostics; using System.Windows.Forms; using WaveEngine.Adapter; namespace ProgressBarSample { static class Program { [STAThread] static void Main() { using (App game = new App()) { game.Run(); } } } }
package br.augustoicaro.pathfindercombat.models; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.<API key>; import javax.xml.parsers.<API key>; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import br.augustoicaro.pathfindercombat.Log; import br.augustoicaro.pathfindercombat.modifier.ModifierBase; import br.augustoicaro.pathfindercombat.modifier.ModifierFactory; public class Toggles { private static final String TAG = "PFCombat"; public static List<ModifierBase> loadToggles(InputStream xml) { List<ModifierBase> modifiers = new ArrayList<ModifierBase>(); try { DocumentBuilder builder = <API key>.newInstance().newDocumentBuilder(); Document doc = builder.parse(xml, null); NodeList condition_nodes = doc.<API key>("toggle"); for (int i = 0; i < condition_nodes.getLength(); i++) { Element elm = (Element)condition_nodes.item(i); Log.d(TAG, "Toggles: Adding toggle with name = " + elm.getAttribute("name")); modifiers.add(ModifierFactory.create(elm.getAttribute("name"))); } } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return modifiers; } }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Categories extends ActiveRecord\Model {} /* End of file Categories.php */ /* Location: ./application/models/Categories.php */
<!doctype html> <html lang="en" ng-app="phonecatApp"> <head> <meta charset="utf-8"> <title>Google Phone Gallery</title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="css/app.css"> <link rel="stylesheet" href="css/animations.css"> <script src="bower_components/jquery/jquery.js"></script> <script src="bower_components/angular/angular.js"></script> <script type="text/javascript" src="js/ui-bootstrap-tpls-0.11.0.min.js"></script> <script src="bower_components/angular-animate/angular-animate.js"></script> <script src="bower_components/angular-route/angular-route.js"></script> <script src="bower_components/angular-resource/angular-resource.js"></script> <script src="js/app.js"></script> <script src="js/animations.js"></script> <script src="js/controllers.js"></script> <script src="js/filters.js"></script> <script src="js/services.js"></script> <script src="js/navbar.js"></script> <script type="text/javascript" src="js/other.js"></script> <script src="js/modal_instance_ctrl.js"></script> </head> <body> <div class="navbar-wrapper"> <div class="container"> <div class="navbar navbar-inverse navbar-static-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Google photo gallery</a> </div> <div ng-controller='NavbarController'> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li ng-class="{active:isSet(1) }"><a href="#" ng-click="setTab(1)"> Home </a></li> <li ng-class="{active:isSet(2) }"><a href="#/about-us" ng-click="setTab(2)"> About </a></li> <li ng-class="{active:isSet(3) }"><a href="#/contact-us" ng-click="setTab(3)"> Contact </a></li> </ul> </div> </div> </div> </div> </div> </div> <div class="view-container"> <div ng-view class="view-frame col-md-10 centering"></div> </div> </body> </html>
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VerySimpleData { public class <API key> : DynamicObject { private readonly Dictionary<string, object> _data; public <API key>() :this(new Dictionary<string, object>()) { } public <API key>(Dictionary<string, object> data) { _data = data; } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (_data.ContainsKey(binder.Name)) { result = _data[binder.Name]; return true; } return base.TryGetMember(binder, out result); } public override bool TrySetMember(SetMemberBinder binder, object value) { _data[binder.Name] = value; return true; } public int ColumnCount { get { return _data.Count; } } } }
{% extends 'common/_base.html' %} {% block local_includes %} {% load sass_tags %} {% load static %} <link href="https://fonts.googleapis.com/css?family=Pangolin" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js" integrity="sha256-7/yoZS3548fXSRXqc/<API key>=" crossorigin="anonymous"> </script> {# <script src="/static/js/public/family-tree.js?ver=1.0"></script>#} <script src="{% static 'js/public/family-tree.js' %}?ver=1.1"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<API key>" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% sass_src 'css/public/family_tree.scss' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'css/lib/<API key>.min.css' %}"/> {% endblock %} {% block title %}Sigma Pi Gamma Iota - Family Tree{% endblock %} {% block body_class %}family-tree{% endblock %} {% block body %} <div class="tree-tools container-fluid"> <div class="row"> <div class="col-4 tree-back"> <a href="{% url '<API key>' %}" class="sp-button">Back to Sigma Pi</a> </div> <div class="col-4 tree-title">Sigma Pi Gamma Iota Family Tree</div> <div class="col-4 tree-tips">Drag to pan, Scroll to zoom</div> </div> </div> <div id="tree-container"> <canvas id="tree"></canvas> </div> <div class="tree-loading"> <div class="<API key>"> <div></div> <div></div> <div></div> <div></div> <div></div> </div> <p> Loading Family Tree </p> </div> {% endblock %}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Livet; using OxyPlot; using OxyPlot.Series; using OxyPlot.Axes; using System.Collections.ObjectModel; namespace WpfEventViewer.Models { public class GraphModel : NotificationObject { #region PlotData private PlotModel _PlotData; public PlotModel PlotData { get { return _PlotData; } set { if (_PlotData == value) return; _PlotData = value; <API key>(); } } #endregion public GraphModel() { this.PlotData = new PlotModel(); } public void UpdatePlotData(<API key><DateObject> calendarItems) { / //var item = new PlotModel { Title = "" }; //var infoSeries = new LineSeries { Title = "", MarkerType = MarkerType.Circle }; //var warnSeries = new LineSeries { Title = "", MarkerType = MarkerType.Square }; //var errorSeries = new LineSeries { Title = "", MarkerType = MarkerType.Triangle }; / / //foreach(var calendarItem in calendarItems) // infoSeries.Points.Add(new DataPoint(calendarItem.Date.Day, calendarItem.InformationCount)); // warnSeries.Points.Add(new DataPoint(calendarItem.Date.Day, calendarItem.WarningCount)); // errorSeries.Points.Add(new DataPoint(calendarItem.Date.Day, calendarItem.ErrorCount)); //item.Series.Add(infoSeries); //item.Series.Add(warnSeries); //item.Series.Add(errorSeries); //this.PlotData = item; var items = new Collection<DayItem>(); foreach(var calendarItem in calendarItems) { if (!calendarItem.ThisMonthMember) continue; items.Add(new DayItem { Label = $"{calendarItem.Date.Day.ToString()}({calendarItem.Date.ToString("ddd")})", InfoCount = calendarItem.InformationCount, WarnCount = calendarItem.WarningCount, ErrorCount = calendarItem.ErrorCount, }); } var item = new PlotModel { Title = "", LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.RightTop, LegendOrientation = LegendOrientation.Vertical, }; item.Axes.Add(new CategoryAxis { ItemsSource = items, LabelField = "Label" }); item.Axes.Add(new LinearAxis { Position = AxisPosition.Left, MinimumPadding = 0, AbsoluteMinimum = 0 }); item.Series.Add(new ColumnSeries { Title = "", ItemsSource = items, ValueField = "InfoCount" }); item.Series.Add(new ColumnSeries { Title = "", ItemsSource = items, ValueField = "WarnCount" }); item.Series.Add(new ColumnSeries { Title = "", ItemsSource = items, ValueField = "ErrorCount" }); this.PlotData = item; } private class DayItem { public string Label { get; set; } public int InfoCount { get; set; } public int WarnCount { get; set; } public int ErrorCount { get; set; } } } }
// --skip-worktree export var CONSUMER_KEY:string = 'KEY'; export var CONSUMER_SECRET:string = 'SECRET';
package com.flightstats.http; import com.flightstats.util.Part; import com.flightstats.util.UUIDGenerator; import com.github.rholder.retry.RetryException; import com.github.rholder.retry.Retryer; import com.google.common.base.Charsets; import com.google.common.base.Throwables; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.io.ByteStreams; import com.google.gson.Gson; import org.apache.http.*; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.<API key>; import org.apache.http.client.methods.*; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.<API key>; import org.apache.http.message.BasicNameValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.io.<API key>; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import static com.flightstats.http.HttpException.Details; import static java.util.stream.Collectors.toList; public class HttpTemplate { public static final ContentType MULTIPART_MIXED = ContentType.create("multipart/mixed", Charsets.UTF_8); public static final String APPLICATION_JSON = "application/json"; public static final Logger logger = LoggerFactory.getLogger(HttpTemplate.class); private final HttpClient client; private final UUIDGenerator uuidGenerator; private final Optional<Gson> gson; private final Retryer<Response> retryer; private final String defaultContentType; private final String acceptType; public HttpTemplate(HttpClient client, Retryer<Response> retryer, String contentType, String acceptType) { this.client = client; this.gson = Optional.empty(); this.retryer = retryer; this.defaultContentType = contentType; this.acceptType = acceptType; this.uuidGenerator = new UUIDGenerator(); } @Inject public HttpTemplate(HttpClient client, Gson gson, Retryer<Response> retryer, UUIDGenerator uuidGenerator) { this.client = client; this.uuidGenerator = uuidGenerator; this.gson = Optional.ofNullable(gson); this.retryer = retryer; this.defaultContentType = APPLICATION_JSON; this.acceptType = APPLICATION_JSON; } public <T> T get(String hostUrl, String path, Function<String, T> responseCreator, NameValuePair... queryParams) { URI uri; try { uri = new URIBuilder(hostUrl).setPath(path).setParameters(queryParams).build(); } catch (URISyntaxException e) { throw new RuntimeException(e); } return get(uri, responseCreator); } public <T> T get(String uri, Function<String, T> responseCreator) { return get(URI.create(uri), responseCreator); } public <T> T get(URI uri, Function<String, T> responseCreator) { AtomicReference<T> result = new AtomicReference<>(); get(uri, (Response response) -> { if (isFailedStatusCode(response.getCode())) { throw new HttpException(new Details(response.getCode(), "Get failed to: " + uri + ". response: " + response)); } result.set(responseCreator.apply(response.getBodyString())); }); return result.get(); } public int get(String uri, Consumer<Response> responseConsumer) { return get(URI.create(uri), responseConsumer).getCode(); } public Response get(URI uri) { return get(uri, (Response c) -> { }); } public Response get(URI uri, Consumer<Response> responseConsumer) { return get(uri, responseConsumer, Collections.emptyMap()); } public Response get(URI uri, Consumer<Response> responseConsumer, Map<String, String> extraHeaders) { HttpGet request = new HttpGet(uri); addExtraHeaders(request, extraHeaders); return handleRequest(request, responseConsumer); } public Response get(URI uri, Map<String, String> extraHeaders) { return get(uri, res -> { }, extraHeaders); } private void addExtraHeaders(HttpRequestBase request, Map<String, String> extraHeaders) { extraHeaders.entrySet() .stream() .filter(e -> !e.getKey().equalsIgnoreCase("Content-Type")) .forEach(entry -> request.setHeader(entry.getKey(), entry.getValue())); } public Response head(URI uri) { return head(uri, true); } public Response head(String uri) { return head(uri, true); } public Response head(String uri, boolean followRedirects) { return head(URI.create(uri), followRedirects); } public Response head(URI uri, boolean followRedirects) { HttpHead httpHead = new HttpHead(uri); if (!followRedirects) { httpHead.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build()); } return handleRequest(httpHead, x -> { }); } public <T> T get(URI uri, Type type) { if (!gson.isPresent()) { throw new <API key>("Must provide gson for deserializion"); } return get(uri, (String body) -> gson.get().fromJson(body, type)); } public String getSimple(String uri) { return get(uri, (Function<String, String>) s -> s); } private Response handleRequest(HttpRequestBase request, Consumer<Response> responseConsumer) { request.setHeader("Accept", acceptType); try { Response response = retryer.call(() -> convertHttpResponse(client.execute(request))); responseConsumer.accept(response); return response; } catch (ExecutionException | RetryException e) { throw new RuntimeException(e); } finally { request.reset(); } } private Response convertHttpResponse(HttpResponse httpResponse) throws IOException { int statusCode = httpResponse.getStatusLine().getStatusCode(); byte[] body = new byte[0]; HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream content = entity.getContent(); body = ByteStreams.toByteArray(content); } return new Response(statusCode, body, mapHeaders(httpResponse)); } private Multimap<String, String> mapHeaders(HttpResponse response) { Header[] headers = response.getAllHeaders(); ListMultimap<String, Header> headersByName = Multimaps.index(Arrays.asList(headers), Header::getName); return Multimaps.transformValues(headersByName, Header::getValue); } public int <API key>(String fullUri, Object bodyToPost, Consumer<Response> responseConsumer) { String bodyEntity = convertBodyToString(bodyToPost); Response response = executePost(fullUri, responseConsumer, defaultContentType, new StringEntity(bodyEntity, Charsets.UTF_8)); return response.getCode(); } private Response executePost(String fullUri, String contentType, HttpEntity entity) throws Exception { return executePost(fullUri, contentType, entity, Collections.emptyMap()); } private Response executePost(String fullUri, String contentType, HttpEntity entity, Map<String, String> extraHeaders) throws Exception { return executePost(fullUri, x -> { }, contentType, entity, extraHeaders); } private Response executePost(String fullUri, Consumer<Response> responseConsumer, String contentType, HttpEntity entity) { return executePost(fullUri, responseConsumer, contentType, entity, Collections.emptyMap()); } private Response executePost(String fullUri, Consumer<Response> responseConsumer, String contentType, HttpEntity entity, Map<String, String> extraHeaders) { HttpPost httpPost = new HttpPost(fullUri); addExtraHeaders(httpPost, extraHeaders); return execute(httpPost, responseConsumer, contentType, entity); } private Response executePut(String fullUri, Consumer<Response> responseConsumer, String contentType, HttpEntity entity) throws Exception { HttpPut httpPut = new HttpPut(fullUri); return execute(httpPut, responseConsumer, contentType, entity); } private Response execute(<API key> httpRequest, String contentType, HttpEntity entity) throws IOException { return execute(httpRequest, x -> { }, contentType, entity); } private Response execute(<API key> httpRequest, Consumer<Response> responseConsumer, String contentType, HttpEntity entity) { try { return retryer.call(() -> { try { httpRequest.setHeader("Content-Type", contentType); httpRequest.setHeader("Accept", acceptType); httpRequest.setEntity(entity); HttpResponse httpResponse = client.execute(httpRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); byte[] body = ByteStreams.toByteArray(httpResponse.getEntity().getContent()); if (<API key>(statusCode)) { logger.error("Internal server error, status code " + statusCode); throw new HttpException(new Details(statusCode, httpRequest.getMethod() + " failed to: " + httpRequest.getURI() + ". Status = " + statusCode + ", message = " + new String(body))); } Response response = new Response(statusCode, body, mapHeaders(httpResponse)); responseConsumer.accept(response); return response; } finally { httpRequest.reset(); } }); } catch (ExecutionException | RetryException e) { throw new RuntimeException(e); } } private boolean isFailedStatusCode(int responseStatusCode) { return (HttpStatus.SC_OK > responseStatusCode) || (responseStatusCode > HttpStatus.SC_NO_CONTENT); } private boolean <API key>(int responseStatusCode) { return 502 <= responseStatusCode && responseStatusCode <= 504; } private String convertBodyToString(Object bodyToPost) { if (gson.isPresent()) { return gson.get().toJson(bodyToPost); } else { return String.valueOf(bodyToPost); } } public Response post(URI uri, byte[] bytes, String contentType) { return post(uri, bytes, contentType, new HashMap<>()); } public Response post(URI uri, byte[] bytes, String contentType, Map<String, String> extraHeaders) { HashMap<String, String> headers = new HashMap<>(extraHeaders); headers.put("Content-Type", contentType); return post(uri, bytes, headers); } public Response post(URI uri, byte[] bytes, Map<String, String> extraHeaders) { try { return executePost(uri.toString(), extraHeaders.getOrDefault("Content-Type", defaultContentType), new ByteArrayEntity(bytes), extraHeaders); } catch (Exception e) { throw new RuntimeException(e); } } /** * Fire &amp; Forget...don't care about the response at all. */ public void post(String fullUri, Object bodyToPost) { postWithResponse(fullUri, bodyToPost, httpResponse -> { }); } /** * Post, and return the response body as a String. */ public String postSimple(String fullUri, Object bodyToPost) { return post(fullUri, bodyToPost, s -> s); } public Response postMultipart(String uri, List<Part> parts) { return postMultipart(uri, parts, Optional.<String>empty()); } public Response postMultipart(String uri, List<Part> parts, Optional<String> separator) { return postMultipart(uri, parts, separator, Optional.empty()); } public Response postMultipart(String uri, List<Part> parts, Optional<String> separator, Optional<ContentType> contentType) { try { HttpEntity multipartEntity = <API key>(parts, separator, contentType); return executePost(uri, multipartEntity.getContentType().getValue(), multipartEntity); } catch (Exception e) { throw new RuntimeException(e); } } public <T> T post(String fullUri, Object bodyToPost, Function<String, T> responseConverter) { AtomicReference<T> result = new AtomicReference<>(); postWithResponse(fullUri, bodyToPost, (Response response) -> result.set(responseConverter.apply(response.getBodyString()))); return result.get(); } public Response put(URI uri, byte[] bytes, String contentType) { try { HttpPut httpPut = new HttpPut(uri.toString()); return execute(httpPut, contentType, new ByteArrayEntity(bytes)); } catch (Exception e) { throw new RuntimeException(e); } } public Response put(URI uri, Object body) { return put(uri, convertBodyToString(body).getBytes(Charsets.UTF_8), defaultContentType); } /** * todo: this needs a better name, but different than "post", so it doesn't collide with the other one. I hate type erasure! */ public Response postWithResponse(String fullUri, Object bodyToPost, Consumer<Response> responseConsumer) { String bodyEntity = convertBodyToString(bodyToPost); Response response = executePost(fullUri, responseConsumer, defaultContentType, new StringEntity(bodyEntity, Charsets.UTF_8)); if (isFailedStatusCode(response.getCode())) { throw new HttpException(new Details(response.getCode(), "Post failed to: " + fullUri + ". response: " + response)); } return response; } /** * Note: does not use the Retryer. Todo: change it so that it does. */ public int postSimpleHtmlForm(String fullUri, Map<String, String> formValues) throws Exception { List<NameValuePair> nameValuePairs = formValues.entrySet().stream() .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())) .collect(toList()); HttpPost httpPost = new HttpPost(fullUri); try { httpPost.setEntity(new <API key>(nameValuePairs)); HttpResponse response = client.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (isFailedStatusCode(statusCode)) { throw new HttpException(new Details(statusCode, "Post failed to: " + fullUri)); } return statusCode; } finally { httpPost.reset(); } } public Response delete(URI uri) { try { return retryer.call(() -> { HttpDelete delete = new HttpDelete(uri); try { try { HttpResponse response = client.execute(delete); return convertHttpResponse(response); } catch (IOException e) { throw new <API key>("Error issuing DELETE against " + uri, e); } } finally { delete.reset(); } }); } catch (ExecutionException | RetryException e) { throw new RuntimeException(e); } } private HttpEntity <API key>(List<Part> parts, Optional<String> separator, Optional<ContentType> contentType) { <API key> entityBuilder = <API key>.create(); //If we dont set the content type, the lib will set the default. if (contentType.isPresent()) { entityBuilder.setContentType(contentType.get()); } entityBuilder.setBoundary(separator.orElse("fava_" + uuidGenerator.generateUUID())); parts.forEach(part -> entityBuilder.addTextBody(part.getName(), part.getContent(), ContentType.parse(part.getContentType()))); return entityBuilder.build(); } }
<?php include 'header.php' ?> <script> SHOT.albums = <?= json_encode($this->albums) ?>; </script> <div class="row"> <div class="large-12 columns"> <ul class="thumbnail-grid"></ul> <p class="page-placeholder"> No albums have been created yet </p> </div> </div> <?php include 'templates/album.php' ?> <?php include 'templates/docks/albums.php' ?> <?php include 'templates/modals/albums/create.php' ?> <?php include 'footer.php' ?>
package net.krinsoft.autorepair.util; /** * * @author krinsdeath */ public class Parser { public static String getType(String input) { if (input.contains("WOOD") || input.contains("BOW")) { return "wood"; } if (input.contains("STONE")) { return "stone"; } if (input.contains("IRON") || input.contains("SHEARS")) { return "iron"; } if (input.contains("GOLD")) { return "gold"; } if (input.contains("DIAMOND")) { return "diamond"; } if (input.contains("LEATHER")) { return "leather"; } if (input.contains("CHAINMAIL")) { return "chainmail"; } return null; } public static String getTool(String input) { if (input.contains("BOW")) { return "bow"; } if (input.contains("HOE")) { return "hoe"; } if (input.contains("SPADE")) { return "spade"; } if (input.contains("SWORD")) { return "sword"; } if (input.contains("PICKAXE")) { return "pickaxe"; } if (input.contains("AXE")) { return "axe"; } if (input.contains("SHEARS")) { return "shears"; } if (input.contains("HELMET")) { return "helmet"; } if (input.contains("CHESTPLATE")) { return "chestplate"; } if (input.contains("LEGGINGS")) { return "leggings"; } if (input.contains("BOOTS")) { return "boots"; } return null; } }
// // FILE: usbmsc.h // TITLE: Generic types and defines use by the mass storage class // // $TI Release: F2837xS Support Library v210 $ // modification, are permitted provided that the following conditions // are met: // documentation and/or other materials provided with the // distribution. // Neither the name of Texas Instruments Incorporated nor the names of // its contributors may be used to endorse or promote products derived // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // 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. // #ifndef __USBMSC_H__ #define __USBMSC_H__
# VectorJs [![Join the chat at https: [![Travis testing](https: A 2D Vector class for JavaScript. That's it! ## Installation `$ npm install vectorjs` Building `$ npm run build` `$ npm run test` ## Usage javascript var Vector = require('vectorjs'); var a = new Vector(2, 2); var b = new Vector(5, 3); var ab = a.add(b); console.log(ab); // => { x: 7, y: 5 } Usage without `new` is also supported javascript var a = new Vector(2, 2); // works the same as var a = Vector(2, 2); Methods None of the methods are mutable, which means that they wont modify the caller, but rather return a new `Vector` # .add(amount): Vector Returns the vector sum of the two vectors `amount` can be either a `Number` or a `Vector` # .sub(amount): Vector Returns caller subtracted by the amount `amount` can be either a `Number` or a `Vector` # .mul(amount): Vector Returns the result of caller multiplied by the amount `amount` being either a `Number` or a `Vector` # .div(amount): Vector Returns the result of caller divided by the amount `amount` being either a `Number` or a `Vector` # .len(): Number Returns the length of the Vector. Alternatively use .lenSq() # .lenSq(): Number Returns the squared length of the Vector. Useful for comparing two vectors # .normalize(): Vector Returns the normal of the Vector. This is a unit sized Vector # .angle(other): Number Returns the angle between calle and `other` in degrees. Alias for `.angleDeg()` `other` being the other vector # .angleDeg(other): Number Returns the angle between calle and `other` in degrees. Returns the same as `.angle()` `other` being the other vector # .angleRad(other): Number Returns the angle between calle and `other` in radian. `other` being the other vector # .clone(): Vector Returns the a copy or clone of the vector # .equals(other): Boolean Returns whether the `x` and `y` of the vectors are the same. This is here since JavaScript is weird and doesn't do. javascript { x: 2, y: 3 } === { x: 2, y: 3 } // => false Vector.equals({ x: 2, y: 3 }, { x: 2, y: 3 }) // => true They have their reasons. `other` being the other vector All of these functions can also be called from the class it self, as shown below. javascript a.add(b) <=> Vector.add(a, b) a.len() <=> Vector.len(a) // etc... ## Motivation In the past weeks, I've wrote multiple vector classes for every single one of my games, each with a different implementation. I needed something that was as simple as `v(2, 1).add(3)` and was easy to install. If you're looking for a super high performance vector library for rendering thousands of particles, this one might not be the one. Although if you do, [send it to me please](mailto:lvrmlbvng@gmail.com)! ## Misconceptions The source it self is written in `ES6`, but is transpiled to pure `ES5` and is ready to be required and used without a precompiler nor transpiler. ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## Credits Thanks to [timoxley](https://github.com/timoxley/to-factory) for supporting me with a wrapper for class to factory. Thanks to [Tribuadore](http: The MIT License (MIT)
from collections import defaultdict, namedtuple import regex as re from gary import ignore_parens_list Record = namedtuple('Record', ['dob', 'eng', 'pos', 'phn']) @ignore_parens_list def split_words(text:str) -> list: return re.split('\s*;\s*', text) class ShParser: def __init__(self, text): self.entries = [] pattern = re.compile('^\\\\(\w+)\s+(.*)$') self.entries = [] curr = defaultdict(list) for line in text.splitlines(): match = pattern.search(line) if match and not match[1].startswith('_'): if match[1].strip() == 'lx' and len(curr) > 0: self.entries.append(curr) curr = defaultdict(list) curr['lx'] = match[2] curr['ps'] = '' if match[1] == 'ps': if len(curr['ge']) > 0: self.entries.append(curr) curr['ge'] = [] curr['ps'] = match[2] if match[1] == 'ge': word_list = split_words(match[2]) for word in word_list: curr['ge'].append(word) def getEntries(self): for entry in self.entries: if 'lx' in entry: dob = entry['lx'] else: dob = '' eng = '‣'.join( entry['ge']) pos = entry['ps'] phn = entry['ph'] yield Record(dob,eng,pos,phn)
<?php namespace Benoth\StaticReflection\Tests\ReflectionFunctions; use Benoth\StaticReflection\Tests\AbstractTestCase; class <API key> extends AbstractTestCase { protected $function; public function setUp() { parent::setUp(); $this->context->parseFile($this->fixturesPath.'/WithNamespace/Functions/SimpleFunction.php'); $this->function = $this->index->getFunction('Benoth\StaticReflection\Tests\Fixtures\WithNamespace\Functions\SimpleFunction'); } public function testGetFileName() { $this->assertSame($this->fixturesPath.'/WithNamespace/Functions/SimpleFunction.php', $this->function->getFileName()); } public function testGetParameters() { $this->assertCount(1, $this->function->getParameters()); $this-><API key>('Benoth\StaticReflection\Reflection\ReflectionParameter', $this->function->getParameters()); } }
import styled from 'styled-components'; import Color from 'color'; import { colorOnBackground } from '../../../util/css-helpers'; import Navigation from '../Navigation'; const StyledNavigation = styled(Navigation)` display: block; height: 50px; width: 100%; margin: 0 0 1em 0; padding: 0; nav { position: fixed; top: 0; z-index: 1; display: inline-flex; flex-direction: columns; align-items: flex-start; @media (max-width: ${props => props.theme.breakpoints.s}px) { justify-content: space-around; } width: 100%; background: ${props => Color(props.theme.colors.primary).grayscale().hex()}; transition: top 0.2s ease-in-out; } nav.hide { top: -60px; } a { display: block; text-decoration: none; color: inherit; } a:hover, a:focus { color: ${props => props.theme.colors.secondary}; cursor: pointer; } a:hover svg, a:focus svg { fill: ${props => props.theme.colors.secondary}; } a.nav-active svg { fill: ${props => props.theme.colors.secondary}; } svg { height: 40px; width: 40px; margin: 5px; fill: ${props => colorOnBackground(Color(props.theme.colors.primary).grayscale().hex(), props.theme.alphaLightText.primary, props.theme.alphaDarkText.primary)}; } `; export default StyledNavigation;
import numpy as np import pandas as pd from emulator.env_factor import get_factors turnovers = pd.read_excel('emulator/SH50.xls', sheetname='total_turnover') opens = pd.read_excel('emulator/SH50.xls', sheetname='open') closes = pd.read_excel('emulator/SH50.xls', sheetname='close') highs = pd.read_excel('emulator/SH50.xls', sheetname='high') lows = pd.read_excel('emulator/SH50.xls', sheetname='low') universe = ['600048.XSHG', '601601.XSHG', '600887.XSHG', '600109.XSHG', '601186.XSHG', '600030.XSHG', '601169.XSHG', '601398.XSHG', '601088.XSHG', '600028.XSHG', '601336.XSHG', '601901.XSHG', '600050.XSHG', '600000.XSHG', '600485.XSHG', '601288.XSHG', '601377.XSHG', '600029.XSHG', '601198.XSHG', '601211.XSHG', '600893.XSHG', '600547.XSHG', '601668.XSHG', '601166.XSHG', '600100.XSHG', '601006.XSHG', '601818.XSHG', '600036.XSHG', '600837.XSHG', '600958.XSHG', '601318.XSHG', '600016.XSHG', '601628.XSHG', '601800.XSHG', '601688.XSHG', '601857.XSHG', '601989.XSHG', '601998.XSHG', '600999.XSHG', '600518.XSHG', '601328.XSHG', '601988.XSHG', '601788.XSHG', '600637.XSHG', '600104.XSHG', '601390.XSHG', '600111.XSHG', '601766.XSHG', '600519.XSHG', '601985.XSHG'] # universe.sort() factors = {} indexes = closes['index'] for i in universe: o = opens.loc[:, i] c = closes.loc[:, i] h = highs.loc[:, i] l = lows.loc[:, i] v = turnovers.loc[:, i] tmp = get_factors(indexes.values, o.values, c.values, h.values, l.values, np.array(v, dtype=np.float64), rolling=188, drop=False) tmp.replace([np.inf, -np.inf], np.nan, inplace=True) tmp.fillna(0, inplace=True) factors[i] = tmp fac_array = [] for i in range(202): j = i * 16 + 351 fac = [] for k in universe: tmp = factors[k] tmp = tmp.iloc[j-16*4: j] fac.append(tmp) fac = np.stack(fac, axis=0) fac = np.transpose(fac, [1, 0, 2]) fac_array.append(fac) # class Market(object): # def __init__(self): # self.fac = fac_array # def step(self, step_counter): # return self.fac[step_counter] class Market(object): def __init__(self): pass def step(self, step_counter): return fac_array[step_counter]
import React, { FunctionComponent } from 'react'; import BackHeader from 'ringcentral-widgets/components/BackHeaderV2'; import classNames from 'classnames'; import { <API key>, <API key>, } from '../../interfaces'; import { HandUpButton, HoldCallButton, } from '../SmallCallControl'; import i18n from './i18n'; import styles from './styles.scss'; export type <API key> = <API key> & <API key>; const ActiveCallListPanel: FunctionComponent<<API key>> = ({ currentLocale, goBack, callList, onHangup, onUnHold, onHold, }) => { return ( <> <BackHeader currentLocale={currentLocale} title={i18n.getString('activeCall', currentLocale)} onBackClick={goBack} className={styles.backHeader} /> <div className={styles.list} data-sign="callList"> {callList.map((callItem, key) => { const index = key > 1 ? 2 : key; const infos = [ <span className={styles.emphasisCallInfo}> {i18n.getString('everyone', currentLocale)} </span>, <span className={classNames(styles.emphasisCallInfo, styles.children)} > {i18n.getString('justMe', currentLocale)} </span>, <div className={classNames(styles.otherCallInfo, styles.children)}> <span className={styles.name}> {callItem.session.transferSessions?.[callItem.session.sessionId] ?.destination ?? null} </span> {/* TODO: add phoneFormat in ev native render logic */} <span className={styles.phoneNumber} /> </div>, ]; return ( <div className={styles.item} data-sign="callItem" key={key}> <div className={styles.info}>{infos[index]}</div> <div className={styles.controlButtons}> <div className={classNames(styles.button, styles.hide)} /> {key > 0 ? ( <HoldCallButton currentLocale={currentLocale} isOnHold={callItem.isHold} onUnHold={() => onUnHold(callItem)} onHold={() => onHold(callItem)} className={styles.button} size="small" /> ) : ( <div className={classNames(styles.button, styles.hide)} /> )} <HandUpButton currentLocale={currentLocale} onHangup={() => onHangup(callItem)} className={styles.button} size="small" /> </div> </div> ); })} </div> </> ); }; export { ActiveCallListPanel };
package kcl.teamIndexZero.traffic.simulator.data; import kcl.teamIndexZero.traffic.log.Logger; import kcl.teamIndexZero.traffic.log.Logger_Interface; import kcl.teamIndexZero.traffic.simulator.data.features.DirectedLanes; import kcl.teamIndexZero.traffic.simulator.data.features.Junction; import kcl.teamIndexZero.traffic.simulator.data.features.Lane; import kcl.teamIndexZero.traffic.simulator.data.links.JunctionLink; import kcl.teamIndexZero.traffic.simulator.exceptions.<API key>; import kcl.teamIndexZero.traffic.simulator.exceptions.<API key>; import java.util.Collection; /** * Helper tools mostly for Graph creation */ public class GraphTools { private static Logger_Interface LOG = Logger.getLoggerInstance(GraphTools.class.getSimpleName()); /** * Checks if all or none of the lanes in a directed group within a Road are connected at the front to links * * @param lanes DirectedLanes group * @return Full connection state * @throws <API key> when the lanes in DirectedLanes group have partly implemented links */ public boolean <API key>(DirectedLanes lanes) throws <API key> { LOG.log_Trace("Checking the connections at the end of ", lanes); int link_count = 0; for (Lane l : lanes.getLanes()) { if (l.getNextLink() != null) link_count++; } if (link_count == 0) { LOG.log_Trace("-->X '", lanes.getID(), "' has no next link(s)."); return false; } else if (link_count == lanes.getNumberOfLanes()) { return true; } else { LOG.log_Error("Road '", lanes.getRoad().getID(), "' has group of directed lanes with partly implemented Links (Fwd). ", link_count, "/", lanes.getNumberOfLanes(), " Lanes connected to a link."); throw new <API key>("Road has a group of directed lanes with partly implemented links."); } } /** * Checks if all or none of the lanes in a directed group within a Road are connected at the back to links * * @param lanes DirectedLanes group * @return Full connection state * @throws <API key> when the lanes in DirectedLanes group have partly implemented links */ public boolean <API key>(DirectedLanes lanes) throws <API key> { LOG.log_Trace("Checking the connections at the end of ", lanes); int link_count = 0; for (Lane l : lanes.getLanes()) { if (l.getPreviousLink() != null) link_count++; } if (link_count == 0) { LOG.log_Trace("X--> '", lanes.getID(), "' has no previous link(s)."); return false; } else if (link_count == lanes.getNumberOfLanes()) { return true; } else { LOG.log_Error("Road '", lanes.getRoad().getID(), "' has group of directed lanes with partly implemented Links (Back). ", link_count, "/", lanes.getNumberOfLanes(), " Lanes connected to a link."); throw new <API key>("Road has a group of directed lanes with partly implemented links."); } } /** * Checks for cases where a traffic generator is needed on a junction * Case 1: Inflow only junctions * Case 2: All roads except one are inflow only. Inflow on 2-way road has no where to go. * * @param junction Junction to check * @return Requirement flag for a TrafficGenerator */ public boolean <API key>(Junction junction) { int outflows = 0; junction.computeAllPaths(); for (JunctionLink link : junction.getInflowLinks()) { try { if (!junction.getNextLinks(link.getID()).isEmpty()) { outflows++; } } catch (<API key> e) { LOG.log_Warning("Inflow link '", link.getID(), "' has no outflow path on junction '", junction.getID(), "'. Junction needs a TrafficGenerator."); return true; } } return outflows == 0; } /** * Checks if collections is/are empty * * @param collections Collections to check * @return Status: 1+ Collections is empty */ public boolean checkEmpty(Collection<?>... collections) { boolean empty_flag = false; for (Collection<?> c : collections) { if (c.isEmpty()) { empty_flag = true; } } return empty_flag; } }
require 'test_helper' class MailMatchesJobTest < ActiveJob::TestCase # test "the truth" do # assert true # end end
<template name="login"> <div class="panel panel-primary"> <div class="panel-heading text-center"> <h3 class="panel-title">Sign in</h3> </div> <div class="panel-body"> <div id="error-message" class="panel-message text-danger"></div> <form role="form"> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" name="email" id="email" autofocus tabindex="1"> </div> <div class="form-group"> <label for="password">Password </label> <small><a href="{{pathFor 'forgotPassword'}}" tabindex="6">(Forgot Password)</a></small> <input type="password" class="form-control" name="password" id="password" tabindex="2"> </div> <div class="checkbox"> <label> <input type="checkbox" tabindex="3"> Remember me </label> </div> <button type="submit" class="btn btn-primary btn-block" tabindex="4">Sign in</button> </form> </div> </div> <div class="text-center"><a href="{{pathFor 'createAccount'}}" tabindex="5">Create an account</a></div> </template>
#pragma once #include <memory> #include <unordered_map> #include "time.hh" #include "thread.hh" #include "shared-mutex.hh" #include "future.hh" namespace mimosa { template <typename Key, typename Value, typename Hash = std::hash<Key>, typename KeyEqual = std::equal_to<Key> > class ExpiringCache : private NonCopyable { public: ExpiringCache(); virtual ~ExpiringCache(); typename Future<Value>::Ptr get(const Key & key); sets the duration after which an unsuded entry must be discarded void setEntryTimeout(Time time); sets the duration after which the value must be discarded void setValueTimeout(Time time); sets the cleanup period void setCleanupPeriod(Time time); starts the cleanup thread void startCleanupThread(); stops the cleanup thread void stopCleanupThread(); removes the specific key from the cache void remove(const Key & key); cleans up old cache entries void cleanup(); removes every entries from the cache and cancels fetchs void clear(); protected: class Entry { public: Time value_ts_; Time last_used_ts_; Value value_; }; typedef std::unordered_map<Key, Entry, Hash, KeyEqual> cache_type; typedef std::unordered_map<Key, typename Future<Value>::Ptr, Hash, KeyEqual> fetch_type; void set(const Key & key, const Value & value); virtual void cacheMiss(const Key & key) = 0; void cleanupLoop(); Time entry_timeout_; Time value_timeout_; Time cleanup_period_; SharedMutex lock_; bool <API key>; std::unique_ptr<Thread> cleanup_thread_; Mutex cleanup_mutex_; Condition cleanup_cond_; cache_type cache_; fetch_type fetch_; }; }
<?php declare(strict_types=1); namespace ProxyManagerTest\Factory; use Laminas\Code\Generator\ClassGenerator; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use ProxyManager\Autoloader\AutoloaderInterface; use ProxyManager\Configuration; use ProxyManager\Factory\AbstractBaseFactory; use ProxyManager\Generator\Util\<API key>; use ProxyManager\GeneratorStrategy\<API key>; use ProxyManager\Inflector\<API key>; use ProxyManager\ProxyGenerator\<API key>; use ProxyManager\Signature\<API key>; use ProxyManager\Signature\<API key>; use ReflectionClass; use ReflectionMethod; use stdClass; use function class_exists; /** * @covers \ProxyManager\Factory\AbstractBaseFactory * @group Coverage */ final class <API key> extends TestCase { /** * Note: we mock the class in order to assert on the abstract method usage * * @var AbstractBaseFactory&MockObject */ private AbstractBaseFactory $factory; /** @var <API key>&MockObject */ private <API key> $generator; /** @var <API key>&MockObject */ private <API key> $classNameInflector; /** @var <API key>&MockObject */ private <API key> $generatorStrategy; /** @var AutoloaderInterface&MockObject */ private AutoloaderInterface $proxyAutoloader; /** @var <API key>&MockObject */ private <API key> $signatureChecker; /** @var <API key>&MockObject */ private <API key> $<API key>; protected function setUp(): void { $configuration = $this->createMock(Configuration::class); $this->generator = $this->createMock(<API key>::class); $this->classNameInflector = $this->createMock(<API key>::class); $this->generatorStrategy = $this->createMock(<API key>::class); $this->proxyAutoloader = $this->createMock(AutoloaderInterface::class); $this->signatureChecker = $this->createMock(<API key>::class); $this-><API key> = $this->createMock(<API key>::class); $configuration ->method('<API key>') ->willReturn($this->classNameInflector); $configuration ->method('<API key>') ->willReturn($this->generatorStrategy); $configuration ->method('getProxyAutoloader') ->willReturn($this->proxyAutoloader); $configuration ->method('getSignatureChecker') ->willReturn($this->signatureChecker); $configuration ->method('<API key>') ->willReturn($this-><API key>); $this ->classNameInflector ->method('getUserClassName') ->willReturn(stdClass::class); $this->factory = $this-><API key>(AbstractBaseFactory::class, [$configuration]); $this->factory->method('getGenerator')->willReturn($this->generator); } public function testGeneratesClass(): void { $generateProxy = new ReflectionMethod($this->factory, 'generateProxy'); $generateProxy->setAccessible(true); $generatedClass = <API key>::getIdentifier('fooBar'); $this ->classNameInflector ->method('getProxyClassName') ->with(stdClass::class) ->willReturn($generatedClass); $this ->generatorStrategy ->expects(self::once()) ->method('generate') ->with(self::isInstanceOf(ClassGenerator::class)); $this ->proxyAutoloader ->expects(self::once()) ->method('__invoke') ->with($generatedClass) ->will(self::returnCallback(static function (string $className): bool { eval('class ' . $className . ' extends \\stdClass {}'); return true; })); $this->signatureChecker->expects(self::atLeastOnce())->method('checkSignature'); $this-><API key>->expects(self::once())->method('addSignature')->will(self::returnArgument(0)); $this ->generator ->expects(self::once()) ->method('generate') ->with( self::callback(static fn (ReflectionClass $reflectionClass): bool => $reflectionClass->getName() === stdClass::class), self::isInstanceOf(ClassGenerator::class), ['some' => 'proxy', 'options' => 'here'] ); self::assertSame( $generatedClass, $generateProxy->invoke($this->factory, stdClass::class, ['some' => 'proxy', 'options' => 'here']) ); self::assertTrue(class_exists($generatedClass, false)); self::assertSame( $generatedClass, $generateProxy->invoke($this->factory, stdClass::class, ['some' => 'proxy', 'options' => 'here']) ); } }
# <API key> Interface | Toolkit Layer | Namespace | | | Core | Microsoft.MixedReality.Toolkit.Core.Interfaces.<API key> | The <API key> is the interface that defines the requirements of the spatial awareness system. The interface is divided, logically into multiple sections. As new functionality is added, the appropriate settings section is to be defined. <img src="Images/<API key>.png"> ## General System Controls The spatial awareness system contains data and methods that configure and control the overall spatial awareness system. StartupBehavior | Type | | | AutoStartBehavior | Gets or sets a value that indicates that the developer intends for the spatial observer to start automatically or wait until explicitly resumed. This allows the application to decide precisely when it wishes to begin receiving spatial data notifications. ObservationExtents | Type | | | Vector3 | Gets or sets the size of the volume from which individual observations will be made. This is not the total size of the observable space. UpdateInterval | Type | | | float | Gets or sets the frequency, in seconds, at which the spatial observer updates. IsObserverRunning | Type | | | bool | Indicates the current running state of the spatial observer. *This is a read-only property, set by the spatial awareness system.* void ResumeObserver() Starts / restarts the spatial observer. This will cause spatial observation events (ex: MeshAddedEvent) to resume being sent. void SuspendObserver() Stops / pauses the spatial observer. This will cause spatial observation events to be suspended until ResumeObserver is called. ## Mesh Handling Controls The mesh handling section contains the data and methods that configure and control the representation of data as a collection of meshes. For platforms that do not natively support returning observation data as a mesh, implementations can optionally process the native data before providing it to the caller. Use Mesh System | Type | | | bool | Gets or sets a value that indicates if the spatial mesh subsystem is in use by the application. Turning this off will suspend all mesh events and cause the subsystem to return an empty collection when the GetMeshes method is called. MeshPhysicsLayer | Type | | | int | Get or sets the desired Unity Physics Layer on which to set the spatial mesh. <API key> | Type | | | int | Gets the bit mask that corresponds to the value specified in MeshPhysicsLayer. *This is a read-only property set by the spatial awareness system.* MeshLevelOfDetail | Type | | | [<API key>](./<API key>.md) | Gets or sets the level of detail for the returned spatial mesh. Setting this value to Custom, implies that the developer is specifying a custom value for <API key>. Specifying any other value will cause <API key> to be overwritten. <API key> | Type | | | int | Gets or sets the level of detail, in triangles per cubic meter, for the returned spatial mesh. When specifying Coarse or Fine for the MeshLevelOfDetail, this value will be automatically overwritten. <API key> | Type | | | bool | Gets or sets the value indicating if the spatial awareness system to generate normal for the returned meshes as some platforms may not support returning normal along with the spatial mesh. MeshDisplayOption | Type | | | [<API key>](./<API key>.md) | Gets or sets a value indicating how the mesh subsystem is to display surface meshes within the application. Applications that wish to process the Meshes should set this value to None. MeshVisibleMaterial | Type | | | Material | Gets or sets the material to be used when displaying spatial meshes. <API key> | Type | | | Material | Gets or sets the material to be used when spatial meshes should occlude other object. IDictionary<uint, GameObject> GetMeshes() Returns the collection of GameObjects being managed by the spatial awareness mesh subsystem. ## Surface Finding Controls The surface finding section contains the data and methods that configure and control the representation of data as a collection of planar surfaces. <API key> | Type | | | bool | Indicates if the surface finding subsystem is in use by the application. Turning this off will suspend all surface events. SurfacePhysicsLayer | Type | | | int | Get or sets the desired Unity Physics Layer on which to set spatial surfaces. <API key> | Type | | | int | Gets the bit mask that corresponds to the value specified in SurfacePhysicsLayer. *This is a read-only property set by the spatial awareness system.* <API key> | Type | | | float | Gets or sets the minimum surface area, in square meters, that must be satisfied before a surface is identified. <API key> | Type | | | bool | Gets or sets a value indicating if the surface subsystem is to automatically display floor surfaces within the application. When enabled, the surfaces will be added to the scene and displayed using the configured <API key>. <API key> | Type | | | Material | Gets or sets the material to be used when displaying planar surface(s) identified as a floor. <API key> | Type | | | bool | Gets or sets a value indicating if the surface subsystem is to automatically display ceiling surfaces within the application. When enabled, the surfaces will be added to the scene and displayed using the configured <API key>. <API key> | Type | | | Material | Gets or sets the material to be used when displaying planar surface(s) identified as a ceiling. DisplayWallSurfaces | Type | | | bool | Gets or sets a value indicating if the surface subsystem is to automatically display wall surfaces within the application. When enabled, the surfaces will be added to the scene and displayed using the configured WallSurfaceMaterial. WallSurfaceMaterial | Type | | | Material | Gets or sets the material to be used when displaying planar surface(s) identified as a wall. <API key> | Type | | | bool | Gets or sets a value indicating if the surface subsystem is to automatically display raised horizontal platform surfaces within the application. When enabled, the surfaces will be added to the scene and displayed using the configured <API key>. <API key> | Type | | | Material | Gets or sets the material to be used when displaying planar surface(s) identified as a raised horizontal platform. IDictionary<int, GameObject> GetSurfaceObjects() Returns the collection of GameObjects managed by the surface finding subsystem. ## See Also - [Mixed Reality Spatial Awareness System Architecture](./<API key>.md) - [<API key> Class](./<API key>.md) - [<API key> Interface](./<API key>.md) - [<API key> Interface](./<API key>.md) - [<API key> Enumeration](./<API key>.md) - [<API key> Enumeration](./<API key>.md)
require 'spec_helper' describe Quill::Error do it "is a kind of Standard Error" do Quill::Error.new.should be_kind_of StandardError end end
<?php defined('BASEPATH') OR exit('No direct script access allowed'); function translate_status($status) { switch ($status) { case 0: return "unsorted"; break; case 1: return "rejected"; break; case 2: return "accepted"; break; case 3: return "selected"; break; case 4: return "backlog"; break; } } ?> <?php if ($this->session->userdata('logged_in')){ ?> <style type="text/css"> .modal-open .modal { overflow-x: auto !important; overflow-y: auto !important; } .modal-dialog { width: 100% !important; height: 100% !important; margin: 0 !important; padding: 0 !important; } div#recat .modal-dialog { width: 600px !important; height: 356px !important; margin: 0 auto !important; padding: 0 !important; } .modal-content { height: auto !important; min-height: 100% !important; border-radius: 0 !important; } div#recat .modal-content { height: 354px; !important; min-height: 354px !important; border-radius: 0 !important; } .table li{ padding:0; margin: 0px; border-bottom: 1px solid #cccccc; font-size: 24px; clear: both; height: 177px; } #image-zoom{ cursor: zoom-in; } .topten{ background: #cccccc; } table.table{ float:right; } table td{ font-size: 12px; } .zoombtn{ cursor: zoom-in; } </style> <h4>Current Role: <?php echo $this->session->userdata('logged_in')['user_type'] ?></h4> <p>The images below are in order of voting:</p> <?php $i = 0; $j = 0; $temp_cat = ''; foreach($entries as $entry){ $i = $i+1; if($temp_cat != $entry['category_title']){ $temp_cat = $entry['category_title']; $j = 0; if($i>1){ echo "</ol>"; } echo '<h3>'.$entry['category_title'].'</h2>'; echo '<ol class="table">'; } $j = $j+1; if($j<11){ echo "<li aria-data='".$entry['art_id']."' ><table class='table'> <tr> <td>Image</td> <td>Tally</td> <td>Status</td> <td>CGS Art ID</td> <td>Category</td> <td>Full Name</td> <td>Address</td> <td>Email</td> <td>CGS User</td> </tr> <tr> <td> <img class='zoombtn' aria-data-image='".$entry['image_large']."' aria-data='".$entry['art_id']."' style='width:120px;' src='".str_replace("_large.jpg","_thumb.jpg",$entry['image_large'])."'> </td> <td>".$entry['position']."</td> <td>".translate_status($entry['status'])."</td> <td>".$entry['art_id']."</td> <td>".$entry['category_title']."</td> <td>".$entry['<API key>']."</td> <td>".$entry['<API key>']."</td> <td>".$entry['email']."</td> <td>".$entry['username']."</td> </tr> </table> </li>"; } } ?> </ol> <!-- Modal --> <div class="modal fade" id="recat" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Change Category</h4> </div> <div class="modal-body"> <p>Select an existing category or create a new one. This form uses tab navigation for speedy input. Press 'esc' to close without making any changes.</p> <div class="form-group"> <form id="recat_form"> <label> Category: <select id="recat_category" class="form-control"> <?php foreach($categories as $category){ echo "<option>".$category['category_title']."</option>"; } ?> </select> </label> <br /> OR <br/> <label> New Category: <input class="form-control" id="new_cat" /> </label> </form> </div> </div> <div class="modal-footer"> <button id="save_cat" type="button" class="btn btn-primary">Save changes</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="zoom" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Zoom View</h4> </div> <div class="modal-body"> <p>This is the zoomed in view, you can actually zoom in even more to the original file that was uploaded and is usually larger simply by clicking on the image in this screen. <br/> This does however require some patience, it may look like it isn't doing anything, BUT it will evenutually load the larger sized image, give it 30 seconds or so. <br> If the larger image still does not show and the browser does not appear to be loading anything futher, then it has finished and what you are looking at is that the original image is on;y slightly larger than the originals. </p> <p> To close this zoomed in window press the X in the top right hand corner or press the [esc] key on your keyboard. </p> <img id="image-zoom" src="" /> </div> </div> </div> </div> <script type="text/javascript"> var current_art_id = 0; // A $( document ).ready() block. $( document ).ready(function() { $('#save_cat').click(function () { new_cat = $("#recat_category").val(); if ($("#new_cat").val().length > 0) { new_cat = $("#new_cat").val(); console.log(new_cat); } change_cat(new_cat); }) $('#category').change(function () { $("#cat_form").submit(); return false; }) $('#status').change(function () { $("#cat_form").submit(); return false; }) $('#image-zoom').click(function () { largeimage = $(this).attr("src"); $('#image-zoom').attr('src', ''); $('#image-zoom').attr('src', largeimage.replace("_large.jpg", "_orig.jpg")); }) $('.zoombtn').click(function () { $('#zoom').modal(); largeimage = $(this).attr("aria-data-image"); $('#image-zoom').attr('src', largeimage); }) }); /* .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); }); */ </script> <?php }?>
<p> A perfect blend of pointy paws in a coat of fur, Baloo is an affable display typeface by Ek Type. Available in nine Indian scripts along with a Latin counterpart, the family is Unicode compliant and libre licensed. </p> <p> Baloo is a distinctive heavy spurless design with a subtle tinge of playfulness and all the bare necessities of type. Snuggling several scripts under a single weight, the typeface focuses on giving equal justice to every act of this gentle jungle affair to secure single and multi-script use. Carefree yet confident, warm yet entertaining, sprightly yet intelligible, Baloo infuses life everywhere it goes. </p> <p> The Baloo project develops nine separate fonts with unique local names for each of the nine Indic Scripts. Each font supports one Indic subset plus Latin, Latin Extended, and Vietnamese. </p> <p><ul> <li><a href="https: <li><a href="https: <li><a href="https: <li>Baloo Chettan for Malayalam</li> <li><a href="https: <li><a href="https: <li><a href="https: <li><a href="https: <li><a href="https: </ul></p> <p> Well fed and thoroughly nourished across every script, it took a team of committed type designers to rear Baloo and raise it to be the typeface we love. Baloo Devanagari is designed by Sarang Kulkarni, Gurmukhi by Shuchita Grover, Bangla by Noopur Datye, Oriya by Manish Minz and Shuchita Grover, Gujarati by Supriya Tembe and Noopur Datye, Kannada by Divya Kowshik, Telugu by Omkar Shende, Malayalam by Maithili Shingre and Tamil by Aadarsh Rajan. Baloo Latin is collaboratively designed by Ek Type. Type design assistance and font engineering by Girish Dalvi. </p> <p> Baloo is grateful to Sulekha Rajkumar, Vaishnavi Murthy, Gangadharan Menon, Vinay Saynekar, Dave Crossland and others for their involvement, suggestions and feedback. </p> <p> To contribute to the project, visit <a href="https://github.com/girish-dalvi/Baloo">github.com/girish-dalvi/Baloo</a> </p>
import {HttpClient} from '<API key>'; import _ from 'lodash'; import {HdoApi} from '../util/hdo-api'; import {flattenQuery} from '../util/url'; export interface PromisesQuery { page?: number; } export interface PromisesResponse { navigators: Object[]; results: Object[]; next_url?: string; previous_url?: string; current_page: number; total_pages: number; } export class PromisesApi { api: HdoApi; previousQuery: any[]; previousResponse: any; constructor(private http: HttpClient) { this.api = new HdoApi(http, 'https: this.previousQuery = []; } fetch(query: PromisesQuery) { var flattened = flattenQuery(query); return _.xor(this.previousQuery, flattened).length > 0 ? this.api.fetch(query) .then(response => { this.previousQuery = flattened; this.previousResponse = response; return response; }) : new Promise(resolve => resolve(this.previousResponse)); } }
#include "less/lessstylesheet/MediaQueryRuleset.h" #include "less/lessstylesheet/LessStylesheet.h" #include "less/stylesheet/MediaQuery.h" MediaQueryRuleset::MediaQueryRuleset(TokenList &selector, const LessRuleset &parent) : LessRuleset(*(new LessSelector()), parent) { this->selector = selector; } MediaQueryRuleset::~MediaQueryRuleset() { } void MediaQueryRuleset::process(Stylesheet& s, const Selector* prefix, ProcessingContext& context) const { Selector *rulesetselector; TokenList queryselector; MediaQuery* query; Ruleset* target; queryselector = selector; context.processValue(queryselector); query = s.createMediaQuery(queryselector); if (prefix != NULL) { rulesetselector = new Selector(*prefix); context.interpolate(*rulesetselector); target = query->createRuleset(*rulesetselector); processStatements(*target, &context); } else processStatements(*query, &context); }
// <API key>.cs - NUnit Test Cases for <API key> // Sebastien Pouliot (sebastien@ximian.com) // 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 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using NUnit.Framework; using System; using System.Security.Cryptography; namespace MonoTests.System.Security.Cryptography { // References: // a. PKCS#1: RSA Cryptography Standard [TestFixture] public class <API key> { protected <API key> pkcs1; [SetUp] public void SetUp () { pkcs1 = new <API key> (); } public void AssertEquals (string msg, byte[] array1, byte[] array2) { AllTests.AssertEquals (msg, array1, array2); } [Test] public void Properties () { // default value Assertion.AssertEquals ("<API key> HashName(default)", "SHA1", pkcs1.HashName); // return to default pkcs1.HashName = null; Assertion.AssertEquals ("<API key> HashName(null)", "SHA1", pkcs1.HashName); // bad hash accepted pkcs1.HashName = "SHA2"; Assertion.AssertEquals ("<API key> HashName(bad)", "SHA2", pkcs1.HashName); // tostring Assertion.AssertEquals ("<API key> ToString()", "System.Security.Cryptography.<API key>", pkcs1.ToString ()); } [Test] public void EmptyMask () { // pretty much useless but supported byte[] random = { 0x01 }; byte[] mask = pkcs1.GenerateMask (random, 0); Assertion.AssertEquals ("<API key> Empty Mask", 0, mask.Length); } [Test] [ExpectedException (typeof (<API key>))] public void NullSeed () { byte[] mask = pkcs1.GenerateMask (null, 10); } [Test] [ExpectedException (typeof (OverflowException))] public void <API key> () { byte[] random = { 0x01 }; byte[] mask = pkcs1.GenerateMask (random, -1); } // This test will FAIL with MS framework 1.0 and 1.1 as their MGF1 implementation is buggy [Test] #if ! NET_2_0 [Category ("NotDotNet")] // Known to fail under MS runtime - both 1.0 and 1.1 #endif public void PKCS1v21TestVector () { pkcs1.HashName = "SHA1"; // seed = random string of octets (well not random in the tests ;-) byte[] seed = { 0xaa, 0xfd, 0x12, 0xf6, 0x59, 0xca, 0xe6, 0x34, 0x89, 0xb4, 0x79, 0xe5, 0x07, 0x6d, 0xde, 0xc2, 0xf0, 0x6c, 0xb5, 0x8f }; int LengthDB = 107; // dbMask = MGF(seed, length(DB)) byte[] dbMask = pkcs1.GenerateMask (seed, LengthDB); byte[] expectedDBMask = { 0x06, 0xe1, 0xde, 0xb2, 0x36, 0x9a, 0xa5, 0xa5, 0xc7, 0x07, 0xd8, 0x2c, 0x8e, 0x4e, 0x93, 0x24, 0x8a, 0xc7, 0x83, 0xde, 0xe0, 0xb2, 0xc0, 0x46, 0x26, 0xf5, 0xaf, 0xf9, 0x3e, 0xdc, 0xfb, 0x25, 0xc9, 0xc2, 0xb3, 0xff, 0x8a, 0xe1, 0x0e, 0x83, 0x9a, 0x2d, 0xdb, 0x4c, 0xdc, 0xfe, 0x4f, 0xf4, 0x77, 0x28, 0xb4, 0xa1, 0xb7, 0xc1, 0x36, 0x2b, 0xaa, 0xd2, 0x9a, 0xb4, 0x8d, 0x28, 0x69, 0xd5, 0x02, 0x41, 0x21, 0x43, 0x58, 0x11, 0x59, 0x1b, 0xe3, 0x92, 0xf9, 0x82, 0xfb, 0x3e, 0x87, 0xd0, 0x95, 0xae, 0xb4, 0x04, 0x48, 0xdb, 0x97, 0x2f, 0x3a, 0xc1, 0x4e, 0xaf, 0xf4, 0x9c, 0x8c, 0x3b, 0x7c, 0xfc, 0x95, 0x1a, 0x51, 0xec, 0xd1, 0xdd, 0xe6, 0x12, 0x64 }; AssertEquals ("PKCS1v21TestVector 1", expectedDBMask, dbMask); // maskedDB = DB xor dbMask byte[] DB = { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 }; byte[] maskedDB = new byte [dbMask.Length]; for (int i = 0; i < dbMask.Length; i++) maskedDB [i] = Convert.ToByte (DB [i] ^ dbMask [i]); // seedMask = MGF(maskedDB, length(seed)) byte[] seedMask = pkcs1.GenerateMask (maskedDB, seed.Length); byte[] expectedSeedMask = { 0x41, 0x87, 0x0b, 0x5a, 0xb0, 0x29, 0xe6, 0x57, 0xd9, 0x57, 0x50, 0xb5, 0x4c, 0x28, 0x3c, 0x08, 0x72, 0x5d, 0xbe, 0xa9 }; AssertEquals ("PKCS1v21TestVector 2", expectedSeedMask, seedMask); } } }
FROM amclain/rbenv MAINTAINER Alex McLain <alex@alexmclain.com> RUN apt-get -qq update RUN apt-get -y install build-essential libssl-dev RUN rbenv install 2.1.2 -v RUN rbenv global 2.1.2 RUN echo "gem: --no-rdoc" > ~/.gemrc RUN gem update --force RUN gem install pry rb-readline CMD /bin/bash
//remember that here you define a stockWidget in camel-case but in html you'll use "stock-widget" angular.module('stockMarketApp') .directive('stockWidget', [function () { return { templateUrl: 'es52_stock.html', restrict: 'A', scope: { stockData: '=' //this has these effects: // it creates a var called stockData on the directive's isolated scope // in the html the value of stockData can be set by using the attributes stock-data // the value of stockData is bound to be the object that the html attrbute stock-data points to. }, link: function ($scope, $element, $attrs) { $scope.getChange = function (stock) { return Math.ceil(((stock.price - stock.previous) / stock.previous) * 100); }; $scope.changeStock = function () { $scope.stockData = { name: 'Directive Stock', price: 500, previous: 200 }; }; } }; }]); /* * restrict: * A: directive can be used as an attribute on existing html elements (such as <div stock-widget></div>). Default value. * E: directive can be used as a new html element * C: directive can be used as a class name in existing html elements * M: directive can be used as html comments (<!-- directive: stock-widget -->). The ng-repeat-start and * ng-repeat-end directives were introduces for this sole purpose, so it's preferable * to use them instead of comment directives. */ /* * Scope: * false: default. Tells to Angular that the directive scope is the same as the parent scope, whichever one it is. * Any modifications are reflected to the parent. * true: Tells to Angular that the directive scope inherits the parent scope, but creates a child scope of its own. * Any modifications are NOT reflected to the parent. This is recommended if we need access to the * parent's functions and information, but need to make local modifications that are specific to the directive. * object: Tells to Angular to create what we call an isolated scope. This scope doesn't inherit anything from the * parent, and any data that the parent scope needs to share with this directive needs to be passed in though * html attributes. This is the best option when creating reusable components that should be * independent of how and where they are used. */ /* * For the object scope you can use this three types of values: * = Specifies that the value of the attribute in html is to be treated as a json object. Any changes * done in the parent scope will be automatically available in the directive. * @ Specifies that the value of the attribute in html is to be treated as a string.Any changes * done in the parent scope will be automatically available in the directive. * & Specifies that the value of the attribute in html is a function in some controller whose reference * needs to be available to the directive. The directive can then trigger the function whenever it needs to. */
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using <API key> = Org.OpenAPITools.Client.<API key>; namespace Org.OpenAPITools.Model { <summary> QueueItemImpl </summary> [DataContract(Name = "QueueItemImpl")] public partial class QueueItemImpl : IEquatable<QueueItemImpl>, IValidatableObject { <summary> Initializes a new instance of the <see cref="QueueItemImpl" /> class. </summary> <param name="_class">_class.</param> <param name="expectedBuildNumber">expectedBuildNumber.</param> <param name="id">id.</param> <param name="pipeline">pipeline.</param> <param name="queuedTime">queuedTime.</param> public QueueItemImpl(string _class = default(string), int expectedBuildNumber = default(int), string id = default(string), string pipeline = default(string), int queuedTime = default(int)) { this.Class = _class; this.ExpectedBuildNumber = expectedBuildNumber; this.Id = id; this.Pipeline = pipeline; this.QueuedTime = queuedTime; } <summary> Gets or Sets Class </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } <summary> Gets or Sets ExpectedBuildNumber </summary> [DataMember(Name = "expectedBuildNumber", EmitDefaultValue = false)] public int ExpectedBuildNumber { get; set; } <summary> Gets or Sets Id </summary> [DataMember(Name = "id", EmitDefaultValue = false)] public string Id { get; set; } <summary> Gets or Sets Pipeline </summary> [DataMember(Name = "pipeline", EmitDefaultValue = false)] public string Pipeline { get; set; } <summary> Gets or Sets QueuedTime </summary> [DataMember(Name = "queuedTime", EmitDefaultValue = false)] public int QueuedTime { get; set; } <summary> Returns the string presentation of the object </summary> <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class QueueItemImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" ExpectedBuildNumber: ").Append(ExpectedBuildNumber).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Pipeline: ").Append(Pipeline).Append("\n"); sb.Append(" QueuedTime: ").Append(QueuedTime).Append("\n"); sb.Append("}\n"); return sb.ToString(); } <summary> Returns the JSON string presentation of the object </summary> <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } <summary> Returns true if objects are equal </summary> <param name="input">Object to be compared</param> <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as QueueItemImpl); } <summary> Returns true if QueueItemImpl instances are equal </summary> <param name="input">Instance of QueueItemImpl to be compared</param> <returns>Boolean</returns> public bool Equals(QueueItemImpl input) { if (input == null) { return false; } return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.ExpectedBuildNumber == input.ExpectedBuildNumber || this.ExpectedBuildNumber.Equals(input.ExpectedBuildNumber) ) && ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Pipeline == input.Pipeline || (this.Pipeline != null && this.Pipeline.Equals(input.Pipeline)) ) && ( this.QueuedTime == input.QueuedTime || this.QueuedTime.Equals(input.QueuedTime) ); } <summary> Gets the hash code </summary> <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } hashCode = (hashCode * 59) + this.ExpectedBuildNumber.GetHashCode(); if (this.Id != null) { hashCode = (hashCode * 59) + this.Id.GetHashCode(); } if (this.Pipeline != null) { hashCode = (hashCode * 59) + this.Pipeline.GetHashCode(); } hashCode = (hashCode * 59) + this.QueuedTime.GetHashCode(); return hashCode; } } <summary> To validate all properties of the instance </summary> <param name="validationContext">Validation context</param> <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
package Janelas.Gasto.Cama; import Hibernate.Lotecama; /** * * @author Douglas */ public class Cadastro_Lote_Cama extends javax.swing.JDialog { private boolean existe=false; public boolean isExiste() { return existe; } public void setExiste(boolean existe) { this.existe = existe; } private Lotecama cama = new Lotecama(); /** * Creates new form Cadastro_Lote_Cama1 */ public Cadastro_Lote_Cama(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } public void setCama(){ } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jComboBox1 = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jSpinner1 = new javax.swing.JSpinner(); jLabel4 = new javax.swing.JLabel(); <API key> = new javax.swing.JFormattedTextField(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); <API key>(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Janelas/Strings"); // NOI18N setTitle(bundle.getString("Cadastro_Lote_Cama")); // NOI18N jComboBox1.setModel(new javax.swing.<API key>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jLabel2.setText(bundle.getString("Tipo")); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel1.setText(bundle.getString("Cadastro_Lote_Cama")); // NOI18N jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/Cancel2.png"))); // NOI18N jButton3.setText(bundle.getString("Fechar")); // NOI18N jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/Erase2.png"))); // NOI18N jButton2.setText(bundle.getString("Limpar")); // NOI18N jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/Ok2.png"))); // NOI18N jButton1.setText(bundle.getString("Salvar")); // NOI18N jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); jLabel4.setText(bundle.getString("Preco")); // NOI18N <API key>.setFormatterFactory(new javax.swing.text.<API key>(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00")))); jLabel5.setText(bundle.getString("Quantidade")); // NOI18N jLabel3.setText(bundle.getString("Origem")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.<API key>() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.<API key>() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jButton2) .addGap(18, 18, 18) .addComponent(jButton3)) .addComponent(jLabel1) .addGroup(layout.<API key>() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField1) .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.<API key>() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel4)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinner1) .addComponent(<API key>)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.<API key>() .addContainerGap() .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(<API key>, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton1)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> // TODO add your handling code here: this.dispose(); }//GEN-LAST:<API key> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.<API key>()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (<API key> ex) { java.util.logging.Logger.getLogger(Cadastro_Lote_Cama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (<API key> ex) { java.util.logging.Logger.getLogger(Cadastro_Lote_Cama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (<API key> ex) { java.util.logging.Logger.getLogger(Cadastro_Lote_Cama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.<API key> ex) { java.util.logging.Logger.getLogger(Cadastro_Lote_Cama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Cadastro_Lote_Cama dialog = new Cadastro_Lote_Cama(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JComboBox jComboBox1; private javax.swing.JFormattedTextField <API key>; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JSpinner jSpinner1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
Setup development environment ## Install NodeJS 8.x * curl -sL https://deb.nodesource.com/setup_8.x | sudo bash - * sudo apt-get install -y nodejs ## Clone the Polyglot-v2 repository * git clone git@github.com:Einstein42/udi-polyglotv2.git * cd udi-polyglotv2 ## Install NodeJS Packages * npm install * sudo npm install pkg nodemon -g ## Run Polyglot * npm run start:dev
<label [attr.for]="inputId" class="<API key>"><input #input class="<API key> cdk-visually-hidden" [type]="_type" [id]="inputId" [checked]="checked" [disabled]="disabled" [name]="name" (change)="_onInputChange($event)" (click)="_onInputClick($event)"><div class="<API key>"><ng-content></ng-content></div></label><div class="<API key>" (touchstart)="$event.preventDefault()"></div>
using System; namespace Neo.Compiler { public class EntryPointException : Exception { <summary> Number of entry point founds </summary> public int Count { get; } <summary> Constructor </summary> <param name="count">Number of entry point founds</param> <param name="message">Message</param> public EntryPointException(int count, string message) : base(message) { Count = count; } } }
'use strict'; const { config: dotenvConfig } = require('dotenv'); dotenvConfig(); const argv = require('minimist')(process.argv.slice(2)); function getVal(...vals) { // returns first defined val or undefined for (let val of vals) { if (val === undefined) { continue; } return val; } return undefined; } // get vals in order of priority, args || env || default const target = getVal(argv.target, process.env.TARGET, 'all'); // all || region(s) const mask = getVal(argv.mask, process.env.MASK, false); // true || false const sync = getVal(argv.sync, process.env.SYNC, false); // true || false const response = getVal(argv.response, process.env.RESPONSE, 'percent'); // percent || bounds || blobs const draw = getVal(argv.draw, process.env.DRAW, false); // true || false const pixFmt = getVal(argv.pixfmt, process.env.PIXFMT, 'gray'); // gray || rgb24 || rgba const outPath = getVal(argv.outPath, process.env.OUT_PATH, './'); const { cpus } = require('os'); const basePathToJpeg = `${__dirname}/out/${(response === 'bounds' || response === 'blobs') && toBool(draw) ? 'draw' : 'pam'}/`; function toBool(val) { return val === true || val === 'true' || val === 1 || val === '1'; } console.log(`cpu cores available: ${cpus().length}`); const P2P = require('pipe2pam'); const PamDiff = require('../index'); const ffmpegPath = require('../lib/ffmpeg'); const { spawn, execFile } = require('child_process'); const { createWriteStream } = require('fs'); const params = [ '-loglevel', 'quiet', /* use hardware acceleration */ '-hwaccel', 'auto', // vda, videotoolbox, none, auto // '-stream_loop', '-1',//-1 for infinite /* use a pre-recorded mp4 video as input */ '-re', // comment out to have ffmpeg read video as fast as possible '-rtsp_transport', 'tcp', '-i', // `${__dirname}/in/circle_star.mp4`, 'rtsp://192.168.1.23:554/user=admin_password=pass_channel=1_stream=1.sdp', /* '-re', '-f', 'lavfi', '-i', 'testsrc=size=1920x1080:rate=2',*/ /* set output flags */ '-an', '-c:v', 'pam', '-pix_fmt', pixFmt, '-f', 'image2pipe', '-vf', // 'fps=4,scale=1920:1080', 'fps=2,scale=640:360', 'pipe:1', ]; const ffmpeg = spawn(`${outPath}ffmpeg`, params, { stdio: ['ignore', 'pipe', 'ignore'], }); console.log(ffmpeg.spawnargs.join(' ')); ffmpeg.on('error', error => { console.log(error); }); ffmpeg.on('exit', (code, signal) => { console.log(`exit ${code} ${signal}`); // may be a race condition with these values console.log(`pam count: ${pamCounter}`); console.log(`diff count: ${diffCounter}`); console.log(`jpeg count: ${jpegCounter}`); }); const p2p = new P2P(); let pamCounter = 0; let diffCounter = 0; let jpegCounter = 0; p2p.on('pam', data => { ++pamCounter; }); let regions; if (target === 'all') { regions = null; } else { const region1 = { name: 'TOP_LEFT', difference: 10, percent: 7, polygon: [ { x: 0, y: 0 }, { x: 959, y: 0 }, { x: 959, y: 539 }, { x: 0, y: 539 }, ], }; const region2 = { name: 'BOTTOM_LEFT', difference: 10, percent: 7, polygon: [ { x: 0, y: 540 }, { x: 959, y: 540 }, { x: 959, y: 1079 }, { x: 0, y: 1079 }, ], }; const region3 = { name: 'TOP_RIGHT', difference: 10, percent: 7, polygon: [ { x: 960, y: 0 }, { x: 1919, y: 0 }, { x: 1919, y: 539 }, { x: 960, y: 539 }, ], }; regions = [region1, region2, region3]; } const pamDiff = new PamDiff({ percent: 2, regions: regions, mask: mask, response: response, sync: sync, draw: draw }); pamDiff.on('diff', data => { // console.log(data); ++diffCounter; // comment out the following line if you want to use ffmpeg to create a jpeg from the pam image that triggered an image difference event // if(true){return;} const date = new Date(); let name = `${pixFmt}-${toBool(sync) ? 'sync' : 'async'}-${diffCounter}`; for (const region of data.trigger) { if (response === 'bounds') { name += `--${region.name}-percent${region.percent}-minX${region.minX}-maxX${region.maxX}-minY${region.minY}-maxY${region.maxY}`; } else { name += `--${region.name}-percent${region.percent}`; } } const jpeg = `${name}.jpeg`; const pathToJpeg = `${outPath}${jpeg}`; // const ff = execFile(ffmpegPath, ['-y', '-f', 'rawvideo', '-pix_fmt', 'gray', '-s', '640x360', '-i', 'pipe:0', '-frames', 1, '-c:v', 'mjpeg', '-pix_fmt', 'yuvj422p', '-q:v', '1', '-huffman', 'optimal', pathToJpeg]); // ff.stdin.end(data.bc); const writeStream = createWriteStream(`${pathToJpeg}.pam`); writeStream.write(data.headers); writeStream.end(data.pixels); console.log(`${pathToJpeg}.pam`); if (global.gc) { global.gc(); } }); ffmpeg.stdout.pipe(p2p).pipe(pamDiff);
using System; using SimplePersistence.Model; namespace SimplePersistence.Example.Console.Models.Logging { public class Log : Entity<long> { public virtual Level Level { get; set; } public virtual Application Application { get; set; } public string Logger { get; set; } public string Thread { get; set; } public string Message { get; set; } public string Exception { get; set; } public DateTime CreatedOn { get; set; } public string CreatedBy { get; set; } public Log() { CreatedOn = DateTime.Now; } } }
// @flow /* eslint-disable import/<API key> */ export const NAME = '<%= moduleName %>';
const express = require('express'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const compression = require('compression'); const nunjucks = require('nunjucks'); const constants = require('../app/lib/constants'); const errorCounter = require('../app/lib/promCounters').errorPageViews; const helmet = require('./helmet'); const locals = require('../app/middleware/locals'); const log = require('../app/lib/logger'); const promBundle = require('../app/lib/promBundle').middleware; const router = require('./routes'); module.exports = (app, config) => { const siteRoot = constants.siteRoot; // <API key> no-param-reassign app.locals.siteRoot = siteRoot; // <API key> no-param-reassign app.locals.assetsUrl = constants.assetsUrl; // start collecting default metrics promBundle.promClient.<API key>(); // Get nunjucks templates from app views and NHS frontend library const appViews = [ `${config.root}/app/views`, 'node_modules/nhsuk-frontend/packages/components', ]; app.set('views', appViews); app.set('view engine', 'nunjucks'); const nunjucksEnvironment = nunjucks.configure(appViews, { autoescape: true, express: app, watch: true, }); log.info({ config: { nunjucksEnvironment } }, 'nunjucks environment configuration'); helmet(app); app.use(locals(config)); app.use((req, res, next) => { log.debug({ req }); next(); }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true, })); app.use(cookieParser()); app.use(compression()); app.use(siteRoot, express.static(`${config.root}/public`)); app.use(siteRoot, express.static('node_modules/nhsuk-frontend/dist')); // metrics needs to be registered before routes wishing to have metrics generated // see https://github.com/jochen-schweizer/express-prom-bundle#sample-uusage app.use(promBundle); app.use(siteRoot, router); app.use(siteRoot, (req, res) => { log.warn({ req }, 404); res.status(404); res.render('error-404'); }); // <API key> no-unused-vars app.use(siteRoot, (err, req, res, next) => { const statusCode = err.statusCode || 500; errorCounter.inc(1); log.error({ error: { err, req, res } }, 'Error'); res.status(statusCode); res.render('error', { error: app.get('env') === 'development' ? err : {}, message: err, title: 'error', }); }); app.get('/', (req, res) => { res.redirect(siteRoot); }); };
#ifndef <API key> #define <API key> #include "linear/ssl_context.h" #include "server_impl.h" namespace linear { class SSLServerImpl : public ServerImpl { public: SSLServerImpl(const linear::weak_ptr<linear::Handler>& handler, const linear::SSLContext& context, const linear::EventLoop& loop); virtual ~SSLServerImpl(); linear::Error Start(const std::string& hostname, int port, linear::EventLoopImpl::ServerEvent* ev); linear::Error Stop(); void OnAccept(tv_stream_t* srv_stream, tv_stream_t* cli_stream, int status); void SetSSLContext(const linear::SSLContext& context) { context_ = context; } private: linear::SSLContext context_; tv_ssl_t* handle_; }; } // namespace linear #endif // <API key>
package togglr import ( "testing" ) func TestInitWithJson(t *testing.T) { Init("data/feature.json") m := FeaturesJSON{} Read(&m) if !m.FeatureJson.IsEnabled() { t.Fatal("FeatureJson was not set") } if !m.FeatureWithTag.IsEnabled() { t.Fatal("FeatureWithTag was not set") } if m.FeatureJsonFalse.IsEnabled() { t.Fatal("FeatureJsonFalse was not set correctly") } } type FeaturesJSON struct { FeatureJson Feature FeatureJsonFalse Feature FeatureWithTag Feature `json:"fwt"` }
namespace Sleemon.Core { using System.Collections.Generic; using Sleemon.Data; public interface IRoleService { IList<UserRole> <API key>(string userUniqueId); IList<Role> GetAllRoleList(); IList<Role> GetRoleList(string roleName, int pageIndex, int pageSize, out int totalCount); ResultBase AddRole(Role role); ResultBase UpdateRole(Role role); ResultBase DeleteRole(int roleid, string userUniqueId); } }
import numpy as np import pandas as pd from sklearn.ensemble import <API key> import xgboost as xgb from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.<API key> import PReLU from keras.models import Sequential from keras.utils import np_utils from hep_ml.losses import <API key> from hep_ml.gradientboosting import <API key> from sklearn.preprocessing import StandardScaler trainingFilePath = 'training.csv' testFilePath = 'test.csv' def get_training_data(): filter_out = ['id', 'min_ANNmuon', 'production', 'mass', 'signal', 'SPDhits', 'IP', 'IPSig', 'isolationc'] f = open(trainingFilePath) data = [] y = [] ids = [] for i, l in enumerate(f): if i == 0: labels = l.rstrip().split(',') label_indices = dict((l, i) for i, l in enumerate(labels)) continue values = l.rstrip().split(',') filtered = [] for v, l in zip(values, labels): if l not in filter_out: filtered.append(float(v)) label = values[label_indices['signal']] ID = values[0] data.append(filtered) y.append(float(label)) ids.append(ID) return ids, np.array(data), np.array(y) def get_test_data(): filter_out = ['id', 'min_ANNmuon', 'production', 'mass', 'signal', 'SPDhits', 'IP', 'IPSig', 'isolationc'] f = open(testFilePath) data = [] ids = [] for i, l in enumerate(f): if i == 0: labels = l.rstrip().split(',') continue values = l.rstrip().split(',') filtered = [] for v, l in zip(values, labels): if l not in filter_out: filtered.append(float(v)) ID = values[0] data.append(filtered) ids.append(ID) return ids, np.array(data) def preprocess_data(X, scaler=None): if not scaler: scaler = StandardScaler() scaler.fit(X) X = scaler.transform(X) return X, scaler # get training data ids, X, y = get_training_data() print('Data shape:', X.shape) # shuffle the data np.random.seed(248) np.random.shuffle(X) np.random.seed(248) np.random.shuffle(y) print('Signal ratio:', np.sum(y) / y.shape[0]) # preprocess the data X, scaler = preprocess_data(X) y = np_utils.to_categorical(y) # split into training / evaluation data nb_train_sample = int(len(y) * 0.97) X_train = X[:nb_train_sample] X_eval = X[nb_train_sample:] y_train = y[:nb_train_sample] y_eval = y[nb_train_sample:] print('Train on:', X_train.shape[0]) print('Eval on:', X_eval.shape[0]) # deep pyramidal MLP, narrowing with depth model = Sequential() model.add(Dropout(0.15)) model.add(Dense(X_train.shape[1],200)) model.add(PReLU((200,))) model.add(Dropout(0.13)) model.add(Dense(200, 150)) model.add(PReLU((150,))) model.add(Dropout(0.12)) model.add(Dense(150,100)) model.add(PReLU((100,))) model.add(Dropout(0.11)) model.add(Dense(100, 50)) model.add(PReLU((50,))) model.add(Dropout(0.09)) model.add(Dense(50, 30)) model.add(PReLU((30,))) model.add(Dropout(0.07)) model.add(Dense(30, 25)) model.add(PReLU((25,))) model.add(Dense(25, 2)) model.add(Activation('softmax')) model.compile(loss='<API key>', optimizer='rmsprop') # train model model.fit(X_train, y_train, batch_size=128, nb_epoch=75, validation_data=(X_eval, y_eval), verbose=2, show_accuracy=True) # generate submission ids, X = get_test_data() print('Data shape:', X.shape) X, scaler = preprocess_data(X, scaler) predskeras = model.predict(X, batch_size=256)[:, 1] print("Load the training/test data using pandas") train = pd.read_csv(trainingFilePath) test = pd.read_csv(testFilePath) print("Eliminate SPDhits, which makes the agreement check fail") features = list(train.columns[1:-5]) print("Train a <API key>") loss = <API key>(['mass'], n_bins=15, uniform_label=0) clf = <API key>(loss=loss, n_estimators=50, subsample=0.1, max_depth=6, min_samples_leaf=10, learning_rate=0.1, train_features=features, random_state=11) clf.fit(train[features + ['mass']], train['signal']) fb_preds = clf.predict_proba(test[features])[:,1] print("Train a Random Forest model") rf = <API key>(n_estimators=250, n_jobs=-1, criterion="entropy", random_state=1) rf.fit(train[features], train["signal"]) print("Train a XGBoost model") params = {"objective": "binary:logistic", "eta": 0.2, "max_depth": 10, "min_child_weight": 1, "silent": 1, "colsample_bytree": 0.7, "seed": 1} num_trees=300 gbm = xgb.train(params, xgb.DMatrix(train[features], train["signal"]), num_trees) print("Make predictions on the test set") test_probs = (0.30*rf.predict_proba(test[features])[:,1]) + (0.30*gbm.predict(xgb.DMatrix(test[features])))+(0.30*predskeras) + (0.10*fb_preds) submission = pd.DataFrame({"id": test["id"], "prediction": test_probs}) submission.to_csv("rf_xgboost_keras.csv", index=False)
var ISOBoxer = {}; ISOBoxer.parseBuffer = function(arrayBuffer) { return new ISOFile(arrayBuffer).parse(); }; ISOBoxer.Utils = {}; ISOBoxer.Utils.dataViewToString = function(dataView, encoding) { var impliedEncoding = encoding || 'utf-8' if (typeof TextDecoder !== 'undefined') { return new TextDecoder(impliedEncoding).decode(dataView); } var a = []; var i = 0; if (impliedEncoding === 'utf-8') { while (i < dataView.byteLength) { var c = dataView.getUint8(i++); if (c < 0x80) { // 1-byte character (7 bits) } else if (c < 0xe0) { // 2-byte character (11 bits) c = (c & 0x1f) << 6; c |= (dataView.getUint8(i++) & 0x3f); } else if (c < 0xf0) { // 3-byte character (16 bits) c = (c & 0xf) << 12; c |= (dataView.getUint8(i++) & 0x3f) << 6; c |= (dataView.getUint8(i++) & 0x3f); } else { // 4-byte character (21 bits) c = (c & 0x7) << 18; c |= (dataView.getUint8(i++) & 0x3f) << 12; c |= (dataView.getUint8(i++) & 0x3f) << 6; c |= (dataView.getUint8(i++) & 0x3f); } a.push(String.fromCharCode(c)); } } else { // Just map byte-by-byte (probably wrong) while (i < dataView.byteLength) { a.push(String.fromCharCode(dataView.getUint8(i++))); } } return a.join(''); }; if (typeof exports !== 'undefined') { exports.parseBuffer = ISOBoxer.parseBuffer; exports.Utils = ISOBoxer.Utils; }; ISOBoxer.Cursor = function(initialOffset) { this.offset = (typeof initialOffset == 'undefined' ? 0 : initialOffset); }; var ISOFile = function(arrayBuffer) { this._raw = new DataView(arrayBuffer); this._cursor = new ISOBoxer.Cursor(); this.boxes = []; } ISOFile.prototype.fetch = function(type) { var result = this.fetchAll(type, true); return (result.length ? result[0] : null); } ISOFile.prototype.fetchAll = function(type, returnEarly) { var result = []; ISOFile._sweep.call(this, type, result, returnEarly); return result; } ISOFile.prototype.parse = function() { this._cursor.offset = 0; this.boxes = []; while (this._cursor.offset < this._raw.byteLength) { var box = ISOBox.parse(this); // Box could not be parsed if (typeof box.type === 'undefined') break; this.boxes.push(box); } return this; } ISOFile._sweep = function(type, result, returnEarly) { if (this.type && this.type == type) result.push(this); for (var box in this.boxes) { if (result.length && returnEarly) return; ISOFile._sweep.call(this.boxes[box], type, result, returnEarly); } }; var ISOBox = function() { this._cursor = new ISOBoxer.Cursor(); } ISOBox.parse = function(parent) { var newBox = new ISOBox(); newBox._offset = parent._cursor.offset; newBox._root = (parent._root ? parent._root : parent); newBox._raw = parent._raw; newBox._parent = parent; newBox._parseBox(); parent._cursor.offset = newBox._raw.byteOffset + newBox._raw.byteLength; return newBox; } ISOBox.prototype._readInt = function(size) { var result = null; switch(size) { case 8: result = this._raw.getInt8(this._cursor.offset - this._raw.byteOffset); break; case 16: result = this._raw.getInt16(this._cursor.offset - this._raw.byteOffset); break; case 32: result = this._raw.getInt32(this._cursor.offset - this._raw.byteOffset); break; case 64: // Warning: JavaScript cannot handle 64-bit integers natively. // This will give unexpected results for integers >= 2^53 var s1 = this._raw.getInt32(this._cursor.offset - this._raw.byteOffset); var s2 = this._raw.getInt32(this._cursor.offset - this._raw.byteOffset + 4); result = (s1 * Math.pow(2,32)) + s2; break; } this._cursor.offset += (size >> 3); return result; } ISOBox.prototype._readUint = function(size) { var result = null; switch(size) { case 8: result = this._raw.getUint8(this._cursor.offset - this._raw.byteOffset); break; case 16: result = this._raw.getUint16(this._cursor.offset - this._raw.byteOffset); break; case 24: var s1 = this._raw.getUint16(this._cursor.offset - this._raw.byteOffset); var s2 = this._raw.getUint8(this._cursor.offset - this._raw.byteOffset + 2); result = (s1 << 8) + s2; break; case 32: result = this._raw.getUint32(this._cursor.offset - this._raw.byteOffset); break; case 64: // Warning: JavaScript cannot handle 64-bit integers natively. // This will give unexpected results for integers >= 2^53 var s1 = this._raw.getUint32(this._cursor.offset - this._raw.byteOffset); var s2 = this._raw.getUint32(this._cursor.offset - this._raw.byteOffset + 4); result = (s1 * Math.pow(2,32)) + s2; break; } this._cursor.offset += (size >> 3); return result; } ISOBox.prototype._readString = function(length) { var str = ''; for (var c = 0; c < length; c++) { var char = this._readUint(8); str += String.fromCharCode(char); } return str; } ISOBox.prototype.<API key> = function() { var str = ''; while (true) { var char = this._readUint(8); if (char == 0) break; str += String.fromCharCode(char); } return str; } ISOBox.prototype._readTemplate = function(size) { var pre = this._readUint(size / 2); var post = this._readUint(size / 2); return pre + (post / Math.pow(2, size / 2)); } ISOBox.prototype._parseBox = function() { this._cursor.offset = this._offset; // return immediately if there are not enough bytes to read the header if (this._offset + 8 > this._raw.buffer.byteLength) { this._root._incomplete = true; return; } this.size = this._readUint(32); this.type = this._readString(4); if (this.size == 1) { this.largesize = this._readUint(64); } if (this.type == 'uuid') { this.usertype = this._readString(16); } switch(this.size) { case 0: this._raw = new DataView(this._raw.buffer, this._offset, (this._raw.byteLength - this._cursor.offset)); break; case 1: if (this._offset + this.size > this._raw.buffer.byteLength) { this._incomplete = true; this._root._incomplete = true; } else { this._raw = new DataView(this._raw.buffer, this._offset, this.largesize); } break; default: if (this._offset + this.size > this._raw.buffer.byteLength) { this._incomplete = true; this._root._incomplete = true; } else { this._raw = new DataView(this._raw.buffer, this._offset, this.size); } } // additional parsing if (!this._incomplete && this._boxParsers[this.type]) this._boxParsers[this.type].call(this); } ISOBox.prototype._parseFullBox = function() { this.version = this._readUint(8); this.flags = this._readUint(24); } ISOBox.prototype._boxParsers = {};; // Simple container boxes, all from ISO/IEC 14496-12:2012 except vttc which is from 14496-30. [ 'moov', 'trak', 'tref', 'mdia', 'minf', 'stbl', 'edts', 'dinf', 'mvex', 'moof', 'traf', 'mfra', 'udta', 'meco', 'strk', 'vttc' ].forEach(function(boxType) { ISOBox.prototype._boxParsers[boxType] = function() { this.boxes = []; while (this._cursor.offset - this._raw.byteOffset < this._raw.byteLength) { this.boxes.push(ISOBox.parse(this)); } } }) ; // ISO/IEC 14496-12:2012 - 8.6.6 Edit List Box ISOBox.prototype._boxParsers['elst'] = function() { this._parseFullBox(); this.entry_count = this._readUint(32); this.entries = []; for (var i=1; i <= this.entry_count; i++) { var entry = {}; if (this.version == 1) { entry.segment_duration = this._readUint(64); entry.media_time = this._readInt(64); } else { entry.segment_duration = this._readUint(32); entry.media_time = this._readInt(32); } entry.media_rate_integer = this._readInt(16); entry.media_rate_fraction = this._readInt(16); this.entries.push(entry); } }; // ISO/IEC 23009-1:2014 - 5.10.3.3 Event Message Box ISOBox.prototype._boxParsers['emsg'] = function() { this._parseFullBox(); this.scheme_id_uri = this.<API key>(); this.value = this.<API key>(); this.timescale = this._readUint(32); this.<API key> = this._readUint(32); this.event_duration = this._readUint(32); this.id = this._readUint(32); this.message_data = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); }; // ISO/IEC 14496-12:2012 - 8.1.2 Free Space Box ISOBox.prototype._boxParsers['free'] = ISOBox.prototype._boxParsers['skip'] = function() { this.data = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); }; // ISO/IEC 14496-12:2012 - 4.3 File Type Box / 8.16.2 Segment Type Box ISOBox.prototype._boxParsers['ftyp'] = ISOBox.prototype._boxParsers['styp'] = function() { this.major_brand = this._readString(4); this.minor_versions = this._readUint(32); this.compatible_brands = []; while (this._cursor.offset - this._raw.byteOffset < this._raw.byteLength) { this.compatible_brands.push(this._readString(4)); } }; // ISO/IEC 14496-12:2012 - 8.4.3 Handler Reference Box ISOBox.prototype._boxParsers['hdlr'] = function() { this._parseFullBox(); this.pre_defined = this._readUint(32); this.handler_type = this._readString(4); this.reserved = [this._readUint(32), this._readUint(32), this._readUint(32)] this.name = this.<API key>() }; // ISO/IEC 14496-12:2012 - 8.1.1 Media Data Box ISOBox.prototype._boxParsers['mdat'] = function() { this.data = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); }; // ISO/IEC 14496-12:2012 - 8.4.2 Media Header Box ISOBox.prototype._boxParsers['mdhd'] = function() { this._parseFullBox(); if (this.version == 1) { this.creation_time = this._readUint(64); this.modification_time = this._readUint(64); this.timescale = this._readUint(32); this.duration = this._readUint(64); } else { this.creation_time = this._readUint(32); this.modification_time = this._readUint(32); this.timescale = this._readUint(32); this.duration = this._readUint(32); } var language = this._readUint(16); this.pad = (language >> 15); this.language = String.fromCharCode( ((language >> 10) & 0x1F) + 0x60, ((language >> 5) & 0x1F) + 0x60, (language & 0x1F) + 0x60 ); this.pre_defined = this._readUint(16); }; // ISO/IEC 14496-12:2012 - 8.8.5 Movie Fragment Header Box ISOBox.prototype._boxParsers['mfhd'] = function() { this._parseFullBox(); this.sequence_number = this._readUint(32); }; // ISO/IEC 14496-12:2012 - 8.2.2 Movie Header Box ISOBox.prototype._boxParsers['mvhd'] = function() { this._parseFullBox(); if (this.version == 1) { this.creation_time = this._readUint(64); this.modification_time = this._readUint(64); this.timescale = this._readUint(32); this.duration = this._readUint(64); } else { this.creation_time = this._readUint(32); this.modification_time = this._readUint(32); this.timescale = this._readUint(32); this.duration = this._readUint(32); } this.rate = this._readTemplate(32); this.volume = this._readTemplate(16); this.reserved1 = this._readUint(16); this.reserved2 = [ this._readUint(32), this._readUint(32) ]; this.matrix = []; for (var i=0; i<9; i++) { this.matrix.push(this._readTemplate(32)); } this.pre_defined = []; for (var i=0; i<6; i++) { this.pre_defined.push(this._readUint(32)); } this.next_track_ID = this._readUint(32); }; // ISO/IEC 14496-30:2014 - WebVTT Cue Payload Box. ISOBox.prototype._boxParsers['payl'] = function() { var cue_text_raw = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); this.cue_text = ISOBoxer.Utils.dataViewToString(cue_text_raw); } ; // ISO/IEC 14496-12:2012 - 8.16.3 Segment Index Box ISOBox.prototype._boxParsers['sidx'] = function() { this._parseFullBox(); this.reference_ID = this._readUint(32); this.timescale = this._readUint(32); if (this.version == 0) { this.<API key> = this._readUint(32); this.first_offset = this._readUint(32); } else { this.<API key> = this._readUint(64); this.first_offset = this._readUint(64); } this.reserved = this._readUint(16); this.reference_count = this._readUint(16); this.references = []; for (var i=0; i<this.reference_count; i++) { var ref = {}; var reference = this._readUint(32); ref.reference_type = (reference >> 31) & 0x1; ref.referenced_size = reference & 0x7FFFFFFF; ref.subsegment_duration = this._readUint(32); var sap = this._readUint(32); ref.starts_with_SAP = (sap >> 31) & 0x1; ref.SAP_type = (sap >> 28) & 0x7; ref.SAP_delta_time = sap & 0xFFFFFFF; this.references.push(ref); } }; // ISO/IEC 14496-12:2012 - 8.16.4 Subsegment Index Box ISOBox.prototype._boxParsers['ssix'] = function() { this._parseFullBox(); this.subsegment_count = this._readUint(32); this.subsegments = []; for (var i=0; i<this.subsegment_count; i++) { var subsegment = {}; subsegment.ranges_count = this._readUint(32); subsegment.ranges = []; for (var j=0; j<subsegment.ranges_count; j++) { var range = {}; range.level = this._readUint(8); range.range_size = this._readUint(24); subsegment.ranges.push(range); } this.subsegments.push(subsegment); } }; // ISO/IEC 14496-12:2012 - 8.8.12 Track Fragmnent Decode Time ISOBox.prototype._boxParsers['tfdt'] = function() { this._parseFullBox(); if (this.version == 1) { this.baseMediaDecodeTime = this._readUint(64); } else { this.baseMediaDecodeTime = this._readUint(32); } }; // ISO/IEC 14496-12:2012 - 8.8.7 Track Fragment Header Box ISOBox.prototype._boxParsers['tfhd'] = function() { this._parseFullBox(); this.track_ID = this._readUint(32); if (this.flags & 0x1) this.base_data_offset = this._readUint(64); if (this.flags & 0x2) this.<API key> = this._readUint(32); if (this.flags & 0x8) this.<API key> = this._readUint(32); if (this.flags & 0x10) this.default_sample_size = this._readUint(32); if (this.flags & 0x20) this.<API key> = this._readUint(32); }; // ISO/IEC 14496-12:2012 - 8.3.2 Track Header Box ISOBox.prototype._boxParsers['tkhd'] = function() { this._parseFullBox(); if (this.version == 1) { this.creation_time = this._readUint(64); this.modification_time = this._readUint(64); this.track_ID = this._readUint(32); this.reserved1 = this._readUint(32); this.duration = this._readUint(64); } else { this.creation_time = this._readUint(32); this.modification_time = this._readUint(32); this.track_ID = this._readUint(32); this.reserved1 = this._readUint(32); this.duration = this._readUint(32); } this.reserved2 = [ this._readUint(32), this._readUint(32) ]; this.layer = this._readUint(16); this.alternate_group = this._readUint(16); this.volume = this._readTemplate(16); this.reserved3 = this._readUint(16); this.matrix = []; for (var i=0; i<9; i++) { this.matrix.push(this._readTemplate(32)); } this.width = this._readUint(32); this.height = this._readUint(32); }; // ISO/IEC 14496-12:2012 - 8.8.8 Track Run Box // Note: the 'trun' box has a direct relation to the 'tfhd' box for defaults. // These defaults are not set explicitly here, but are left to resolve for the user. ISOBox.prototype._boxParsers['trun'] = function() { this._parseFullBox(); this.sample_count = this._readUint(32); if (this.flags & 0x1) this.data_offset = this._readInt(32); if (this.flags & 0x4) this.first_sample_flags = this._readUint(32); this.samples = []; for (var i=0; i<this.sample_count; i++) { var sample = {}; if (this.flags & 0x100) sample.sample_duration = this._readUint(32); if (this.flags & 0x200) sample.sample_size = this._readUint(32); if (this.flags & 0x400) sample.sample_flags = this._readUint(32); if (this.flags & 0x800) { if (this.version == 0) { sample.<API key> = this._readUint(32); } else { sample.<API key> = this._readInt(32); } } this.samples.push(sample); } }; // ISO/IEC 14496-30:2014 - WebVTT Source Label Box ISOBox.prototype._boxParsers['vlab'] = function() { var source_label_raw = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); this.source_label = ISOBoxer.Utils.dataViewToString(source_label_raw); } ; // ISO/IEC 14496-30:2014 - WebVTT Configuration Box ISOBox.prototype._boxParsers['vttC'] = function() { var config_raw = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); this.config = ISOBoxer.Utils.dataViewToString(config_raw); } ; // ISO/IEC 14496-30:2014 - WebVTT Empty Sample Box ISOBox.prototype._boxParsers['vtte'] = function() { // Nothing should happen here. }
#pragma once #include "game/GameLib.h" #include "map/Map.h" #include <memory> namespace game { class Controller { public: explicit Controller(std::unique_ptr<GameLib>& gameLib, const std::string& pathToRallyDir, size_t parts); void run(); private: std::unique_ptr<GameLib> gameLib_; std::string pathToRoot_; map::Map map_; size_t parts_; }; }
`pptx` recipe generates office powerpoint presentations based on the uploaded pptx template with [handlebars](/learn/handlebars) tags filled inside using Powerpoint application. 1. Open Powerpoint and create pptx file using handlebars templating engine. 2. Upload created pptx file as an asset to the jsreport studio 3. Create template, select pptx recipe and link the previously uploaded asset 4. Attach sample input data or scripts if needed 5. Run the template, you get back dynamically assembled pptx report ![pptx](/img/pptx.png) ## Examples - [Basic](https://playground.jsreport.net/w/admin/Jix3rnoQ) ## Built-in helpers pptxSlides Main helper used to multiply slides. The helper call should be placed on the slide and the system iterates over provided data and creates extra slide based on item's context. {{pptxSlides item}} [Example - Slides](https://playground.jsreport.net/w/admin/Jix3rnoQ) pptxList Create a list with single item using Word and call the `pptxList` helper. It will iterate over provided data and create another list item for every entry. - {{#pptxList people}}{{name}}{{/pptxList }} [Example - List](https://playground.jsreport.net/w/admin/QCStNYjG) pptxImage 1. Prepare image placeholder using Powerpoint- place any image to the desired position and format it to your needs. 2. Insert to the slide a new text box with content `{{pptxImage src=myDataURIForImage}}` 3. Move the text box over previously created image 4. Select both image and text box and click group from the "Picture Tools/Format" toolbar 5. Run the template with `myDataURIForImage` prop in the input data and you should see the image replaced in the output. [Example - Image](https://playground.jsreport.net/w/admin/MBHWcK~B) ## Preview in studio See general documentation for office preview in studio [here](/learn/office-preview). ## API js { "template": { "recipe": "pptx", "engine": "handlebars", "pptx": { "<API key>": "xxxx" } }, "data": {} } In case you don't have the office template stored as an asset you can send it directly in the API call. js { "template": { "recipe": "pptx", "engine": "handlebars", "pptx": { "templateAsset": { "content": "base64 encoded word file", "encoding": "base64" } } }, "data": {} }
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Cultural Blog 3</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css"> <link rel="stylesheet" href="../styles/main.css"> </head> <body> <header> <div class= "row"> <div class="container"> <h1> Meditation process </h1> <div class= "twelve columns"> <div class= "three columns"><a class="button"href="http://janawinter.github.io/index.html"> Home</a></div> <div class="three columns"><a class="button"href="http://janawinter.github.io/blog.html"> Blog</a></div> <div class="three columns"><a class="button"href="http://janawinter.github.io/about.html"> About</a></div> <div class="three columns"><a class="button"href="http://janawinter.github.io/contact.html">Contact</a></div> </div> </div> </header> <div class="container"> <h1>Search Inside Yourself</h1> <h2>A cultural blog part 3 </h2> <h3> 4th June 2016</h3> </div> </div> <div class="container"> <br> <p> <strong> How did the 'process over product' concept affect the way you tackled the site redesign and rebuild?</strong> I find it hard to not focus on the design (I still am working on it!) But the concept really made me just focus to get the pages functioning right and fully responsive, instead of worrying about the overall look- I think that these two almost work together- the website design and responsive design. I feel like I will be spending a bit more time of the look of the site over the next while. </p> <br> <p> <strong>What did you think about mediation before reading chapter 2?</strong> I guess most of my life I thought meditation was something one did for a very long time- I.e an hour or more at a time. I thought it was predominantly for spiritual hippy people and not for people like Meng who work at google, or for the students that go through EDA to learn. </p> <p> </p> <br> <p> <strong>What new things have you learnt about mediation?</strong> </p> <p> That it doesn’t have to be done the traditional way, one can generally do their own style, in their own way, however is most comfortable, and wherever you want to do it. That it is good for us both emotionally and physically, it can help with all sorts of stresses and even physical medical conditions. </p> <br> <p> <strong>Did any of the suggested mediation techniques stand out to you?</strong> </p> <p> I liked the 'Imagine you are a mountain' when meditating. <br> </p> <p> <strong> Any other musings?</strong></p> 'Breathing as though your life depended' on it is pretty good way of looking at it. </p> </div> <div class="footer"> <div class="row"> <div class ="container"> <p> &copy; Jana Winter 2016 <a href="http://JanaWinter.github.io/contact.html">Contact me </a></p> </div> </div> </div> </p> </div> </body> </html>
#ifndef __CAMERA_H__ #define __CAMERA_H__ #include "cocos2d.h" USING_NS_CC; class Camera3d { Vec3 _eye; // Eye position Vec3 _lookat; // Lookat position Vec3 _up; // Up vector Mat4 _viewMatrix; float _fov; // FOVy int _screenWidth; // Screen width int _screenHeight; // Screen height float _nearClip; // Distance to near clipping plane float _farClip; // Distance to far clipping plane Mat4 _projectionMatrix; public: Camera3d(int _width, int _height); virtual ~Camera3d(); Mat4& getViewMatrix() { return _viewMatrix; } Mat4& getProjectionMatrix() { return _projectionMatrix; } // Get the eye position Vec3& getEye() { return _eye; } // Set the eye postion void setEye(float x, float y, float z) { _eye.x = x; _eye.y = y; _eye.z = z; setViewMatrix(); } // Set lookat (target) postion void setLookat(float x, float y, float z) { _lookat.x = x; _lookat.y = y; _lookat.z = z; setViewMatrix(); } // Set FOV in degree void setFov(float fov) { _fov = fov; setPeojectionMatrix(); } protected: void setViewMatrix() { Mat4::createLookAt(_eye, _lookat, _up, &_viewMatrix); } void setPeojectionMatrix() { Mat4::createPerspective(_fov, (GLfloat)_screenWidth / _screenHeight, _nearClip, _farClip, &_projectionMatrix); } }; #endif
package com.taro.backspring; import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; public class <API key> { public static Date convert(String line) throws ParseException { if (line.contains("Strategy finished")) { String [] tokens = line.split("\\|"); String interestingToken = tokens[2]; interesting<API key>.trim(); String [] detailedTokens = interestingToken.split("\\s+"); String dateToken = detailedTokens[0].trim(); String timeToken = detailedTokens[1].trim(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); Date parsedDate = formatter.parse(dateToken + " " + timeToken); return parsedDate; } else { return null; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using DataTables.AspNet.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace DataTables.AspNet.Samples.AspNetCore.BasicIntegration { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // DataTables.AspNet registration with default options. services.RegisterDataTables(); } public void Configure(IApplicationBuilder app) { // Add static files to the request pipeline. app.UseStaticFiles(); // Adds dev exception page for better debug experience. app.<API key>(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); // Uncomment the following line to add a route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); }); } } }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>SHA256</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/expect.js/0.2.0/expect.min.js"></script> <script src="../src/sha256.js"></script> </head> <body> <div id="mocha"></div> <script> mocha.setup('bdd'); </script> <script src="test.js"></script> <script> mocha.checkLeaks(); mocha.run(); </script> </body> </html>
// This is a Controller mixin to add methods for generating Swagger data. // __Dependencies__ var mongoose = require('mongoose'); var utils = require('./utils'); var params = require('./parameters'); // __Private Members__ // __Module Definition__ module.exports = function () { var controller = this; // __Private Instance Members__ function buildTags(resourceName) { return [ resourceName ]; } function buildResponsesFor(isInstance, verb, resourceName, pluralName) { var responses = {}; //default errors on baucis httpStatus code + string responses.default = { description: 'Unexpected error.', schema: { 'type': 'string' } }; if (isInstance || verb==='post') { responses['200'] = { description: 'Sucessful response. Single resource.', schema: { '$ref': '#/definitions/' + utils.capitalize(resourceName) } }; } else { responses['200'] = { description: 'Sucessful response. Collection of resources.', schema: { type: 'array', items: { $ref: '#/definitions/' + utils.capitalize(resourceName) } } }; } // Add other errors if needed: (400, 403, 412 etc. ) responses['404'] = { description: (isInstance) ? 'No ' + resourceName + ' was found with that ID.' : 'No ' + pluralName + ' matched that query.', schema: { 'type': 'string' //'$ref': '#/definitions/ErrorModel' } }; if (verb === 'put' || verb==='post' || verb==='patch') { responses['422'] = { description: 'Validation error.', schema: { type: 'array', items: { '$ref': '#/definitions/ValidationError' } } }; } return responses; } function buildSecurityFor() { return null; //no security defined } function buildOperationInfo(res, operationId, summary, description) { res.operationId = operationId; res.summary = summary; res.description = description; return res; } function buildBaseOperation(mode, verb, controller) { var resourceName = controller.model().singular(); var pluralName = controller.model().plural(); var isInstance = (mode === 'instance'); var resourceKey = utils.capitalize(resourceName); var res = { //consumes: ['application/json'], //if used overrides global definition //produces: ['application/json'], //if used overrides global definition parameters: params.<API key>(isInstance, verb, controller), responses: buildResponsesFor(isInstance, verb, resourceName, pluralName) }; if (res.parameters.length === 0) { delete(res.parameters); } var sec = buildSecurityFor(); if (sec) { res.security = sec; } if (isInstance) { return <API key>(verb, res, resourceKey, resourceName); } else { //collection return <API key>(verb, res, resourceKey, pluralName); } } function <API key>(verb, res, resourceKey, resourceName) { if ('get' === verb) { return buildOperationInfo(res, 'get' + resourceKey + 'ById', 'Get a ' + resourceName + ' by its unique ID', 'Retrieve a ' + resourceName + ' by its ID' + '.'); } else if ('put' === verb) { return buildOperationInfo(res, 'update' + resourceKey, 'Modify a ' + resourceName + ' by its unique ID', 'Update an existing ' + resourceName + ' by its ID' + '.'); } else if ('delete' === verb) { return buildOperationInfo(res, 'delete' + resourceKey + 'ById', 'Delete a ' + resourceName + ' by its unique ID', 'Deletes an existing ' + resourceName + ' by its ID' + '.'); } } function <API key>(verb, res, resourceKey, pluralName) { if ('get' === verb) { return buildOperationInfo(res, 'query' + resourceKey, 'Query some ' + pluralName, 'Query over ' + pluralName + '.'); } else if ('post' === verb) { return buildOperationInfo(res, 'create' + resourceKey, 'Create some ' + pluralName, 'Create one or more ' + pluralName + '.'); } else if ('delete' === verb) { return buildOperationInfo(res, 'delete' + resourceKey + 'ByQuery', 'Delete some ' + pluralName + ' by query', 'Delete all ' + pluralName + ' matching the specified query.'); } } function buildOperation(containerPath, mode, verb) { var resourceName = controller.model().singular(); var operation = buildBaseOperation(mode, verb, controller); operation.tags = buildTags(resourceName); containerPath[verb] = operation; return operation; } // Convert a Mongoose type into a Swagger type function swagger20TypeFor(type) { if (!type) { return null; } if (type === Number) { return 'number'; } if (type === Boolean) { return 'boolean'; } if (type === String || type === Date || type === mongoose.Schema.Types.ObjectId || type === mongoose.Schema.Types.Oid) { return 'string'; } if (type === mongoose.Schema.Types.Array || Array.isArray(type) || type.name === "Array") { return 'array'; } if (type === Object || type instanceof Object || type === mongoose.Schema.Types.Mixed || type === mongoose.Schema.Types.Buffer) { return null; } throw new Error('Unrecognized type: ' + type); } function <API key>(type) { if (!type) { return null; } if (type === Number) { return 'double'; } if (type === Date) { return 'date-time'; } return null; } function skipProperty(name, path, controller) { var select = controller.select(); var mode = (select && select.match(/(?:^|\s)[-]/g)) ? 'exclusive' : 'inclusive'; var <API key> = new RegExp('\\B-' + name + '\\b', 'gi'); var <API key> = new RegExp('(?:\\B[+]|\\b)' + name + '\\b', 'gi'); // Keep deselected paths private if (path.selected === false) { return true; } // _id always included unless explicitly excluded? // If it's excluded, skip this one. if (select && mode === 'exclusive' && select.match(<API key>)) { return true; } // If the mode is inclusive but the name is not present, skip this one. if (select && mode === 'inclusive' && name !== '_id' && !select.match(<API key>)) { return true; } return false; } // A method used to generated a Swagger property for a model function <API key>(name, path, definitionName) { var property = {}; var type = path.options.type ? swagger20TypeFor(path.options.type) : 'string'; // virtuals don't have type if (skipProperty(name, path, controller)) { return; } // Configure the property if (path.options.type === mongoose.Schema.Types.ObjectId) { if ("_id" === name) { property.type = 'string'; } else if (path.options.ref) { property.$ref = '#/definitions/' + utils.capitalize(path.options.ref); } } else if (path.schema) { //Choice (1. embed schema here or 2. reference and publish as a root definition) property.type = 'array'; property.items = { //2. reference $ref: '#/definitions/'+ definitionName + utils.capitalize(name) }; } else { property.type = type; if ('array' === type) { if (isArrayOfRefs(path.options.type)) { property.items = { type: 'string' //handle references as string (serialization for objectId) }; } else { var resolvedType = referenceForType(path.options.type); if (resolvedType.isPrimitive) { property.items = { type: resolvedType.type }; } else { property.items = { $ref: resolvedType.type }; } } } var format = <API key>(path.options.type); if (format) { property.format = format; } if ('__v' === name) { property.format = 'int32'; } } /* // Set enum values if applicable if (path.enumValues && path.enumValues.length > 0) { // Pending: property.allowableValues = { valueType: 'LIST', values: path.enumValues }; } // Set allowable values range if min or max is present if (!isNaN(path.options.min) || !isNaN(path.options.max)) { // Pending: property.allowableValues = { valueType: 'RANGE' }; } if (!isNaN(path.options.min)) { // Pending: property.allowableValues.min = path.options.min; } if (!isNaN(path.options.max)) { // Pending: property.allowableValues.max = path.options.max; } */ if (!property.type && !property.$ref) { warnInvalidType(name, path); property.type = 'string'; } return property; } function referenceForType(type) { if (type && type.length>0 && type[0]) { var sw2Type = swagger20TypeFor(type[0]); if (sw2Type) { return { isPrimitive: true, type: sw2Type //primitive type }; } else { return { isPrimitive: false, type: '#/definitions/' + type[0].name //not primitive: asume complex type def and reference }; } } return { isPrimitive: true, type: 'string' }; //No info provided } function isArrayOfRefs(type) { return (type && type.length > 0 && type[0].ref && type[0].type && type[0].type.name === 'ObjectId'); } function warnInvalidType(name, path) { console.log('Warning: That field type is not yet supported in baucis Swagger definitions, using "string."'); console.log('Path name: %s.%s', utils.capitalize(controller.model().singular()), name); console.log('Mongoose type: %s', path.options.type); } function mergePaths(definition, pathsCollection, definitionName) { Object.keys(pathsCollection).forEach(function (name) { var path = pathsCollection[name]; var property = <API key>(name, path, definitionName); definition.properties[name] = property; if (path.options.required) { definition.required.push(name); } }); } // A method used to generate a Swagger model definition for a controller function <API key>(schema, definitionName) { var definition = { required: [], properties: {} }; mergePaths(definition, schema.paths, definitionName); mergePaths(definition, schema.virtuals, definitionName); //remove empty arrays -> swagger 2.0 validates if (definition.required.length === 0) { delete(definition.required); } if (definition.properties.length === 0) { delete(definition.properties); } return definition; } function <API key>(defs, collectionPaths, definitionName) { Object.keys(collectionPaths).forEach(function (name) { var path = collectionPaths[name]; if (path.schema) { var newdefinitionName = definitionName + utils.capitalize(name); //<-- synthetic name (no info for this in input model) var def = <API key>(path.schema, newdefinitionName); defs[newdefinitionName] = def; } }); } function <API key>(defs, definitionName) { var schema = controller.model().schema; <API key>(defs, schema.paths, definitionName); <API key>(defs, schema.virtuals, definitionName); } // __Build the Definition__ controller.generateSwagger2 = function () { if (controller.swagger2) { return controller; } var modelName = utils.capitalize(controller.model().singular()); controller.swagger2 = { paths: {}, definitions: {} }; // Add Resource Model controller.swagger2.definitions[modelName] = <API key>(controller.model().schema, modelName); <API key>(controller.swagger2.definitions, modelName); // Paths var pluralName = controller.model().plural(); var collectionPath = '/' + pluralName; var instancePath = '/' + pluralName + '/{id}'; var paths = {}; buildPathParams(paths, instancePath, true); buildPathParams(paths, collectionPath, false); buildOperation(paths[instancePath], 'instance', 'get'); buildOperation(paths[instancePath], 'instance', 'put'); buildOperation(paths[instancePath], 'instance', 'delete'); buildOperation(paths[collectionPath], 'collection', 'get'); buildOperation(paths[collectionPath], 'collection', 'post'); buildOperation(paths[collectionPath], 'collection', 'delete'); controller.swagger2.paths = paths; return controller; }; function buildPathParams(pathContainer, path, isInstance) { var pathParams = params.<API key>(isInstance); if (pathParams.length > 0) { pathContainer[path] = { parameters : pathParams }; } } return controller; };
helpers do def clothes possible_reports = { "clear-day" => "It's going to be a nice day, wear something light & casual. Today is a good day for those new shoes ", "clear-night" => "Wear your party clothes, because it's a nice night to hit the town in that cute outfit ", "rain" => "GETCHA UMBRELLA AND RAIN BOOTS CAUSE YOU GON' BE WET ", "snow" => "Get your hot coco cup ready, and wear the biggest coat in your house that you can find ", "sleet" => "SLEET?! ALL the wetness - wear your rain boots, and a poncho, shit's going down in the sky ", "wind" => "DO NOT, and I repeat, DO NOT wear a skirt today. Bundle up with a wind breaker and some closed toed shoes ", "fog" => "It will be a little crisp due to the fog today, so bundle up in a comfy sweater and jeans - but the fog wears off, so remeber to wear something under the sweater ", "cloudy" => "Lay off the sandals and crop tops, today is a cloudy day! Stay close to your sweaters and hoodies ", "partly-cloudy-day" => "It's colder right now, but it could warm up later. Wear something cozy and warm, but make sure you have layers to take off for later ", "partly-cloudy-night" => "If you're trying to party tonight, definitely bring a jacket", "hail" => "Screw the clothes, go park your car under something so those golf balls outside don't cost you a leg and an arm in auto work ", "thunderstorm" => "Grab your thunder buddy, the sky is ANGRY. Big chance of rain, wear something waterproof ", "tornado" => "HIDE YO KEYS HIDE YO WIFE, screw the clothes, get to your basement " } end end
package r2router import ( "github.com/stretchr/testify/assert" //"fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestRouter(t *testing.T) { router := NewRouter() router.Get("/user/keys/", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("GET:/user/keys")) }) router.Post("/user/keys/", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("POST:/user/keys")) }) router.Put("/user/keys/:id", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("PUT:/user/keys/:id," + p.Get("id"))) }) router.Delete("/user/keys/:id", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("DELETE:/user/keys/:id," + p.Get("id"))) }) router.Get("/user/keys/:id", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("GET:/user/keys/:id," + p.Get("id"))) }) ts := httptest.NewServer(router) defer ts.Close() // get res, err := http.Get(ts.URL + "/user/keys/testing") assert.Nil(t, err) content, err := ioutil.ReadAll(res.Body) res.Body.Close() assert.Nil(t, err) assert.Equal(t, string(content), "GET:/user/keys/:id,testing") // Get all res, err = http.Get(ts.URL + "/user/keys") assert.Nil(t, err) content, err = ioutil.ReadAll(res.Body) res.Body.Close() assert.Nil(t, err) assert.Equal(t, string(content), "GET:/user/keys") // post res, err = http.Post(ts.URL+"/user/keys", "", nil) assert.Nil(t, err) content, err = ioutil.ReadAll(res.Body) res.Body.Close() assert.Nil(t, err) assert.Equal(t, string(content), "POST:/user/keys") // put client := &http.Client{} req, err := http.NewRequest("PUT", ts.URL+"/user/keys/testing", nil) res, err = client.Do(req) content, err = ioutil.ReadAll(res.Body) res.Body.Close() assert.Equal(t, string(content), "PUT:/user/keys/:id,testing") // delete req, err = http.NewRequest("DELETE", ts.URL+"/user/keys/testing", nil) res, err = client.Do(req) content, err = ioutil.ReadAll(res.Body) res.Body.Close() assert.Equal(t, string(content), "DELETE:/user/keys/:id,testing") // options req, err = http.NewRequest("OPTIONS", ts.URL+"/user/keys/testing", nil) res, err = client.Do(req) res.Body.Close() assert.Contains(t, res.Header.Get("Allow"), "GET") assert.Contains(t, res.Header.Get("Allow"), "PUT") assert.Contains(t, res.Header.Get("Allow"), "DELETE") } func <API key>(t *testing.T) { router := NewRouter() router.Get("/user/keys/:id", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("GET:/user/keys/:id," + p.Get("id"))) }) ts := httptest.NewServer(router) defer ts.Close() client := &http.Client{} req, err := http.NewRequest("DELETE", ts.URL+"/user/keys/testing", nil) assert.Nil(t, err) res, err := client.Do(req) res.Body.Close() assert.Equal(t, res.StatusCode, http.<API key>) } func <API key>(t *testing.T) { router := NewRouter() router.MethodNotAllowed = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.<API key>) w.Write([]byte("Hello")) } router.Get("/user/keys/:id", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("GET:/user/keys/:id," + p.Get("id"))) }) ts := httptest.NewServer(router) defer ts.Close() client := &http.Client{} req, err := http.NewRequest("DELETE", ts.URL+"/user/keys/testing", nil) assert.Nil(t, err) res, err := client.Do(req) content, err := ioutil.ReadAll(res.Body) res.Body.Close() assert.Equal(t, string(content), "Hello") assert.Equal(t, res.StatusCode, http.<API key>) } func <API key>(t *testing.T) { router := NewRouter() router.AddHandler("OPTIONS", "/users/", func(w http.ResponseWriter, r *http.Request, p Params) { w.Header().Add("Allow", "GET, POST") }) ts := httptest.NewServer(router) defer ts.Close() client := &http.Client{} // custom req, _ := http.NewRequest("OPTIONS", ts.URL+"/users/", nil) res2, _ := client.Do(req) res2.Body.Close() assert.Equal(t, res2.Header.Get("Allow"), "GET, POST") } func TestRouterNotFound(t *testing.T) { router := NewRouter() ts := httptest.NewServer(router) defer ts.Close() res, err := http.Get(ts.URL + "/user/keys/testing") assert.Nil(t, err) res.Body.Close() assert.Equal(t, res.StatusCode, http.StatusNotFound) } func <API key>(t *testing.T) { router := NewRouter() router.NotFound = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) w.Write([]byte("Boo")) } ts := httptest.NewServer(router) defer ts.Close() res, err := http.Get(ts.URL + "/user/keys/testing") assert.Nil(t, err) content, err := ioutil.ReadAll(res.Body) res.Body.Close() assert.Equal(t, res.StatusCode, http.StatusNotFound) assert.Equal(t, content, []byte("Boo")) } func <API key>(t *testing.T) { router := NewRouter() router.Get("/:page", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("GET:/:page," + p.Get("page"))) }) router.Get("/user/keys/:id", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("GET:/user/keys/:id," + p.Get("id"))) }) ts := httptest.NewServer(router) defer ts.Close() client := &http.Client{} req, err := http.NewRequest("GET", ts.URL+"/testing", nil) assert.Nil(t, err) res, err := client.Do(req) content, err := ioutil.ReadAll(res.Body) res.Body.Close() assert.Equal(t, string(content), "GET:/:page,testing") req, err = http.NewRequest("GET", ts.URL+"/user/keys/testing", nil) assert.Nil(t, err) res, err = client.Do(req) content, err = ioutil.ReadAll(res.Body) res.Body.Close() assert.Equal(t, string(content), "GET:/user/keys/:id,testing") } func TestRouterDump(t *testing.T) { router := NewRouter() router.Get("/:page", func(w http.ResponseWriter, r *http.Request, p Params) { w.Write([]byte("GET:/:page," + p.Get("page"))) }) assert.Contains(t, router.Dump(), " |\n -- \n |\n -- :page (<") }
package sparkConfig import org.apache.spark.SparkConf trait BaseSparkConf { def sparkConf(map: scala.collection.immutable.HashMap[String, String]): SparkConf }
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your need! */ class <API key> extends AbstractMigration { public function up(Schema $schema) { // this up() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("ALTER TABLE Comment CHANGE date date DATETIME NOT NULL"); $this->addSql("ALTER TABLE Post CHANGE date date DATETIME NOT NULL"); } public function down(Schema $schema) { // this down() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("ALTER TABLE Comment CHANGE date date DATE NOT NULL"); $this->addSql("ALTER TABLE Post CHANGE date date DATE NOT NULL"); } }
var express = require("express"); var router = new express.Router(); var List = require("../../lib/task"); // Tasks sub-route var tasks = require("./tasks"); router.use("/:list_id/tasks", tasks); router.param("list_id", function (req, res, next, listId) { List.findById(listId, function(err, list) { if (err) return next(err); if (!list) { var notFound = new Error('Resource not found') notFound.status = 404; return next(notFound); } if (!list.owner.equals(req.user._id)) { var fobidden = new Error('Fobidden') fobidden.status = 403; return next(fobidden); } req.appData = req.appData || {}; req.appData.list = list; return next(); }); }); router.get("/", function (req, res) { List.find({ owner: req.user}, function(err, lists) { if (err) throw err; res.status(200).send(lists); }); }); router.post("/", function (req, res) { var list = new List(); list.name = req.body.name; list.owner = req.user; list.save(function(err, newList) { if (err) throw err; res.status(201).send(newList); }); }); router.get("/:list_id", function (req, res) { res.status(200).send(req.appData.list); }); router.put("/:list_id", function (req, res) { req.appData.list.name = req.body.name; req.appData.list.save(function(err, updatedDoc) { res.status(204).send(updatedDoc); }); }); router.delete("/:list_id", function (req, res) { req.appData.list.remove(function(err, removedDoc) { res.status(204).send(removedDoc); }); }); module.exports = router;
using System; using System.Data; using System.IO; using LinqToDB; using LinqToDB.Data; using LinqToDB.DataProvider.Access; using NUnit.Framework; namespace Tests.Create { using Model; [TestFixture] public class CreateData : TestBase { static void RunScript(string configString, string divider, string name, Action<IDbConnection> action = null) { Console.WriteLine("=== " + name + " === \n"); var text = File.ReadAllText(@"..\..\..\..\Data\Create Scripts\" + name + ".sql"); while (true) { var idx = text.IndexOf("SKIP " + configString + " BEGIN"); if (idx >= 0) text = text.Substring(0, idx) + text.Substring(text.IndexOf("SKIP " + configString + " END", idx)); else break; } var cmds = text.Replace("\r", "").Replace(divider, "\x1").Split('\x1'); Exception exception = null; using (var db = new TestDataConnection(configString)) { foreach (var cmd in cmds) { var command = cmd.Trim(); if (command.Length == 0) continue; try { Console.WriteLine(command); db.Execute(command); Console.WriteLine("\nOK\n"); } catch (Exception ex) { if (command.TrimStart().StartsWith("DROP")) Console.WriteLine("\nnot too OK\n"); else { Console.WriteLine(ex.Message); Console.WriteLine("\nFAILED\n"); if (exception == null) exception = ex; } } } if (exception != null) throw exception; Console.WriteLine("\nBulkCopy LinqDataTypes\n"); db.BulkCopy( new [] { new LinqDataTypes { ID = 1, MoneyValue = 1.11m, DateTimeValue = new DateTime(2001, 1, 11, 1, 11, 21, 100), BoolValue = true, GuidValue = new Guid("<API key>"), SmallIntValue = 1 }, new LinqDataTypes { ID = 2, MoneyValue = 2.49m, DateTimeValue = new DateTime(2005, 5, 15, 5, 15, 25, 500), BoolValue = false, GuidValue = new Guid("<API key>"), SmallIntValue = 2 }, new LinqDataTypes { ID = 3, MoneyValue = 3.99m, DateTimeValue = new DateTime(2009, 9, 19, 9, 19, 29, 90), BoolValue = true, GuidValue = new Guid("<API key>"), SmallIntValue = 3 }, new LinqDataTypes { ID = 4, MoneyValue = 4.50m, DateTimeValue = new DateTime(2009, 9, 20, 9, 19, 29, 90), BoolValue = false, GuidValue = new Guid("<API key>"), SmallIntValue = 4 }, new LinqDataTypes { ID = 5, MoneyValue = 5.50m, DateTimeValue = new DateTime(2009, 9, 21, 9, 19, 29, 90), BoolValue = true, GuidValue = new Guid("<API key>"), SmallIntValue = 5 }, new LinqDataTypes { ID = 6, MoneyValue = 6.55m, DateTimeValue = new DateTime(2009, 9, 22, 9, 19, 29, 90), BoolValue = false, GuidValue = new Guid("<API key>"), SmallIntValue = 6 }, new LinqDataTypes { ID = 7, MoneyValue = 7.00m, DateTimeValue = new DateTime(2009, 9, 23, 9, 19, 29, 90), BoolValue = true, GuidValue = new Guid("<API key>"), SmallIntValue = 7 }, new LinqDataTypes { ID = 8, MoneyValue = 8.99m, DateTimeValue = new DateTime(2009, 9, 24, 9, 19, 29, 90), BoolValue = false, GuidValue = new Guid("<API key>"), SmallIntValue = 8 }, new LinqDataTypes { ID = 9, MoneyValue = 9.63m, DateTimeValue = new DateTime(2009, 9, 25, 9, 19, 29, 90), BoolValue = true, GuidValue = new Guid("<API key>"), SmallIntValue = 9 }, new LinqDataTypes { ID = 10, MoneyValue = 10.77m, DateTimeValue = new DateTime(2009, 9, 26, 9, 19, 29, 90), BoolValue = false, GuidValue = new Guid("<API key>"), SmallIntValue = 10 }, new LinqDataTypes { ID = 11, MoneyValue = 11.45m, DateTimeValue = new DateTime(2009, 9, 27, 9, 19, 29, 90), BoolValue = true, GuidValue = new Guid("<API key>"), SmallIntValue = 11 }, new LinqDataTypes { ID = 12, MoneyValue = 11.45m, DateTimeValue = new DateTime(2012, 11, 7, 19, 19, 29, 90), BoolValue = true, GuidValue = new Guid("<API key>"), SmallIntValue = 12 } }); Console.WriteLine("\nBulkCopy Parent\n"); db.BulkCopy( new [] { new Parent { ParentID = 1, Value1 = 1 }, new Parent { ParentID = 2, Value1 = null }, new Parent { ParentID = 3, Value1 = 3 }, new Parent { ParentID = 4, Value1 = null }, new Parent { ParentID = 5, Value1 = 5 }, new Parent { ParentID = 6, Value1 = 6 }, new Parent { ParentID = 7, Value1 = 1 } }); Console.WriteLine("\nBulkCopy Child\n"); db.BulkCopy( new [] { new Child { ParentID = 1, ChildID = 11 }, new Child { ParentID = 2, ChildID = 21 }, new Child { ParentID = 2, ChildID = 22 }, new Child { ParentID = 3, ChildID = 31 }, new Child { ParentID = 3, ChildID = 32 }, new Child { ParentID = 3, ChildID = 33 }, new Child { ParentID = 4, ChildID = 41 }, new Child { ParentID = 4, ChildID = 42 }, new Child { ParentID = 4, ChildID = 43 }, new Child { ParentID = 4, ChildID = 44 }, new Child { ParentID = 6, ChildID = 61 }, new Child { ParentID = 6, ChildID = 62 }, new Child { ParentID = 6, ChildID = 63 }, new Child { ParentID = 6, ChildID = 64 }, new Child { ParentID = 6, ChildID = 65 }, new Child { ParentID = 6, ChildID = 66 }, new Child { ParentID = 7, ChildID = 77 } }); Console.WriteLine("\nBulkCopy GrandChild\n"); db.BulkCopy( new [] { new GrandChild { ParentID = 1, ChildID = 11, GrandChildID = 111 }, new GrandChild { ParentID = 2, ChildID = 21, GrandChildID = 211 }, new GrandChild { ParentID = 2, ChildID = 21, GrandChildID = 212 }, new GrandChild { ParentID = 2, ChildID = 22, GrandChildID = 221 }, new GrandChild { ParentID = 2, ChildID = 22, GrandChildID = 222 }, new GrandChild { ParentID = 3, ChildID = 31, GrandChildID = 311 }, new GrandChild { ParentID = 3, ChildID = 31, GrandChildID = 312 }, new GrandChild { ParentID = 3, ChildID = 31, GrandChildID = 313 }, new GrandChild { ParentID = 3, ChildID = 32, GrandChildID = 321 }, new GrandChild { ParentID = 3, ChildID = 32, GrandChildID = 322 }, new GrandChild { ParentID = 3, ChildID = 32, GrandChildID = 323 }, new GrandChild { ParentID = 3, ChildID = 33, GrandChildID = 331 }, new GrandChild { ParentID = 3, ChildID = 33, GrandChildID = 332 }, new GrandChild { ParentID = 3, ChildID = 33, GrandChildID = 333 }, new GrandChild { ParentID = 4, ChildID = 41, GrandChildID = 411 }, new GrandChild { ParentID = 4, ChildID = 41, GrandChildID = 412 }, new GrandChild { ParentID = 4, ChildID = 41, GrandChildID = 413 }, new GrandChild { ParentID = 4, ChildID = 41, GrandChildID = 414 }, new GrandChild { ParentID = 4, ChildID = 42, GrandChildID = 421 }, new GrandChild { ParentID = 4, ChildID = 42, GrandChildID = 422 }, new GrandChild { ParentID = 4, ChildID = 42, GrandChildID = 423 }, new GrandChild { ParentID = 4, ChildID = 42, GrandChildID = 424 } }); if (action != null) action(db.Connection); } } [Test, <API key>(ProviderName.DB2)] public void DB2 (string ctx) { RunScript(ctx, "\nGO\n", "DB2"); } [Test, <API key>(ProviderName.Informix)] public void Informix (string ctx) { RunScript(ctx, "\nGO\n", "Informix", InformixAction); } [Test, <API key>(ProviderName.Oracle)] public void Oracle (string ctx) { RunScript(ctx, "\n/\n", "Oracle"); } [Test, <API key>(ProviderName.Firebird)] public void Firebird (string ctx) { RunScript(ctx, "COMMIT;", "Firebird"); } [Test, <API key>(ProviderName.PostgreSQL)] public void PostgreSQL (string ctx) { RunScript(ctx, "\nGO\n", "PostgreSQL"); } [Test, <API key>(ProviderName.MySql)] public void MySql (string ctx) { RunScript(ctx, "\nGO\n", "MySql"); } [Test, <API key>(ProviderName.SqlServer2000)] public void Sql2000 (string ctx) { RunScript(ctx, "\nGO\n", "SqlServer2000"); } [Test, <API key>(ProviderName.SqlServer2005)] public void Sql2005 (string ctx) { RunScript(ctx, "\nGO\n", "SqlServer"); } [Test, <API key>(ProviderName.Sybase)] public void Sybase (string ctx) { RunScript(ctx, "\nGO\n", "Sybase"); } [Test, <API key>(ProviderName.SqlServer2008)] public void Sql2008 (string ctx) { RunScript(ctx, "\nGO\n", "SqlServer"); } [Test, <API key>(ProviderName.SqlServer2012)] public void Sql2012 (string ctx) { RunScript(ctx, "\nGO\n", "SqlServer"); } [Test, <API key>(ProviderName.SqlServer2014)] public void Sql2014 (string ctx) { RunScript(ctx, "\nGO\n", "SqlServer"); } [Test, <API key>("SqlAzure.2012")] public void SqlAzure2012 (string ctx) { RunScript(ctx, "\nGO\n", "SqlServer"); } [Test, <API key>(ProviderName.SqlCe)] public void SqlCe (string ctx) { RunScript(ctx, "\nGO\n", "SqlCe"); } [Test, <API key>(ProviderName.SqlCe)] public void SqlCeData (string ctx) { RunScript(ctx+ ".Data", "\nGO\n", "SqlCe"); } [Test, <API key>(ProviderName.SQLite)] public void SQLite (string ctx) { RunScript(ctx, "\nGO\n", "SQLite", SQLiteAction); } [Test, <API key>(ProviderName.SQLite)] public void SQLiteData (string ctx) { RunScript(ctx+ ".Data", "\nGO\n", "SQLite", SQLiteAction); } [Test, <API key>(ProviderName.Access)] public void Access (string ctx) { RunScript(ctx, "\nGO\n", "Access", AccessAction); } [Test, <API key>(ProviderName.Access)] public void AccessData (string ctx) { RunScript(ctx+ ".Data", "\nGO\n", "Access", AccessAction); } [Test, <API key>(ProviderName.SapHana)] public void SapHana (string ctx) { RunScript(ctx, ";;\n" , "SapHana"); } static void AccessAction(IDbConnection connection) { using (var conn = AccessTools.<API key>(connection)) { conn.Execute(@" INSERT INTO AllTypes ( bitDataType, decimalDataType, smallintDataType, intDataType,tinyintDataType, moneyDataType, floatDataType, realDataType, datetimeDataType, charDataType, varcharDataType, textDataType, ncharDataType, nvarcharDataType, ntextDataType, binaryDataType, varbinaryDataType, imageDataType, oleobjectDataType, <API key> ) VALUES ( 1, 2222222, 25555, 7777777, 100, 100000, 20.31, 16.2, @datetimeDataType, '1', '234', '567', '23233', '3323', '111', @binaryDataType, @varbinaryDataType, @imageDataType, @oleobjectDataType, @<API key> )", new { datetimeDataType = new DateTime(2012, 12, 12, 12, 12, 12), binaryDataType = new byte[] { 1, 2, 3, 4 }, varbinaryDataType = new byte[] { 1, 2, 3, 5 }, imageDataType = new byte[] { 3, 4, 5, 6 }, oleobjectDataType = new byte[] { 5, 6, 7, 8 }, <API key> = new Guid("{<API key>}"), }); } } static void SQLiteAction(IDbConnection connection) { using (var conn = LinqToDB.DataProvider.SQLite.SQLiteTools.<API key>(connection)) { conn.Execute(@" UPDATE AllTypes SET binaryDataType = @binaryDataType, varbinaryDataType = @varbinaryDataType, imageDataType = @imageDataType, <API key> = @<API key> WHERE ID = 2", new { binaryDataType = new byte[] { 1 }, varbinaryDataType = new byte[] { 2 }, imageDataType = new byte[] { 0, 0, 0, 3 }, <API key> = new Guid("{<API key>}"), }); } } static void InformixAction(IDbConnection connection) { using (var conn = LinqToDB.DataProvider.Informix.InformixTools.<API key>(connection)) { conn.Execute(@" UPDATE AllTypes SET byteDataType = ? WHERE ID = 2", new { blob = new byte[] { 1, 2 }, }); } } } }
import java.util.*; import java.util.regex.*; public class RegisterGraph { public class RegisterColoring { public HashMap<String, List<String>> registers; public List<String> spills; } private List<String> ints = Arrays.asList("$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7", "$t8", "$t9"); private List<String> floats = Arrays.asList("$f4", "$f5", "$f6", "$f7", "$f8", "$f9", "f10", "$f16", "$f17", "$f18"); private List<Interval> intIntervals; private List<Interval> intSpills; private List<Interval> floatIntervals; public RegisterGraph() { intIntervals = new LinkedList<Interval>(); floatIntervals = new LinkedList<Interval>(); } public void addIntInterval(Interval i) { intIntervals.add(i); } public void addFloatInterval(Interval i) { floatIntervals.add(i); } private RegisterColoring color(List<String> colors, int colorLimit, List<Interval> intervals) { int iMax = 0; for (Interval i : intervals) { iMax = Math.max(iMax, i.end); } HashMap<String, List<String>> iGraph = new HashMap<String, List<String>>(); @SuppressWarnings("unchecked") List<String>[] iVars = (LinkedList<String>[]) new LinkedList[iMax]; // Set up the intervals in an array for (Interval i : intervals) { iGraph.put(i.var, new LinkedList<String>()); for (int idx = i.start; idx <= i.end; idx += 1) { if (!iVars[idx].contains(i)) { iVars[idx].add(i.var); } } } // Construct the graph for (int idx = 0; idx < iMax; idx += 1) { List<String> vars = iVars[idx]; for (String vari : vars) { for (String varj : vars) { if (vari == varj) continue; List<String> neighbors = iGraph.get(vari); if (!neighbors.contains(varj)) { neighbors.add(varj); iGraph.put(vari, neighbors); } } } } // Color the graph LinkedList<String> stack = new LinkedList<String>(); HashMap<String, List<String>> registers = new HashMap<String, List<String>>(); LinkedList<String> spills = new LinkedList<String>(); HashMap<String, List<String>> iGraphScratch = new HashMap<String, List<String>>(iGraph); while (true) { List<String> remove = new LinkedList<String>(); for (String var : iGraphScratch.keySet()) { List<String> neighbors = iGraphScratch.get(var); if (neighbors.size() < colorLimit) { remove.add(var); stack.addLast(var); } } if (remove.size() == 0) { String maxVar = null; int max = 0; for (String var : iGraphScratch.keySet()) { int neighbors = iGraphScratch.get(var).size(); if (neighbors > max) { max = neighbors; remove.clear(); remove.add(var); } } spills.add(maxVar); } if (remove.size() == 0) { break; } for (String vari : remove) { iGraphScratch.remove(vari); for (String varj : iGraphScratch.keySet()) { List<String> neighbors = iGraphScratch.get(varj); neighbors.remove(vari); } } } for (String spill : spills) { // Actually remove the spills iGraph.remove(spill); } while (!stack.isEmpty()) { String var = stack.pollLast(); boolean colored = false; for (int color = 0; color < colorLimit; color += 1) { String register = ints.get(color); boolean valid = true; for (String neighbor : iGraph.get(var)) { if (registers.get(register).contains(neighbor)) { valid = false; break; } } if (valid) { // found a color colored = true; List<String> sharedWith = registers.get(register); sharedWith.add(var); registers.put(register, sharedWith); } } if (!colored) { System.out.println("ERROR: Register coloring failed ... "); System.exit(1); } } RegisterColoring coloring = new RegisterColoring(); coloring.registers = registers; coloring.spills = spills; return coloring; } public RegisterColoring intColoring(int colorLimit) { return color(ints, colorLimit, intIntervals); } public RegisterColoring floatColoring(int colorLimit) { return color(floats, colorLimit, floatIntervals); } public String toString() { StringBuilder str = new StringBuilder(); return str.toString(); } }
"use strict"; CompItem.prototype.forLayers = function (cb) { var layers = this.layers; var numLayers = layers.length; for (var i = 1; i <= numLayers; i++) { cb(layers[i]); } }; CompItem.prototype.forSelectedLayers = function (cb) { var selectedLayers = this.selectedLayers; var numSelectedLayers = selectedLayers.length; if (numSelectedLayers !== 0) { for (var i = 0; i < numSelectedLayers; i++) { cb(selectedLayers[i]); } } };
var stream = require('vinyl-source-stream'), buffer = require('vinyl-buffer'); var builder = require('browserify'); var gulp = require('gulp'), jshint = require('gulp-jshint'), phantom = require('<API key>'), uglify = require('gulp-uglify'), size = require('gulp-size'); var source = './lib/view.js', dest = './dist/'; // Quality Analysis gulp.task('qualify', ['lint', 'test']); // Lint with JSHint gulp.task('lint', function(){ gulp.src('./lib*.js') .pipe(jshint()); }); gulp.task('test', ['build'], function(){ gulp.src('test/index.html') .pipe(phantom()); }); // Compile JavaScript gulp.task('build', function(){ var bndl = builder('./index.js').bundle({ debug: true }); bndl.pipe(stream('bundle.js')) .pipe(buffer()) // .pipe(uglify()) .pipe(gulp.dest('./dist/')) .pipe(size()); }); gulp.task('watch', function(){ gulp.watch('./lib*.js', ['build', 'test']); });
package net.akhyar.android.imgpro.actions; import net.akhyar.android.imgpro.Action; public class Brightness extends Action { private int offset; public Brightness(int offset) { this.offset = offset; } @Override protected void adjustPixels(int[] pixels) { int r, g, b; int[] cache = new int[256]; for (int i = 0; i < cache.length; i++) { cache[i] = clamp(i + offset); } for (int i = 0; i < pixels.length; i++) { r = cache[0xff & (pixels[i] >> 16)]; g = cache[0xff & (pixels[i] >> 8)]; b = cache[0xff & (pixels[i])]; pixels[i] = 0xff000000 + (r << 16) + (g << 8) + b; } } public float getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } }
(function (global) { 'use strict'; var expect = global.expect || require('expect.js'), date = global.date || require('../../date-and-time'), forEach = function (array, fn) { for (var i = 0, len = array.length; i < len; i++) { if (fn(array[i], i) === 0) { break; } } }, MMMM = ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'], MMM = ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'], dddd = ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'], ddd = ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'], dd = ['Do', 'Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa'], A = ['di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', 'di mattina', // 0 - 11 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio', 'di pomerrigio']; // 12 - 23 var locale = typeof require === 'function' ? require('../../locale/it') : 'it'; describe('format with "it"', function () { before(function () { date.locale(locale); }); forEach(MMMM, function (m, i) { it('"MMMM" equals to "' + m + '"', function () { var now = new Date(2015, i, 1, 12, 34, 56, 789); expect(date.format(now, 'MMMM')).to.equal(m); }); }); forEach(MMM, function (m, i) { it('"MMM" equals to "' + m + '"', function () { var now = new Date(2015, i, 1, 12, 34, 56, 789); expect(date.format(now, 'MMM')).to.equal(m); }); }); forEach(dddd, function (d, i) { it('"dddd" equals to "' + d + '"', function () { var now = new Date(2016, 0, i + 3, 12, 34, 56, 789); expect(date.format(now, 'dddd')).to.equal(d); }); }); forEach(ddd, function (d, i) { it('"ddd" equals to "' + d + '"', function () { var now = new Date(2016, 0, i + 3, 12, 34, 56, 789); expect(date.format(now, 'ddd')).to.equal(d); }); }); forEach(dd, function (d, i) { it('"dd" equals to "' + d + '"', function () { var now = new Date(2016, 0, i + 3, 12, 34, 56, 789); expect(date.format(now, 'dd')).to.equal(d); }); }); forEach(A, function (a, i) { it('"A" equals to "' + a + '"', function () { var now = new Date(2016, 0, 1, i, 34, 56, 789); expect(date.format(now, 'A')).to.equal(a); }); }); after(function () { date.locale(typeof require === 'function' ? require('../../locale/en') : 'en'); }); }); describe('parse with "it"', function () { before(function () { date.locale(locale); }); forEach(MMMM, function (m, i) { it('"MMMM"', function () { var now = new Date(1970, i, 1); expect(date.parse(m, 'MMMM')).to.eql(now); }); }); forEach(MMM, function (m, i) { it('"MMM"', function () { var now = new Date(1970, i, 1); expect(date.parse(m, 'MMM')).to.eql(now); }); }); forEach(A, function (a, i) { it('h A', function () { var now = new Date(1970, 0, 1, i); expect(date.parse((i > 11 ? i - 12 : i) + ' ' + a, 'h A')).to.eql(now); }); }); after(function () { date.locale(typeof require === 'function' ? require('../../locale/en') : 'en'); }); }); }(this));
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family", parent_name="funnelarea.title.font", **kwargs ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "plot"), no_blank=kwargs.pop("no_blank", True), role=kwargs.pop("role", "style"), strict=kwargs.pop("strict", True), **kwargs )
// <API key>.cs // MiNG <developer@ming.gz.cn> // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. using System; namespace Aliyun.Api.LogService.Domain.Config { public class <API key> { public String LogstoreName { get; } public <API key>(String logstoreName) { this.LogstoreName = logstoreName; } } }
const mongoose = require('mongoose'); let taskSchema = mongoose.Schema({ title: {type: String, required:true}, status: {type: String, required: true} }); let Task = mongoose.model('Task', taskSchema); module.exports = Task;
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace CodeTiger.CodeAnalysis.Analyzers.Readability { <summary> Analyzes comparisons for readability issues. </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class <API key> : DiagnosticAnalyzer { internal static readonly <API key> <API key> = new <API key>("CT3113", "Literals should not be on the left side of comparison operators.", "Literals should not be on the left side of comparison operators.", "CodeTiger.Readability", DiagnosticSeverity.Warning, true); internal static readonly <API key> <API key> = new <API key>("CT3114", "Constants should not be on the left side of comparison operators.", "Constants should not be on the left side of comparison operators.", "CodeTiger.Readability", DiagnosticSeverity.Warning, true); <summary> Gets a set of descriptors for the diagnostics that this analyzer is capable of producing. </summary> public override ImmutableArray<<API key>> <API key> { get { return ImmutableArray.Create( <API key>, <API key>); } } <summary> Registers actions in an analysis context. </summary> <param name="context">The context to register actions in.</param> <remarks>This method should only be called once, at the start of a session.</remarks> public override void Initialize(AnalysisContext context) { Guard.ArgumentIsNotNull(nameof(context), context); context.<API key>(<API key>.None); context.<API key>(); context.<API key>(AnalyzeComparison, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.<API key>, SyntaxKind.<API key>, SyntaxKind.LessThanExpression, SyntaxKind.<API key>); } private static void AnalyzeComparison(<API key> context) { var node = (<API key>)context.Node; if (IsLiteral(node.Left)) { if (!IsLiteral(node.Right)) { context.ReportDiagnostic(Diagnostic.Create( <API key>, node.Left.GetLocation())); } } else if (context.SemanticModel.GetConstantValue(node.Left, context.CancellationToken).HasValue) { if (!IsLiteral(node.Right) && !context.SemanticModel.GetConstantValue(node.Right, context.CancellationToken).HasValue) { context.ReportDiagnostic(Diagnostic.Create( <API key>, node.Left.GetLocation())); } } } private static bool IsLiteral(ExpressionSyntax node) { switch (node.Kind()) { case SyntaxKind.<API key>: case SyntaxKind.<API key>: case SyntaxKind.<API key>: case SyntaxKind.<API key>: case SyntaxKind.<API key>: case SyntaxKind.<API key>: return true; default: return false; } } } }
#include <debug.h> #include <printf.h> #include <arch/arm/dcc.h> #include <dev/fbcon.h> #include <dev/uart.h> #include <platform/timer.h> static void write_dcc(char c) { uint32_t timeout = 10; /* Note: Smallest sampling rate for DCC is 50us. * This can be changed by SNOOPer.Rate on T32 window. */ while (timeout) { if (dcc_putc(c) == 0) break; udelay(50); timeout } } void _dputc(char c) { #if WITH_DEBUG_DCC if (c == '\n') { write_dcc('\r'); } write_dcc(c) ; #endif #if WITH_DEBUG_UART uart_putc(0, c); #endif #if WITH_DEBUG_FBCON && WITH_DEV_FBCON fbcon_putc(c); #endif #if WITH_DEBUG_JTAG jtag_dputc(c); #endif } int dgetc(char *c, bool wait) { int n; #if WITH_DEBUG_DCC n = dcc_getc(); #elif WITH_DEBUG_UART n = uart_getc(0, 0); #else n = -1; #endif if (n < 0) { return -1; } else { *c = n; return 0; } } void platform_halt(void) { dprintf(INFO, "HALT: spinning forever...\n"); for (;;) ; }
<div> <form> <button type="submit" id="filter" class="btn btn-primary btn-sm" formaction="/History/dateSort">Sort by date</button> <button type="submit" id="filter" class="btn btn-primary btn-sm" formaction="/History/modelSort">Sort by robot model</button> </form> </div> <div class="container"> <h2>History</h2> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th>Id</th> <th>Model</th> <th>Plant</th> <th>Date</th> </tr> </thead> <tbody> {history} <tr> <td>{id}</td> <td>{model}</td> <td>{plant}</td> <td>{stamp}</td> </tr> {/history} </tbody> </table> </div> <?php echo $this->pagination->create_links(); ?> </div>
using UnityEngine; public class Bullet : MonoBehaviour { private Transform target; public float speed = 70f; public int damage = 50; public float explosionRadius; public GameObject impactEffect; public void Seek(Transform _target) { target = _target; } // Update is called once per frame void Update() { if (target == null) { Destroy(gameObject); //Because Destroy sometimes take sometime to activated return; } Vector3 dir = target.position - transform.position; float distanceThisFrame = speed * Time.deltaTime; if (dir.magnitude <= distanceThisFrame) { HitTarget(); return; } transform.Translate(dir.normalized * distanceThisFrame, Space.World); transform.LookAt(target); } private void HitTarget() { GameObject effectIns = (GameObject)Instantiate(impactEffect, transform.position, transform.rotation); Destroy(effectIns, 5f); if (explosionRadius > 0f) Explode(); else Damage(target); Destroy(gameObject); } void Explode() { Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius); foreach (Collider collider in colliders) { if (collider.tag == "Enemy") Damage(collider.transform); } } void Damage(Transform enemy) { Enemy e = enemy.GetComponent<Enemy>(); if (e != null) //Destroy(enemy.gameObject); e.TakeDamage(damage); } void <API key>() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, explosionRadius); } }
<?php namespace Binaerpiloten\MagicBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; /** * User * * @ORM\Table() * @ORM\Entity */ class User extends BaseUser { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return User */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } }
<!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <!-- Place favicon.ico in the root directory --> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="../../css/normalize.css"> <link rel="stylesheet" type="text/css" href="slick/slick.css"/> <link rel="stylesheet" type="text/css" href="slick/slick-theme.css"/> <link rel="stylesheet" href="../../css/main.css"> <script src="../../js/vendor/modernizr-2.8.3.min.js"></script> </head> <body class="contentpage"> <!--[if lt IE 8]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif] <header class="clearfix" > <a href="../../index.html"><img src="../../img/cmdlogowit.png" alt="Hogeschool van Amsterdam" class="cmdlogo"/></a> <img src="../../img/logo.png" alt="Hogeschool van Amsterdam" class="logo"/> </header> <div class="title"> <ul id="dropdownmn"> <li class="selecteditem">Frontend developer</li> <li class="dropdownitem"><a href="../cm/ai.html">Content manager</a></li> <li class="dropdownitem"><a href="../id/ai.html">Interaction designer</a></li> <li class="dropdownitem"><a href="../vd/ai.html">Visual designer</a></li> </ul> </div> <div class="submenu clearfix"> <div class="menulineVD"></div> <ul> <li class="imgli active"><a href="ai.html">Algemene info</a></li> <li class="imgli"><a href="jaareen.html">Vakken eerste jaar</a></li> <li class="imgli"><a href="profilering.html">Profileringsvakken</a></li> <li class="imgli"><a href="vaardigheden.html">Vaardigheden</a></li> <li class="imgli"><a href="interview.html">Interviews</a></li> </ul> </div> <div class="content"> <h1>Algemene info</h1> <img src="../../img/fotoFD.jpg" alt="" /> <p> De content manager gaat over alle content op een website. Content management is het systematisch plannen, ontwikkelen, beheren, distribueren, evalueren en behouden van alle content in een organisatie. Als content manager bepaal je dus de strategie en sta je garant voor kwalitatieve en relevante inhoud op de site. Content managers kunnen worden ingezet in full-time vaste posities, of op freelance basis voor individuele projecten. </p> <!-- slider --> <div id="testit"> <div class="one-time"> <div class="sliderContent">Omzetten van design naar html.</div> <div class="sliderContent">Je bent op de hoogte van de nieuweste snufjes die beschikbaar zijn op het web.</div> <div class="sliderContent">Je speurt in je vrijetijd graag blogs voor informatie.</div> <div class="sliderContent">Je vindt het niet erg om week achter je laptop te zitten.</div> <div class="sliderContent">Vormgeven en bewaken van de huisstijl.</div> </div> </div> <h2>Hoe ga je te werk?</h2> <h3>1. Planfase</h3> <p> In de planfase stel je een contentstrategie op aan de hand van de doelen van je organisatie en de behoeften van de doelgroep. Je ontwikkelt de contentarchitectuur en bepaalt het contentbeleid. </p> <h3>2. Ontwikkelfase</h3> <p> In de ontwikkelfase verzamel je alle content en voorzie je deze van context. Hierbij sta je garant voor de kwaliteit en relevantie van de content. </p> <h3>3. Beheerfase</h3> <p> In de beheerfase manage je de content binnen een contentorganisatie. Je slaat op, beveiligt, beoordeelt en keurt goed. </p> </div> <script src="../../js/plugins.js"></script> <script src="../../js/main.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="slick/slick.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.one-time').slick({ dots: true, infinite: true, speed: 300, slidesToShow: 1, adaptiveHeight: true }); }); $( ".selecteditem" ).click(function() { $( ".dropdownitem" ).toggle( 0, function() { // Animation complete. }); }); </script> </body> </html>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_02) on Wed Oct 17 22:44:35 PDT 2012 --> <title>Uses of Class com.stevenmz.project1.domainTypes.Menu</title> <meta name="date" content="2012-10-17"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.stevenmz.project1.domainTypes.Menu"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/stevenmz/project1/domainTypes/Menu.html" title="class in com.stevenmz.project1.domainTypes">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/stevenmz/project1/domainTypes/\class-useMenu.html" target="_top">Frames</a></li> <li><a href="Menu.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class com.stevenmz.project1.domainTypes.Menu" class="title">Uses of Class<br>com.stevenmz.project1.domainTypes.Menu</h2> </div> <div class="classUseContainer">No usage of com.stevenmz.project1.domainTypes.Menu</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/stevenmz/project1/domainTypes/Menu.html" title="class in com.stevenmz.project1.domainTypes">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/stevenmz/project1/domainTypes/\class-useMenu.html" target="_top">Frames</a></li> <li><a href="Menu.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. package cmd import ( "fmt" "path/filepath" "github.com/boltdb/bolt" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/pinheirolucas/bolt-cli/validator" ) const defaultDBName = "bolt.db" // createCmd represents the create command var createCmd = &cobra.Command{ Use: "create [path to create the database]", Aliases: []string{"new"}, Short: "Create a new empty BoltDB file", Long: `Create (bolt-cli create) will create a new empty BoltDB file with the specified path. If no filename is provided, it will create with the name: "bolt.db". Examples: bolt-cli create ./ bolt-cli create ./dev.db `, Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { er(errors.New("create expects the path of the new BoltDB")) } p := args[0] absp, err := filepath.Abs(p) if err != nil { er(err) } e := filepath.Ext(absp) switch e { case "": isDir, err := validator.DirExists(absp) if err != nil { er(err) } else if !isDir { er(errors.Errorf("%s does not exists", absp)) } absp = filepath.Join(absp, defaultDBName) case ".db": dp := filepath.Dir(absp) isDir, err := validator.DirExists(dp) if err != nil { er(err) } else if !isDir { er(errors.Errorf("%s does not exists", dp)) } default: er(errors.New("the name of DB must have the extension \".db\"")) } _, err = bolt.Open(absp, 0600, bolt.DefaultOptions) if err != nil { er(err) } fmt.Println(fmt.Sprintf("New BoltDB created at: %s", absp)) }, } func init() { RootCmd.AddCommand(createCmd) }
<template name="keywordPage"> <h1>keyword Page</h1> <!-- keyword Card <div class="panel-primary col-sm-6"> <div class="panel-heading" for="inputkeyword"> keyword</div> <div class="list-group"> <ul class="list-group-item"> {{> addkeywordItem}} <p></p> <p> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapsekeyword" aria-expanded="false" aria-controls="collapsekeyword"> keyword Card: </button> </p> <div class="collapse" id="collapsekeyword"> <div class="list-group"> <ul class="list-group-item"> {{#each keywordEach}} {{> keywordItem}} {{/each}} </ul> </div> </div> </ul> </div> </div> <!-- end of keyword card </template> <!-- Start of Add keyword Item <template name="addkeywordItem"> <form> keyword: <input type="text" class="form-control" placeholder="What are your keyword" name="keyworditemName"> </form> </template> <!-- End of Add Keyword Item <!-- Start of Retrieve keyword Item <template name="keywordItem"> <input type="text" value="{{keyworditemName}}" name="keywordItem"> [<a href="#" class="delete-keyworditem"> Delete </a>] </template> <!-- End of keyword Item
package xss.LinkContainer; import java.util.LinkedHashSet; public class XssContainer extends LinkedHashSet<XssStruct> { <API key> callback; @Override public boolean add(XssStruct xssStruct) { boolean wasAdded = super.add(xssStruct); if (wasAdded) if (callback != null) callback.onXssAdded(xssStruct); return wasAdded; } public void setCallback(<API key> callback) { this.callback = callback; } public interface <API key> { public void onXssAdded(XssStruct xssStruct); } }
const {shiphold} = require('../../dist/bundle'); export default ({test}) => { test('should create a service when a definition argument is passed', t => { const registry = shiphold({}); const service = registry.service({table: 'users'}); t.eq(typeof service.select, 'function', 'select method should be defined'); t.eq(typeof service.insert, 'function', 'insert method should be defined'); t.eq(typeof service.delete, 'function', 'delete method should be defined'); t.eq(typeof service.update, 'function', 'update method should be defined'); t.eq(typeof service.if, 'function', 'if method should be defined'); }); test('services should be singletons', t => { const registry = shiphold({}); const service = registry.service({name: 'foo', table: 'users'}); t.eq(service, registry.service('foo'), 'should refer to the same reference'); }); test('should pass default value', t => { const registry = shiphold({}); const service = registry.service({table: 'users'}); t.eq(service.definition.primaryKey, 'id', 'default primaryKey should be "id"'); t.eq(service.definition.name, 'Users', 'default name should be a camel case version of the table name'); }); test('registry should be iterable', t => { const registry = shiphold({}); const service = registry.service({ table: 'users', name: 'foo' }); t.eq(typeof registry[Symbol.iterator], 'function'); const items = [...registry]; t.eq(items, [['foo', service]]); }); }
<?php require __DIR__ . '/bootstrap.php'; $action = isset($_GET['action']) ? $_GET['action'] : ''; // update our session/client if needed. // NOTE: This example uses the session, but you could also be using a database or some other persistance layer. if (isset($_SESSION['access_token']) && $fc->getAccessToken() != $_SESSION['access_token']) { if ($fc->getAccessToken() == '') { $fc->setAccessToken($_SESSION['access_token']); } } if (isset($_SESSION['refresh_token']) && $fc->getRefreshToken() != $_SESSION['refresh_token']) { if ($fc->getRefreshToken() == '') { $fc->setRefreshToken($_SESSION['refresh_token']); } } if (isset($_SESSION['client_id']) && $fc->getClientId() != $_SESSION['client_id']) { if ($fc->getClientId() == '') { $fc->setClientId($_SESSION['client_id']); } } if (isset($_SESSION['client_secret']) && $fc->getClientSecret() != $_SESSION['client_secret']) { if ($fc->getClientSecret() == '') { $fc->setClientSecret($_SESSION['client_secret']); } } if (isset($_SESSION['<API key>']) && $fc-><API key>() != $_SESSION['<API key>']) { if ($fc-><API key>() == '') { $fc-><API key>($_SESSION['<API key>']); } } $fc-><API key>(); // let's see if we have access to a store... if so, bookmark some stuff if ($fc->getAccessToken() != '') { if (!isset($_SESSION['store_uri']) || $_SESSION['store_uri'] == '' || !isset($_SESSION['store_name']) || $_SESSION['store_name'] == '') { $result = $fc->get(); $store_uri = $fc->getLink('fx:store'); //$user_uri = $fc->getLink('fx:user'); //$client_uri = $fc->getLink('fx:client'); if ($store_uri != '') { $_SESSION['store_uri'] = $store_uri; $result = $fc->get($store_uri); $errors = $fc->getErrors($result); if (!count($errors)) { $_SESSION['store_name'] = $result['store_name']; $_SESSION['item_categories_uri'] = $result['_links']['fx:item_categories']['href']; $_SESSION['coupons_uri'] = $result['_links']['fx:coupons']['href']; $_SESSION['transactions_uri'] = $result['_links']['fx:transactions']['href']; $_SESSION['subscriptions_uri'] = $result['_links']['fx:subscriptions']['href']; } //} elseif ($user_uri != '') { // $_SESSION['user_uri'] = $user_uri; //} elseif ($client_uri != '') { // $_SESSION['client_uri'] = $client_uri; } } } ?> <!DOCTYPE html> <html> <head> <title>Example Requests for the Foxy Hypermedia API</title> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <style> body { padding-bottom: 70px; } footer { padding-top: 50px; clear:both; } </style> </head> <body> <nav class="navbar navbar-default"> <div class="container"> <a class="navbar-brand" href="/">Foxy hAPI Example</a> <ul class="nav navbar-nav"> <li><a href="/?action=">Home</a></li> <li><a target="_blank" href="https://api<?php print ($fc->getUseSandbox() ? '-sandbox' : ''); ?>.foxycart.com/hal-browser/browser.html">HAL Browser</a></li> <?php if (isset($_SESSION['store_name'])) { ?> <li class="divider"></li> <li class="navbar-text">STORE: <?php print $_SESSION['store_name']; ?></li> <?php } if ($fc->getClientId() != '') { ?> <li><a href="/?action=logout">Logout</a></li> <?php } ?> </ul> <ul class="nav navbar-nav navbar-right"> <li><p class="navbar-text"><?php print ($fc->getUseSandbox() ? '<span class="text-success">SANDBOX</span>' : '<span class="text-danger">PRODUCTION</span>'); ?></p></li> </ul> </div> </nav> <div class="container"> <?php // BEGIN HERE if ($action == '') { ?> <h1>Welcome to the Foxy Hypermedia API example!</h1> <p> If you haven't already, please check out the <a href="https://api-sandbox.foxycart.com/docs">Foxy hAPI documentation</a> to better understand the purpose of this library. </p> <?php if (isset($_SESSION['store_name'])) { ?> <p>The following are examples of interacting with the Hypermedia API using the FoxyClient PHP library to perform CRUD operations on store elements. This is just a subset of what is possible with the API and is provided to give a practical overview of how it can function.</p> <h3>Store: <?php print $_SESSION['store_name']; ?></h3> <h4>Subscriptions</h4> <ul> <li><a href="/?action=<API key>">View all subscriptions as CSV</a></li> </ul> <h4>Transactions</h4> <ul> <li><a href="/?action=view_transactions">View all transactions</a></li> </ul> <h4>Coupons</h4> <ul> <li><a href="/?action=view_coupons">View all coupons</a></li> <li><a href="/?action=add_coupon_form">Add a new coupon</a></li> </ul> <h4>Categories</h4> <ul> <li><a href="/?action=<API key>">View all item categories</a></li> <li><a href="/?action=<API key>">Add a new item category</a></li> </ul> <?php } else { ?> <h3>Getting started</h3> <p>The Foxy Hypermedia API uses OAuth 2.0 to authenticate access, so to make use of this example set up, you first need to create an OAuth Integration client. There are two ways you can go about this:</p> <h4>Quick start</h4> <p>If you want to jump in and play with the API rather than stepping through creating a client, user and store manually, you can quickly set up an integration for an existing FoxyCart store. Simply log in to your <a href="https://admin.foxycart.com" target="_blank">FoxyCart store administration</a>, navigate to the "Integrations" page and click the "Get Token" button. After you specify a name for your integration, you'll be presented with the <code>client_id</code>, <code>client_secret</code> and <code>refresh_token</code> you'll need to access that store using the API. To connect that newly created client into this example code, use the "Authenticate client" option in the below "OAuth Interactions".</p> <h4>Manual steps</h4> <p>You can also run through each step manually - creating a client through the API, and then manually creating a user and store as well. Follow the steps below for doing that.</p> <p>Alternatively, you can also just complete step 1 below to create an OAuth Integration client, and then use the "OAuth Authorization Code Grant" to connect this new client to your existing FoxyCart user or store.</p> <ol> <li><a href="/?action=<API key>">Register your application</a> by creating an OAuth client</li> <li><a href="/?action=<API key>">Check if a Foxy user exists</a></li> <li><a href="/?action=create_user_form">Create a Foxy user</a></li> <li><a href="/?action=<API key>">Check if a Foxy store exists</a></li> <li><a href="/?action=create_store_form">Create a Foxy store</a></li> </ol> <h3>OAuth Interactions</h3> <ul> <li><a href="/?action=<API key>>Authenticate client</a><br/>If you have a <code>client_id</code>, <code>client_secret</code>, and OAuth <code>refresh_token</code> and want to connect using those credentials</li> <li><a href="/?action=<API key>">OAuth Client Credentials grant</a><br/>If you want to use the <code>client_id</code> and <code>client_secret</code> to get the <code>client_full_access</code> scoped refresh token for modifying your client</li> <li><a href="/?action=<API key>>OAuth Authorization Code grant</a><br/>If you have a <code>client_id</code> and <code>client_secret</code> and you want to get access to your store or user</li> </ul> <?php } } include 'includes/coupons.php'; include 'includes/item_categories.php'; include 'includes/transactions.php'; include 'includes/subscriptions.php'; if ($action == 'register_client') { ?> <h2>Register Client</h2> <h3>Code Steps:</h3> <ol> <li>Clear FoxyClient credentials <code>$fc->clearCredentials();</code>.</li> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:create_client</code> link.</li> <li>Check for errors.</li> <li>Post data to create a client resource <code>$fc->post($create_client_uri,$data);</code>.</li> <li>Check for errors.</li> <li>Configure FoxyClient with the new OAuth token from the response.</li> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:client</code> link (authenticated with a <code>client_full_access</code> scope).</li> <li>Check for errors.</li> <li>Get the client <code>$fc->get($client_uri);</code> and save the <code>client_id</code> and <code>client_secret</code>.</li> <li>Check for errors.</li> </ol> <?php $errors = array(); $fc->clearCredentials(); $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $create_client_uri = $fc->getLink('fx:create_client'); if ($create_client_uri == '') { $errors[] = 'Unable to obtain fx:create_client href'; } $required_fields = array( 'redirect_uri', 'project_name', 'company_name', 'contact_name', 'contact_email', 'contact_phone' ); foreach($required_fields as $required_field) { if ($_POST[$required_field] == '') { $errors[] = $required_field . ' can not be blank'; } } $data = array( 'redirect_uri' => $_POST['redirect_uri'], 'project_name' => $_POST['project_name'], 'project_description' => $_POST['project_description'], 'company_name' => $_POST['company_name'], 'company_url' => $_POST['company_url'], 'company_logo' => $_POST['company_logo'], 'contact_name' => $_POST['contact_name'], 'contact_email' => $_POST['contact_email'], 'contact_phone' => $_POST['contact_phone'], ); if (!count($errors)) { $result = $fc->post($create_client_uri,$data); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { ?> <h3 class="alert alert-success" role="alert"><?php print $result['message']; ?></h3> <pre><?php print_r($result['token']); ?></pre> <?php $_SESSION['access_token'] = $result['token']['access_token']; $_SESSION['refresh_token'] = $result['token']['refresh_token']; $_SESSION['<API key>'] = time() + $result['token']['expires_in']; $fc->setAccessToken($_SESSION['access_token']); $fc->setRefreshToken($_SESSION['refresh_token']); $fc-><API key>($_SESSION['<API key>']); $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $client_uri = $fc->getLink('fx:client'); if ($client_uri == '') { $errors[] = 'Unable to obtain fx:client href'; } if (!count($errors)) { $result = $fc->get($client_uri); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { $_SESSION['client_id'] = $result['client_id']; $_SESSION['client_secret'] = $result['client_secret']; $fc->setClientId($_SESSION['client_id']); $fc->setClientSecret($_SESSION['client_secret']); ?> <h3 class="alert alert-success" role="alert">Client Registered</h3> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php } } } } if (count($errors)) { $action = '<API key>'; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } } if ($action == '<API key>') { $redirect_uri = 'http' . (($_SERVER['SERVER_PORT'] == 443) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; $redirect_uri .= "?action=<API key>; if (isset($_POST['redirect_uri'])) { $redirect_uri = htmlspecialchars($_POST['redirect_uri']); } ?> <h2><a href="https://tools.ietf.org/html/rfc6749#section-2">Register</a> your OAuth Client</h2> <form role="form" action="/?action=register_client" method="post" class="form-horizontal"> <input type="hidden" name="act" value="create_client"> <div class="form-group"> <label for="project_name" class="col-sm-2 control-label">Project Name<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="project_name" name="project_name" maxlength="200" value="<?php echo isset($_POST['project_name']) ? htmlspecialchars($_POST['project_name']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="project_description" class="col-sm-2 control-label">Project Description</label> <div class="col-sm-3"> <input type="text" class="form-control" id="project_description" name="project_description" maxlength="200" value="<?php echo isset($_POST['project_description']) ? htmlspecialchars($_POST['project_description']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="company_name" class="col-sm-2 control-label">Company Name<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="company_name" name="company_name" maxlength="200" value="<?php echo isset($_POST['company_name']) ? htmlspecialchars($_POST['company_name']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="company_url" class="col-sm-2 control-label">Company URL</label> <div class="col-sm-3"> <input type="text" class="form-control" id="company_url" name="company_url" maxlength="200" value="<?php echo isset($_POST['company_url']) ? htmlspecialchars($_POST['company_url']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="company_logo" class="col-sm-2 control-label">Company Logo</label> <div class="col-sm-3"> <input type="text" class="form-control" id="company_logo" name="company_logo" maxlength="200" value="<?php echo isset($_POST['company_logo']) ? htmlspecialchars($_POST['company_logo']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="contact_name" class="col-sm-2 control-label">Contact Name<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="contact_name" name="contact_name" maxlength="200" value="<?php echo isset($_POST['contact_name']) ? htmlspecialchars($_POST['contact_name']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="contact_email" class="col-sm-2 control-label">Contact Email<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="email" class="form-control" id="contact_email" name="contact_email" maxlength="200" value="<?php echo isset($_POST['contact_email']) ? htmlspecialchars($_POST['contact_email']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="contact_phone" class="col-sm-2 control-label">Contact Phone<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="contact_phone" name="contact_phone" maxlength="200" value="<?php echo isset($_POST['contact_phone']) ? htmlspecialchars($_POST['contact_phone']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="redirect_uri" class="col-sm-2 control-label">Redirect URI<span class="text-danger">*</span></label> <div class="col-sm-5"> <input type="text" class="form-control" id="redirect_uri" name="redirect_uri" maxlength="200" value="<?php echo $redirect_uri; ?>"> <small class="muted">Put your application's OAuth Code Grant endpoint here.</small> </div> </div> <div class="form-group"> <label for="<API key>" class="col-sm-2 control-label">Javascript Origin URI</label> <div class="col-sm-5"> <input type="text" class="form-control" id="<API key>" name="<API key>" maxlength="200" value="<?php echo isset($_POST['<API key>']) ? htmlspecialchars($_POST['<API key>']) : ""; ?>"> <small class="muted">This is used by public OAuth clients (like a mobile browser only app where you can't secure the credentials).</small> </div> </div> <input type="hidden" name="csrf_token" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <button type="submit" class="btn btn-primary">Create Client</button> </form> <?php } if ($action == 'authenticate_client') { ?> <h2>Authenticate Client</h2> <h3>Code Steps:</h3> <ol> <li>Update FoxyClient credentials <code>$fc->updateFromConfig($data);</code>.</li> <li>Get the homepage <code>$fc->get();</code>.</li> <li>Check for errors.</li> </ol> <?php $errors = array(); $required_fields = array( 'client_id', 'client_secret' ); foreach($required_fields as $required_field) { if ($_POST[$required_field] == '') { $errors[] = $required_field . ' can not be blank'; } } $data = array( 'access_token' => $_POST['access_token'], 'refresh_token' => $_POST['refresh_token'], '<API key>' => $_POST['<API key>'], 'client_id' => $_POST['client_id'], 'client_secret' => $_POST['client_secret'], ); if (!count($errors)) { $fc->updateFromConfig($data); $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { $_SESSION['client_id'] = $data['client_id']; $_SESSION['client_secret'] = $data['client_secret']; $_SESSION['access_token'] = $data['access_token']; $_SESSION['refresh_token'] = $data['refresh_token']; $_SESSION['<API key>'] = $data['<API key>']; ?> <h3 class="alert alert-success" role="alert">Client Authenticated</h3> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php print '<br /><a href="/?action=<API key>">Check if User Exists</a>'; print '<br /><a href="/?action=create_user_form">Create User</a> <span class="muted">(client_full_access scope only)</span>'; print '<br /><a href="/?action=<API key>">Check if Store Exists</a>'; print '<br /><a href="/?action=create_store_form">Create Store</a> <span class="muted">(user_full_access scope only)</span>'; } } if (count($errors)) { $action = '<API key>; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } } if ($action == '<API key>) { ?> <h2>Authenticate your OAuth Client</h2> <form role="form" action="/?action=authenticate_client" method="post" class="form-horizontal"> <div class="form-group"> <label for="client_id" class="col-sm-2 control-label">Client ID<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="client_id" name="client_id" maxlength="200" value="<?php echo isset($_POST['client_id']) ? htmlspecialchars($_POST['client_id']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="client_secret" class="col-sm-2 control-label">Client Secret<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="client_secret" name="client_secret" maxlength="200" value="<?php echo isset($_POST['client_secret']) ? htmlspecialchars($_POST['client_secret']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="access_token" class="col-sm-2 control-label">Access Token</label> <div class="col-sm-3"> <input type="text" class="form-control" id="access_token" name="access_token" maxlength="200" value="<?php echo isset($_POST['access_token']) ? htmlspecialchars($_POST['access_token']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="access_token" class="col-sm-2 control-label">Refresh Token</label> <div class="col-sm-3"> <input type="text" class="form-control" id="access_token" name="refresh_token" maxlength="200" value="<?php echo isset($_POST['refresh_token']) ? htmlspecialchars($_POST['refresh_token']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="<API key>" class="col-sm-2 control-label">Token Expires</label> <div class="col-sm-3"> <input type="text" class="form-control" id="<API key>" name="<API key>" maxlength="200" value="<?php echo isset($_POST['<API key>']) ? htmlspecialchars($_POST['<API key>']) : ""; ?>"> </div> </div> <input type="hidden" name="csrf_token" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <button type="submit" class="btn btn-primary">Authenticate Client</button> </form> <?php } if ($action == '<API key>) { ?> <h2>Authorize Your Application</h2> <form role="form" action="<?php print $fc->get<API key>(); ?>" method="GET" class="form-horizontal"> <input type="hidden" name="state" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <input type="hidden" name="response_type" value="code" /> <input type="hidden" name="client_id" value="<?php print $fc->getClientId(); ?>" /> <div class="form-group"> <label for="client_id" class="col-sm-2 control-label">Scope<span class="text-danger">*</span></label> <div class="col-sm-3"> <select name="scope" class="form-control"> <option value="store_full_access">store_full_access</option> <option value="user_full_access">user_full_access</option> </select> </div> </div> <input type="hidden" name="csrf_token" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <button type="submit" class="btn btn-primary">Authorize Application</button> </form> <?php } if ($action == '<API key>) { ?> <h2>OAuth Authorization Code grant</h2> <h3>Code Steps:</h3> <ol> <li>Request an access_token using the Authorization Code <code>$fc->getAccess<API key>($code);</code>.</li> <li>Check for errors.</li> <li>Update locally stored <code>access_token</code> and <code>refresh_token</code>.</li> </ol> <?php $errors = array(); if (!array_key_exists('code', $_GET)) { $errors[] = 'Missing code from Authorization endpoint'; } if (!count($errors)) { $result = $fc->getAccess<API key>($_GET['code']); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { $_SESSION['access_token'] = $result['access_token']; $_SESSION['<API key>'] = time() + $result['expires_in']; $_SESSION['refresh_token'] = $result['refresh_token']; ?> <h3 class="alert alert-success" role="alert">Access Token Obtained</h3> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php } } if (count($errors)) { $action = ''; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } } if ($action == '<API key>') { ?> <h2>OAuth Client Credentials grant</h2> <h3>Code Steps:</h3> <ol> <li>Request an access_token via Client Credentials grant <code>$fc->getAccess<API key>();</code>.</li> <li>Check for errors.</li> <li>Update locally stored <code>access_token</code> and <code>refresh_token</code>.</li> </ol> <?php $errors = array(); $result = $fc->getAccess<API key>(); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { $_SESSION['access_token'] = $result['access_token']; $_SESSION['<API key>'] = time() + $result['expires_in']; ?> <h3 class="alert alert-success" role="alert">Access Token Obtained</h3> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php } if (count($errors)) { $action = ''; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } } if ($action == 'check_user_exists') { ?> <h2>Check User Exists</h2> <h3>Code Steps:</h3> <ol> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:reporting</code> link.</li> <li>Check for errors.</li> <li>Go to the reporting homepage <code>$fc->get($reporting_uri);</code> so we can get the <code>fx:<API key></code> link.</li> <li>Check for errors.</li> <li>Check if the email exists as a user <code>$fc->get($email_exists_uri, $data);</code>.</li> <li>Check for errors.</li> </ol> <?php $errors = array(); $required_fields = array( 'email' ); foreach($required_fields as $required_field) { if ($_POST[$required_field] == '') { $errors[] = $required_field . ' can not be blank'; } } $data = array( 'email' => $_POST['email'], ); if (!count($errors)) { $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $reporting_uri = $fc->getLink('fx:reporting'); if ($reporting_uri == '') { $errors[] = 'Unable to obtain fx:reporting href'; } if (!count($errors)) { $result = $fc->get($reporting_uri); $errors = array_merge($errors,$fc->getErrors($result)); $email_exists_uri = $fc->getLink('fx:<API key>'); if ($email_exists_uri == '') { $errors[] = 'Unable to obtain fx:<API key> href'; } if (!count($errors)) { $result = $fc->get($email_exists_uri, $data); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { ?> <h3 class="alert alert-success" role="alert">User Exists</h3> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php print '<br /><a href="/?action=create_user_form">Create User</a>'; } } } } if (count($errors)) { $action = '<API key>'; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } } if ($action == '<API key>') { ?> <h2>Check User Exists</h2> <form role="form" action="/?action=check_user_exists" method="post" class="form-horizontal"> <div class="form-group"> <label for="email" class="col-sm-2 control-label">User Email Address<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="email" class="form-control" id="email" name="email" maxlength="200" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ""; ?>"> </div> </div> <input type="hidden" name="csrf_token" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <button type="submit" class="btn btn-primary">Check User</button> </form> <?php } if ($action == 'create_user') { ?> <h2>Create User</h2> <h3>Code Steps:</h3> <ol> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:create_user</code> link (authenticated with a <code>client_full_access</code> scope).</li> <li>Check for errors.</li> <li>Post data to create a user resource <code>$fc->post($create_user_uri, $data);</code>.</li> <li>Check for errors.</li> <li>Configure FoxyClient with the new OAuth token from the response.</li> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:user</code> link (authenticated with a <code>user_full_accesss</code> scope).</li> <li>Check for errors.</li> <li>Get the user <code>$fc->get($user_uri);</code>.</li> <li>Check for errors.</li> </ol> <?php $errors = array(); $required_fields = array( 'first_name', 'last_name', 'email', 'phone' ); foreach($required_fields as $required_field) { if ($_POST[$required_field] == '') { $errors[] = $required_field . ' can not be blank'; } } $data = array( 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'email' => $_POST['email'], 'phone' => $_POST['phone'], 'is_programmer' => isset($_POST['is_programmer']), '<API key>' => isset($_POST['<API key>']), 'is_designer' => isset($_POST['is_designer']), 'is_merchant' => isset($_POST['is_merchant']), ); if (!count($errors)) { $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $create_user_uri = $fc->getLink('fx:create_user'); if ($create_user_uri == '') { $errors[] = 'Unable to obtain fx:create_user href'; } if (!count($errors)) { $result = $fc->post($create_user_uri, $data); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { ?> <h3 class="alert alert-success" role="alert"><?php print $result['message']; ?></h3> <pre><?php print_r($result['token']); ?></pre> <?php $_SESSION['access_token'] = $result['token']['access_token']; $_SESSION['refresh_token'] = $result['token']['refresh_token']; $_SESSION['<API key>'] = time() + $result['token']['expires_in']; $fc->setAccessToken($_SESSION['access_token']); $fc->setRefreshToken($_SESSION['refresh_token']); $fc-><API key>($_SESSION['<API key>']); $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $user_uri = $fc->getLink('fx:user'); if ($user_uri == '') { $errors[] = 'Unable to obtain fx:user href'; } if (!count($errors)) { $result = $fc->get($user_uri); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { ?> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php print '<br /><a href="/?action=check_store_exists">Check if Store Exists</a>'; } } } } } if (count($errors)) { $action = 'create_user_form'; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } } if ($action == 'create_user_form') { ?> <h2>Create User</h2> <form role="form" action="/?action=create_user" method="post" class="form-horizontal"> <div class="form-group"> <label for="first_name" class="col-sm-2 control-label">First Name<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="first_name" name="first_name" maxlength="200" value="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="last_name" class="col-sm-2 control-label">Last Name<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="last_name" name="last_name" maxlength="200" value="<?php echo isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="email" class="col-sm-2 control-label">Email<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="email" name="email" maxlength="200" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="phone" class="col-sm-2 control-label">Phone<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="phone" name="phone" maxlength="200" value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="is_programmer" class="col-sm-2 control-label">is_programmer</label> <div class="col-sm-3"> <?php $checked = (isset($_POST['is_programmer']) ? ' checked' : ''); ?> <input type="checkbox"<?php print $checked; ?> class="form-control" id="is_programmer" name="is_programmer"> </div> </div> <div class="form-group"> <label for="<API key>" class="col-sm-2 control-label"><API key></label> <div class="col-sm-3"> <?php $checked = (isset($_POST['<API key>']) ? ' checked' : ''); ?> <input type="checkbox"<?php print $checked; ?> class="form-control" id="<API key>" name="<API key>"> </div> </div> <div class="form-group"> <label for="is_designer" class="col-sm-2 control-label">is_designer</label> <div class="col-sm-3"> <?php $checked = (isset($_POST['is_designer']) ? ' checked' : ''); ?> <input type="checkbox"<?php print $checked; ?> class="form-control" id="is_designer" name="is_designer"> </div> </div> <div class="form-group"> <label for="is_merchant" class="col-sm-2 control-label">is_merchant</label> <div class="col-sm-3"> <?php $checked = (isset($_POST['is_merchant']) ? ' checked' : ''); ?> <input type="checkbox"<?php print $checked; ?> class="form-control" id="is_merchant" name="is_merchant"> </div> </div> <input type="hidden" name="csrf_token" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <button type="submit" class="btn btn-primary">Create User</button> </form> <?php } if ($action == 'check_store_exists') { ?> <h3>Check Store Exists</h3> <h3>Code Steps:</h3> <ol> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:reporting</code> link.</li> <li>Check for errors.</li> <li>Go to the reporting homepage <code>$fc->get($reporting_uri);</code> so we can get the <code>fx:<API key></code> link.</li> <li>Check for errors.</li> <li>Check if the store_domain exists as a store <code>$fc->get($store_exists_uri, $data);</code>.</li> <li>Check for errors.</li> </ol> <?php $errors = array(); $required_fields = array( 'store_domain' ); foreach($required_fields as $required_field) { if ($_POST[$required_field] == '') { $errors[] = $required_field . ' can not be blank'; } } $data = array( 'store_domain' => $_POST['store_domain'], ); if (!count($errors)) { $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $reporting_uri = $fc->getLink('fx:reporting'); if ($reporting_uri == '') { $errors[] = 'Unable to obtain fx:reporting href'; } if (!count($errors)) { $result = $fc->get($reporting_uri); $errors = array_merge($errors,$fc->getErrors($result)); $store_exists_uri = $fc->getLink('fx:<API key>'); if ($store_exists_uri == '') { $errors[] = 'Unable to obtain fx:<API key> href'; } if (!count($errors)) { $result = $fc->get($store_exists_uri, $data); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { ?> <h3 class="alert alert-success" role="alert">Store Exists</h3> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php } } } } if (count($errors)) { $action = '<API key>'; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } print '<br /><a href="/?action=create_store_form">Create Store</a>'; } if ($action == '<API key>') { ?> <h2>Check Store Exists</h2> <form role="form" action="/?action=check_store_exists" method="post" class="form-horizontal"> <div class="form-group"> <label for="project_name" class="col-sm-2 control-label">Foxy Store Domain<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_domain" name="store_domain" maxlength="200" value="<?php echo isset($_POST['store_domain']) ? htmlspecialchars($_POST['store_domain']) : ""; ?>"> </div> </div> <input type="hidden" name="csrf_token" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <button type="submit" class="btn btn-primary">Check Store</button> </form> <?php } if ($action == 'create_store') { ?> <h2>Create Store</h2> <h3>Code Steps:</h3> <ol> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:stores</code> link (authenticated with a <code>user_full_access</code> scope).</li> <li>Check for errors.</li> <li>Post data to create a store resource <code>$fc->post($stores_uri, $data);</code>.</li> <li>Check for errors.</li> <li>Configure FoxyClient with the new OAuth token from the response.</li> <li>Get the homepage <code>$fc->get();</code> so we can get the <code>fx:store</code> link (authenticated with a <code>store_full_accesss</code> scope).</li> <li>Check for errors.</li> <li>Get the store <code>$fc->get($store_uri);</code>.</li> <li>Check for errors.</li> </ol> <?php $errors = array(); $required_fields = array( 'store_name', 'store_domain', 'store_url', 'store_email', 'store_postal_code', 'store_country', 'store_state' ); foreach($required_fields as $required_field) { if ($_POST[$required_field] == '') { $errors[] = $required_field . ' can not be blank'; } } $data = array( 'store_name' => $_POST['store_name'], 'store_domain' => $_POST['store_domain'], 'store_url' => $_POST['store_url'], 'store_email' => $_POST['store_email'], 'store_postal_code' => $_POST['store_postal_code'], 'store_country' => $_POST['store_country'], 'store_state' => $_POST['store_state'] ); if (!count($errors)) { $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $stores_uri = $fc->getLink('fx:stores'); if ($stores_uri == '') { $errors[] = 'Unable to obtain fx:stores href'; } if (!count($errors)) { $result = $fc->post($stores_uri, $data); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { ?> <h3 class="alert alert-success" role="alert"><?php print $result['message']; ?></h3> <pre><?php print_r($result['token']); ?></pre> <?php $_SESSION['access_token'] = $result['token']['access_token']; $_SESSION['refresh_token'] = $result['token']['refresh_token']; $_SESSION['<API key>'] = time() + $result['token']['expires_in']; $fc->setAccessToken($_SESSION['access_token']); $fc->setRefreshToken($_SESSION['refresh_token']); $fc-><API key>($_SESSION['<API key>']); $result = $fc->get(); $errors = array_merge($errors,$fc->getErrors($result)); $store_uri = $fc->getLink('fx:store'); if ($store_uri == '') { $errors[] = 'Unable to obtain fx:store href'; } if (!count($errors)) { $result = $fc->get($store_uri); $errors = array_merge($errors,$fc->getErrors($result)); if (!count($errors)) { ?> <h3>Result:</h3> <pre><?php print_r($result); ?></pre> <?php print '<br /><a href="/?action=">Home</a>'; } } } } } if (count($errors)) { $action = 'create_store_form'; print '<div class="alert alert-danger" role="alert">'; print '<h2>Error:</h2>'; foreach($errors as $error) { print $error . '<br />'; } print '</div>'; } } if ($action == 'create_store_form') { ?> <h2>Create Store</h2> <form role="form" action="/?action=create_store" method="post" class="form-horizontal"> <div class="form-group"> <label for="store_name" class="col-sm-2 control-label">Store Name<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_name" name="store_name" maxlength="200" value="<?php echo isset($_POST['store_name']) ? htmlspecialchars($_POST['store_name']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="store_domain" class="col-sm-2 control-label">Store Domain<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_domain" name="store_domain" maxlength="200" value="<?php echo isset($_POST['store_domain']) ? htmlspecialchars($_POST['store_domain']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="store_url" class="col-sm-2 control-label">Store URL<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_url" name="store_url" maxlength="200" value="<?php echo isset($_POST['store_url']) ? htmlspecialchars($_POST['store_url']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="store_email" class="col-sm-2 control-label">Store Email<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_email" name="store_email" maxlength="200" value="<?php echo isset($_POST['store_email']) ? htmlspecialchars($_POST['store_email']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="store_postal_code" class="col-sm-2 control-label">Store Postal Code<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_postal_code" name="store_postal_code" maxlength="200" value="<?php echo isset($_POST['store_postal_code']) ? htmlspecialchars($_POST['store_postal_code']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="store_country" class="col-sm-2 control-label">Store Country (ISO 3166-1 alpha-2)<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_country" name="store_country" maxlength="200" value="<?php echo isset($_POST['store_country']) ? htmlspecialchars($_POST['store_country']) : ""; ?>"> </div> </div> <div class="form-group"> <label for="store_state" class="col-sm-2 control-label">Store State (ISO 3166-2)<span class="text-danger">*</span></label> <div class="col-sm-3"> <input type="text" class="form-control" id="store_state" name="store_state" maxlength="200" value="<?php echo isset($_POST['store_state']) ? htmlspecialchars($_POST['store_state']) : ""; ?>"> </div> </div> <input type="hidden" name="csrf_token" value="<?php print htmlspecialchars($token, ENT_QUOTES | ENT_HTML5, 'UTF-8'); ?>" /> <button type="submit" class="btn btn-primary">Create Store</button> </form> <?php } if ($action == 'logout') { session_destroy(); $fc->clearCredentials(); print '<h2>You are Logged out</h2>'; print '<br /><a href="/?action=">Home</a>'; } // NOTE: This example uses the session, but you could also be using a database or some other persistance layer. if (isset($_SESSION['access_token']) && $fc->getAccessToken() != $_SESSION['access_token']) { // This can happen after a token refresh. if ($fc->getAccessToken() != '') { $_SESSION['access_token'] = $fc->getAccessToken(); } } if (isset($_SESSION['<API key>']) && $fc-><API key>() != $_SESSION['<API key>']) { // This can happen after a token refresh. if ($fc-><API key>() != '') { $_SESSION['<API key>'] = $fc-><API key>(); } } if ($action != 'logout' && $fc->getClientId() != '') { print '<footer class="text-muted">Authenticated: '; print '<ul>'; print '<li>client_id: ' . $fc->getClientId() . '</li>'; print '<li>client_secret (select text to view): <span style="color:white">' . $fc->getClientSecret() . '</span></li>'; print '<li>access_token: ' . $fc->getAccessToken() . '</li>'; print '<li>refresh_token (select text to view): <span style="color:white">' . $fc->getRefreshToken() . '</span></li>'; if ($fc-><API key>() != '') { print '<li><API key>: ' . $fc-><API key>() . '</li>'; print '<li>now: ' . time() . '</li>'; print '<li>next token refresh: ' . ($fc-><API key>() - time()) . '</li>'; } print '</ul>'; print '</footer>'; } ?> </div> </body> </html>
/* jshint node: true */ const should = require('should'); const fs = require('fs'); const path = require('path'); const Vinyl = require('vinyl'); const getStylesheetList = require('../index'); function getFile(filePath) { return new Vinyl({ path: path.resolve(filePath), cwd: './test/', base: path.dirname(filePath), contents: Buffer.from(String(fs.readFileSync(filePath))) }); } describe('list-stylesheets', () => { it('Should list stylesheets from an html file', done => { const options = { applyLinkTags: true, removeLinkTags: true }; function compare(fixturePath, expectedHTML) { const file = getFile(fixturePath); const data = getStylesheetList(file.contents.toString('utf8'), options); data.hrefs[0].should.be.equal('file.css'); data.html.should.be.equal(String(fs.readFileSync(expectedHTML))); done(); } compare(path.join('test', 'fixtures', 'in.html'), path.join('test', 'expected', 'out.html'), options, done); }); it('Should ignore hbs code blocks', done => { const options = { applyLinkTags: true, removeLinkTags: true }; function compare(fixturePath, expectedHTML) { const file = getFile(fixturePath); const data = getStylesheetList(file.contents.toString('utf8'), options); data.hrefs[0].should.be.equal('codeblocks.css'); data.html.should.be.equal(String(fs.readFileSync(expectedHTML))); done(); } compare(path.join('test', 'fixtures', 'codeblocks.html'), path.join('test', 'expected', 'codeblocks.html'), options, done); }); it('Should ignore ejs code blocks', done => { const options = { applyLinkTags: true, removeLinkTags: true }; function compare(fixturePath, expectedHTML) { const file = getFile(fixturePath); const data = getStylesheetList(file.contents.toString('utf8'), options); data.hrefs[0].should.be.equal('ejs.css'); data.html.should.be.equal(String(fs.readFileSync(expectedHTML))); done(); } compare(path.join('test', 'fixtures', 'ejs.html'), path.join('test', 'expected', 'ejs.html'), options, done); }); it('Should ignore user defined code blocks', done => { const options = { codeBlocks: { craze: { start: '<<', end: '>>' } } }; function compare(fixturePath, expectedHTML) { const file = getFile(fixturePath); const data = getStylesheetList(file.contents.toString('utf8'), options); data.html.should.be.equal(String(fs.readFileSync(expectedHTML))); done(); } compare(path.join('test', 'fixtures', 'codeblocks-external.html'), path.join('test', 'expected', 'codeblocks-external.html'), options, done); }); });
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module GenderPredictor class Application < Rails::Application
function Tour(settings) { var tour = settings.tour; var exit_callback = settings.exit_callback; var position = settings.position var options = ('<div class="tour">\ <a class="glyphicon glyphicon-remove pull-right text-muted btn-exit-tour"></a>\ <div class="tour-options">\ <div class="tour-controls">\ <a class="btn btn-default btn-xs btn-prev-tour">\ <span class="glyphicon glyphicon-backward"></span>\ </a>\ <a class="btn btn-default btn-xs btn-pause-tour">\ <span class="glyphicon glyphicon-pause"></span>\ </a>\ <a class="btn btn-default btn-primary btn-xs btn-play-tour">\ <span class="glyphicon glyphicon-play"></span>\ </a>\ <a class="btn btn-default btn-xs btn-next-tour">\ <span class="glyphicon glyphicon-forward"></span>\ </a>\ </div>\ <div class="tour-controls2">\ <a class="btn btn-primary btn-start-tour">Start Tour</a>\ <a class="btn btn-danger btn-exit-tour hide">Exit Tour</a>\ </div>\ </div>\ </div>'); $('body').append('<div class="modal-backdrop tour-modal-backdrop in"></div>') $('body').prepend(options) var loop; var i = 0; var bVisibles = []; $('.btn-start-tour').click(function() { clearInterval(loop); $(this).text('Restart Tour') $('.btn-pause-tour').addClass('btn-primary'); $('.btn-play-tour').removeClass('btn-primary'); i = 0; showTourTip(tour[i]) tourLoop(); }) $('.btn-exit-tour').click(function() { clearInterval(loop); $('.tour, .tour-modal-backdrop, .popover').remove(); for (var i in bVisibles) { bVisibles[i].addClass('hide'); } exit_callback(); }) $('.btn-pause-tour').click(function() { clearInterval(loop); $(this).removeClass('btn-primary'); $('.btn-play-tour').addClass('btn-primary') }) $('.btn-play-tour').click(function() { // if first play, show tip right away. #poetry if (i == 0) { showTourTip(tour[i]); i++; } tourLoop(); $(this).toggleClass('btn-primary') $('.btn-pause-tour').toggleClass('btn-primary') }); $('.btn-prev-tour').click(function() { clearInterval(loop); if (i > 1) { i = i-1; // i is already i+1 :) } else if (i == 1) { i = 0; } showTourTip(tour[i]) //if (i == 0) i = i-1; $('.btn-pause-tour').removeClass('btn-primary'); $('.btn-play-tour').addClass('btn-primary'); }) $('.btn-next-tour').click(function() { clearInterval(loop); // i is already i+1, for case 0 i++; showTourTip(tour[i]); $('.btn-pause-tour').removeClass('btn-primary'); $('.btn-play-tour').addClass('btn-primary') }) function tourLoop() { loop = setInterval(function(){ i++; showTourTip(tour[i]) // stop interval after tour. if (i >= tour.length) { clearInterval(loop); $('.btn-exit-tour').removeClass('hide'); $('.btn-pause-tour').removeClass('btn-primary'); $('.btn-play-tour').addClass('btn-primary') } }, 3000) } function showTourTip(exhibit) { // remove all popovers $('.popover').remove(); // aww, shucks, no more exhibits to visit? Then, leave the museum; if (!exhibit) return; // if something needs to happen before the exhibit, make it happen if (exhibit.event) exhibit.event(); // select the nth element if supplied var n = exhibit.n; var ele = n ? $(exhibit.element).eq(n) : $(exhibit.element); var text = exhibit.text; var hover = exhibit.bVisible; var placement = exhibit.placement ? exhibit.placement : 'bottom'; if (hover) { ele.removeClass('hide'); bVisibles.push(ele); } ele.tooltip('destroy'); // destroy the regular tooltips ele.popover('destroy') if (text) { ele.popover({content: '<div class="tour-text">'+text+'</div>', placement: placement, trigger:'manual', html: true, container: 'body'}); ele.popover('show'); } $('.popover').css('z-index', 9999); } }
# ifndef <API key> # define <API key> # include <chaos/preprocessor/cat.h> # include <chaos/preprocessor/config.h> # include <chaos/preprocessor/punctuation/paren.h> # /* CHAOS_PP_SPECIAL */ # define CHAOS_PP_SPECIAL(digit) <API key>(CHAOS_IP_SPECIAL_, digit) # if CHAOS_PP_VARIADICS # define CHAOS_IP_SPECIAL_00(...) # define CHAOS_IP_SPECIAL_0(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_1(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_2(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_3(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_4(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_5(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_6(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_7(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_8(...) __VA_ARGS__ # define CHAOS_IP_SPECIAL_9(...) __VA_ARGS__ # else # define CHAOS_IP_SPECIAL_00(x) # define CHAOS_IP_SPECIAL_0(x) x # define CHAOS_IP_SPECIAL_1(x) x # define CHAOS_IP_SPECIAL_2(x) x # define CHAOS_IP_SPECIAL_3(x) x # define CHAOS_IP_SPECIAL_4(x) x # define CHAOS_IP_SPECIAL_5(x) x # define CHAOS_IP_SPECIAL_6(x) x # define CHAOS_IP_SPECIAL_7(x) x # define CHAOS_IP_SPECIAL_8(x) x # define CHAOS_IP_SPECIAL_9(x) x # endif # /* <API key> */ # define <API key>(x) <API key> x(00) # define <API key>(digit) CHAOS_PP_SPECIAL(digit)(CHAOS_PP_RPAREN() <API key>) # define <API key>(digit) CHAOS_PP_SPECIAL(digit)(CHAOS_PP_RPAREN() <API key>) # endif
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" type="text/css" href="css/base.css"> </head> <body style="overflow:auto;"> <div class="content_main baseinfo"> <div class="content_title"> <span class="main_title"></span> </div> <div class="print_info"> <a class="print"> <img src="images/print.png" width="23" height="21"> <span class="print_btn"></span> </a> </div> <div class="content_table"> <table> <tbody> <tr> <td width="20%"></td> <td width="30%">XX</td> <td width="20%"></td> <td width="30%">101010101101010</td> </tr> <tr> <td></td> <td></td> <td></td> <td>771910101010</td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td>10101010201010</td> </tr> <tr> <td></td> <td>2001-01-01</td> <td></td> <td>2001-01-01</td> </tr> <tr> <td></td> <td>2001-01-01</td> <td></td> <td>2015-03-01</td> </tr> <tr> <td></td> <td></td> <td></td> <td>101010101010120</td> </tr> <tr> <td></td> <td>XXXX</td> <td></td> <td>XXXX</td> </tr> <tr> <td></td> <td>30</td> <td></td> <td>0</td> </tr> <tr> <td></td> <td class="tip"></td> <td></td> <td>011111</td> </tr> <tr> <td></td> <td colspan="3"></td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="17%"></td> <td width="16%"></td> <td width="16%"></td> <td width="16%"></td> <td width="16%"></td> </tr> <tr> <td ></td> <td ></td> <td ></td> <td >3201258xxxxxxxxxxx</td> <td >8356xxxx</td> <td >1380516xxxx</td> </tr> <tr> <td ></td> <td ></td> <td ></td> <td >3201258xxxxxxxxxxx</td> <td >8356xxxx</td> <td >1380516xxxx</td> </tr> <tr> <td ></td> <td ></td> <td ></td> <td >3201258xxxxxxxxxxx</td> <td >8356xxxx</td> <td >1380516xxxx</td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="33%"></td> <td width="51%"></td> </tr> <tr> <td ></td> <td ></td> <td >3201258xxxxxxxxxxx</td> </tr> <tr> <td ></td> <td ></td> <td >3201258xxxxxxxxxxx</td> </tr> <tr> <td ></td> <td ></td> <td >3201258xxxxxxxxxxx</td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="33%"></td> <td width="16%"></td> <td width="16%"></td> <td width="16%"></td> </tr> <tr> <td ></td> <td ></td> <td >15</td> <td >2015-10-10</td> <td ></td> </tr> <tr> <td ></td> <td ></td> <td >15</td> <td >2015-10-10</td> <td ></td> </tr> <tr> <td ></td> <td ></td> <td >15</td> <td >2015-10-10</td> <td ></td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="33%"></td> <td width="25%"></td> <td width="25%"></td> </tr> <tr> <td ></td> <td >2005-01-22</td> <td >2015-02-01</td> <td ></td> </tr> <tr> <td ></td> <td >2005-01-22</td> <td >2015-02-01</td> <td ></td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="33%"></td> <td width="16%"></td> <td width="16%"></td> <td width="17%"></td> </tr> <tr> <td ></td> <td ></td> <td >25</td> <td >2015-10-10</td> <td></td> </tr> <tr> <td ></td> <td ></td> <td >100</td> <td >2015-10-10</td> <td></td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="17%"></td> <td width="16%"></td> <td width="16%"></td> <td width="17%"></td> <td width="17%"></td> </tr> <tr> <td >1100143130</td> <td ></td> <td >15</td> <td >2700086</td> <td>2700000</td> <td></td> </tr> <tr> <td >1100151320</td> <td ></td> <td >98</td> <td >3600078</td> <td>3600075</td> <td></td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="33%">645xx4</td> <td width="16%"></td> <td width="33%">xx</td> </tr> <tr> <td ></td> <td >160</td> <td ></td> <td >1</td> </tr> <tr> <td ></td> <td ></td> <td ></td> <td >713xxx548</td> </tr> <tr> <td ></td> <td ></td> <td ></td> <td >XXXX</td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="100%">()/</td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table"> <table> <tbody> <tr> <td width="16%"></td> <td width="42%"></td> <td width="42%"></td> </tr> <tr> <td ></td> <td ></td> <td >3201xxxx</td> </tr> <tr> <td ></td> <td ></td> <td >3285xxxx</td> </tr> </tbody> </table> </div> <div class="content_title"> <span class="main_title"></span> </div> <div class="content_table" style="margin-bottom:20px;"> <table> <tbody> <tr> <td>A</td> </tr> </tbody> </table> </div> <!-- <div class="content_bottom"> <a class="print"><img src="images/print.png" width="55" height="26"></a> <a class="back"><img src="images/back.png" width="55"height="26" ></a> </div> </div> <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> function setIframe_child(){ window.top.setIframeHeight($("body").height()); //iframe } //Iframe height window.onload=function(){ setIframe_child(); } </script> </body> </html>
.timeline { position: relative; padding: 20px 0 20px; list-style: none; } .timeline::before { content: " "; position: absolute; top: 0; bottom: 0; left: 50%; width: 3px; margin-left: -1.5px; background-color: #eee; } .timeline > li { position: relative; margin-bottom: 20px; } .timeline > li::before, .timeline > li::after { content: " "; display: table; } .timeline > li::after { clear: both; } .timeline > li::before, .timeline > li::after { content: " "; display: table; } .timeline > li::after { clear: both; } .timeline > li > .timeline-panel { float: left; position: relative; width: 46%; padding: 20px; border: 1px solid #d4d4d4; border-radius: 2px; -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175); box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175); } .timeline > li > .timeline-panel::before { content: " "; display: inline-block; position: absolute; top: 26px; right: -15px; border-top: 15px solid transparent; border-right: 0 solid #ccc; border-bottom: 15px solid transparent; border-left: 15px solid #ccc; } .timeline > li > .timeline-panel::after { content: " "; display: inline-block; position: absolute; top: 27px; right: -14px; border-top: 14px solid transparent; border-right: 0 solid #fff; border-bottom: 14px solid transparent; border-left: 14px solid #fff; } .timeline > li > .timeline-badge { z-index: 100; position: absolute; top: 16px; left: 50%; width: 50px; height: 50px; margin-left: -25px; border-radius: 50% 50% 50% 50%; text-align: center; font-size: 1.4em; line-height: 50px; color: #fff; background-color: #999; } .timeline > li.timeline-inverted > .timeline-panel { float: right; } .timeline > li.timeline-inverted > .timeline-panel::before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } .timeline > li.timeline-inverted > .timeline-panel::after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } .timeline-badge.primary { background-color: #2e6da4 !important; } .timeline-badge.success { background-color: #3f903f !important; } .timeline-badge.warning { background-color: #f0ad4e !important; } .timeline-badge.danger { background-color: #d9534f !important; } .timeline-badge.info { background-color: #5bc0de !important; } .timeline-title { margin-top: 0; color: inherit; } .timeline-body > p, .timeline-body > ul { margin-bottom: 0; } .timeline-body > p + p { margin-top: 5px; } @media(max-width: 767px) { ul.timeline::before { left: 40px; } ul.timeline > li > .timeline-panel { width: calc(100% - 90px); width: -moz-calc(100% - 90px); width: -webkit-calc(100% - 90px); } ul.timeline > li > .timeline-badge { top: 16px; left: 15px; margin-left: 0; } ul.timeline > li > .timeline-panel { float: right; } ul.timeline > li > .timeline-panel::before { right: auto; left: -15px; border-right-width: 15px; border-left-width: 0; } ul.timeline > li > .timeline-panel:::after { right: auto; left: -14px; border-right-width: 14px; border-left-width: 0; } }
<?php namespace Nova\Controllers; use Nova\Object; use Nova\Models\DirectoryType; class <API key> extends ControllerBase { public function indexAction() { $data = new Object(); $data->directory_types = DirectoryType::find()->toArray(); return $this->jsonResponse($data); } public function findAction($id) { $id = $this->filter->sanitize($id, array("int")); $directoryType = DirectoryType::findFirst($id); if (!$directoryType) { return $this->forward("error/notFound"); } $data = new Object(); $data->directory_type = $directoryType; return $this->jsonResponse($data); } }
![GitHub Actions](https://github.com/pegjs/pegjs/workflows/Github%20Actions/badge.svg) [![Codecov](https: [![CodeFactor](https: [![license](https: PEG.js is a simple parser generator for JavaScript that produces fast parsers with excellent error reporting. You can use it to process complex data or computer languages and build transformers, interpreters, compilers and other tools easily. > PEG.js is still very much work in progress. There are no compatibility guarantees until version 1.0 public packages | package | version | dependency status | | | [pegjs][P001] | [![release][P002]][P003] [![dev][P004]][P005] | [![dependencies][P006]][P007] | local packages | package | dependency status | | | [~/][L013] | [![dependencies][L014]][L015] | | [~/test][L001] | [![dependencies][L002]][L003] | | [~/tools/benchmark][L004] | [![dependencies][L005]][L006] | | [~/tools/bundler][L007] | [![dependencies][L008]][L009] | | [~/tools/impact][L010] | [![dependencies][L011]][L012] | | [~/tools/publish-dev][L016] | [![dependencies][L017]][L018] | <!-- packages/pegjs --> [P001]: https://github.com/pegjs/pegjs/tree/master/packages/pegjs [P002]: https://img.shields.io/npm/v/pegjs.svg [P003]: https: [P004]: https://img.shields.io/npm/v/pegjs/dev.svg [P005]: https://github.com/pegjs/pegjs [P006]: https://img.shields.io/david/pegjs/pegjs.svg?path=packages/pegjs [P007]: https://david-dm.org/pegjs/pegjs?path=packages/pegjs [L013]: https://github.com/pegjs/pegjs/tree/master/ [L014]: https://img.shields.io/david/pegjs/pegjs.svg [L015]: https://david-dm.org/pegjs/pegjs <!-- test --> [L001]: https://github.com/pegjs/pegjs/tree/master/test [L002]: https://img.shields.io/david/pegjs/pegjs.svg?path=test [L003]: https://david-dm.org/pegjs/pegjs?path=test <!-- tools/benchmark --> [L004]: https://github.com/pegjs/pegjs/tree/master/tools/benchmark [L005]: https://img.shields.io/david/pegjs/pegjs.svg?path=tools/benchmark [L006]: https://david-dm.org/pegjs/pegjs?path=tools/benchmark <!-- tools/bundler --> [L007]: https://github.com/pegjs/pegjs/tree/master/tools/bundler [L008]: https://img.shields.io/david/pegjs/pegjs.svg?path=tools/bundler [L009]: https://david-dm.org/pegjs/pegjs?path=tools/bundler <!-- tools/impact --> [L010]: https://github.com/pegjs/pegjs/tree/master/tools/impact [L011]: https://img.shields.io/david/pegjs/pegjs.svg?path=tools/impact [L012]: https://david-dm.org/pegjs/pegjs?path=tools/impact <!-- tools/publish-dev --> [L016]: https://github.com/pegjs/pegjs/tree/master/tools/publish-dev [L017]: https://img.shields.io/david/pegjs/pegjs.svg?path=tools/publish-dev [L018]: https://david-dm.org/pegjs/pegjs?path=tools/publish-dev
# -*- coding: utf-8 -*- import re import sympy from colorama import Fore from plugin import alias, plugin @alias('calc', 'evaluate') @plugin('calculate') def calculate(jarvis, s): """ Jarvis will get your calculations done! -- Example: calculate 3 + 5 """ tempt = s.replace(" ", "") if len(tempt) > 1: calc(jarvis, tempt, formatter=lambda x: x) else: jarvis.say("Error: Not in correct format", Fore.RED) @plugin('solve') def solve(jarvis, s): """ Prints where expression equals zero -- Example: solve x**2 + 5*x + 3 solve x + 3 = 5 """ x = sympy.Symbol('x') def _format(solutions): if solutions == 0: return "No solution!" ret = '' for count, point in enumerate(solutions): if x not in point: return "Please use 'x' in expression." x_value = point[x] ret += "{}. x: {}\n".format(count, x_value) return ret def _calc(expr): return sympy.solve(expr, x, dict=True) s = remove_equals(jarvis, s) calc(jarvis, s, calculator=_calc, formatter=_format, do_evalf=False) @plugin('equations') def equations(jarvis, term): """ Solves linear equations system Use variables: a, b, c, ..., x, y,z Example: ~> Hi, what can I do for you? equations 1. Equation: x**2 + 2y - z = 6 2. Equation: (x-1)(y-1) = 0 3. Equation: y**2 - x -10 = y**2 -y 4. Equation: [{x: -9, y: 1, z: 77}, {x: 1, y: 11, z: 17}] """ a, b, c, d, e, f, g, h, i, j, k, l, m = sympy.symbols( 'a,b,c,d,e,f,g,h,i,j,k,l,m') n, o, p, q, r, s, t, u, v, w, x, y, z = sympy.symbols( 'n,o,p,q,r,s,t,u,v,w,x,y,z') equations = [] count = 1 user_input = jarvis.input('{}. Equation: '.format(count)) while user_input != '': count += 1 user_input = format_expression(user_input) user_input = remove_equals(jarvis, user_input) equations.append(user_input) user_input = jarvis.input('{}. Equation: '.format(count)) calc( jarvis, term, calculator=lambda expr: sympy.solve( expr, equations, dict=True)) @plugin('factor') def factor(jarvis, s): """ Jarvis will factories -- Example: factor x**2-y**2 """ tempt = s.replace(" ", "") if len(tempt) > 1: calc(jarvis, tempt, formatter=sympy.factor) else: jarvis.say("Error: Not in correct format", Fore.RED) @alias("curve plot") @plugin('plot') def plot(jarvis, s): """ Plot graph -- Example: plot x**2 plot y=x(x+1)(x-1) """ def _plot(expr): sympy.plotting.plot(expr) return "" if len(s) == 0: jarvis.say("Missing parameter: function (e.g. call 'plot x**2')") return s = remove_equals(jarvis, s) try: calc(jarvis, s, calculator=solve_y, formatter=_plot, do_evalf=False) except ValueError: jarvis.say("Cannot plot...", Fore.RED) except OverflowError: jarvis.say("Cannot plot - values probably too big...") @plugin('limit') def limit(jarvis, s): """ Prints limit to +/- infinity or to number +-. Use 'x' as variable. -- Examples: limit 1/x limit @1 1/(1-x) limit @1 @2 1/((1-x)(2-x)) """ def try_limit(term, x, to, directory=''): try: return sympy.Limit(term, x, to, directory).doit() except sympy.SympifyError: return 'Error' except NotImplementedError: return "Sorry, cannot solve..." if s == '': jarvis.say("Usage: limit TERM") return s_split = s.split() limit_to = [] term = "" for token in s_split: if token[0] == '@': if token[1:].isnumeric(): limit_to.append(int(token[1:])) else: jarvis.say("Error: {} Not a number".format( token[1:]), Fore.RED) else: term += token term = remove_equals(jarvis, term) term = format_expression(term) try: term = solve_y(term) except (sympy.SympifyError, TypeError): jarvis.say('Error, not a valid term') return x = sympy.Symbol('x') # infinity: jarvis.say("lim -> ∞\t= {}".format(try_limit(term, x, +sympy.S.Infinity)), Fore.BLUE) jarvis.say("lim -> -∞\t= {}".format(try_limit(term, x, -sympy.S.Infinity)), Fore.BLUE) for limit in limit_to: limit_plus = try_limit(term, x, limit, directory="+") limit_minus = try_limit(term, x, limit, directory="-") jarvis.say("lim -> {}(+)\t= {}".format(limit, limit_plus), Fore.BLUE) jarvis.say("lim -> {}(-)\t= {}".format(limit, limit_minus), Fore.BLUE) def remove_equals(jarvis, equation): """ User should be able to input equations like x + y = 1. SymPy only accepts equations like: x + y - 1 = 0. => This method Finds '=' and move everything beyond to left side """ split = equation.split('=') if len(split) == 1: return equation if len(split) != 2: jarvis.say("Warning! More than one = detected!", Fore.RED) return equation return "{} - ({})".format(split[0], split[1]) def format_expression(s): s = str.lower(s) s = s.replace("power", "**") s = s.replace("plus", "+") s = s.replace("minus", "-") s = s.replace("dividedby", "/") s = s.replace("by", "/") s = s.replace("^", "**") # Insert missing * commonly omitted # 2x -> 2*x p = re.compile('(\\d+)([abcxyz])') s = p.sub(r'\1*\2', s) # x(... -> x*(... p = re.compile('([abcxyz])\\(') s = p.sub(r'\1*(', s) # (x-1)(x+1) -> (x-1)*(x+1) # x(... -> x*(... s = s.replace(")(", ")*(") return s def solve_y(s): if 'y' in s: y = sympy.Symbol('y') try: results = sympy.solve(s, y) except NotImplementedError: return 'unknown' if len(results) == 0: return '0' else: return results[0] else: return solve_y("({}) -y".format(s)) def calc(jarvis, s, calculator=sympy.sympify, formatter=None, do_evalf=True): s = format_expression(s) try: result = calculator(s) except sympy.SympifyError: jarvis.say("Error: Something is wrong with your expression", Fore.RED) return except NotImplementedError: jarvis.say("Sorry, cannot solve", Fore.RED) return if formatter is not None: result = formatter(result) if do_evalf: result = result.evalf() jarvis.say(str(result), Fore.BLUE) @alias("curve sketch") @plugin('curvesketch') def curvesketch(jarvis, s): """ Prints useful information about a graph of a function. * Limit * Intersection x/y axis * Derivative and Integral * Minima / Maxima / Turning point -- Example: curve sketch y=x**2+10x-5 curve sketch y=sqrt((x+1)(x-1)) curve sketch y=1/3x**3-2x**2+3x """ if len(s) == 0: jarvis.say( "Missing parameter: function (e.g. call 'curve sketch y=x**2+10x-5')") return def section(jarvis, headline): jarvis.say("\n{:#^50}".format(" {} ".format(headline)), Fore.MAGENTA) term = remove_equals(jarvis, s) term = format_expression(term) term = solve_y(term) def get_y(x_val, func=term): x = sympy.Symbol('x') return func.evalf(subs={x: x_val}) section(jarvis, s) section(jarvis, "Graph") jarvis.eval('plot {}'.format(s)) section(jarvis, "Limit") jarvis.eval('limit {}'.format(term)) section(jarvis, "Intersection x-axis") jarvis.eval('solve {}'.format(term)) section(jarvis, "Intersection y-axis") jarvis.say(str(get_y(0).round(9)), Fore.BLUE) section(jarvis, "Factor") jarvis.eval('factor {}'.format(term)) section(jarvis, "Derivative") x = sympy.Symbol('x') derivative_1 = sympy.Derivative(term, x).doit() derivative_2 = sympy.Derivative(derivative_1, x).doit() derivative_3 = sympy.Derivative(derivative_2, x).doit() jarvis.say("1. Derivative: {}".format(derivative_1), Fore.BLUE) jarvis.say("2. Derivative: {}".format(derivative_2), Fore.BLUE) jarvis.say("3. Derivative: {}".format(derivative_3), Fore.BLUE) section(jarvis, "Integral") jarvis.say("F(x) = {} + t".format(sympy.Integral(term, x).doit()), Fore.BLUE) section(jarvis, "Maxima / Minima") try: critical_points = sympy.solve(derivative_1) except NotImplementedError: jarvis.say("Sorry, cannot solve...", Fore.RED) critical_points = [] for x in critical_points: y = str(get_y(x).round(9)) try: isminmax = float(get_y(x, func=derivative_2)) except ValueError: isminmax = None except TypeError: # probably complex number isminmax = None if isminmax is None: minmax = "unknown" elif isminmax > 0: minmax = "Minima" elif isminmax < 0: minmax = "Maxima" else: minmax = "/" jarvis.say("({}/{}) : {}".format(x, y, minmax), Fore.BLUE) section(jarvis, "Turning Point") try: critical_points = sympy.solve(derivative_2) except NotImplementedError: jarvis.say("Sorry, cannot solve...", Fore.RED) critical_points = [] for x in critical_points: y = get_y(x) try: is_turning_point = float(get_y(x, func=derivative_3)) except ValueError: is_turning_point = -1 if is_turning_point != 0: jarvis.say("({}/{})".format(x, y.round(9)), Fore.BLUE) section(jarvis, "")
<?php namespace lukaszmakuch\ValueMatcher\String; use lukaszmakuch\ValueMatcher\Exception\<API key>; use <API key>; abstract class <API key> extends <API key> { /** * @var StrictStringMatcher */ protected $m; public function <API key>() { $this-><API key>(<API key>::class); $this->m->matches(123); } }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin extends <API key> { protected $_user_name,$_password = null; public function __construct(){ parent::__construct(); if(!isset($_SESSION['auth_admin_login'])){ header("Location: /Admin_Login/login"); } $this->load->model('public_model', 'p'); $this->load->model('wish_model','wish'); $this->load->model('upload_file_model','upload_file'); $this->load->model('quotation_model','quotation'); } public function index(){ //$this->load->view('admin_index'); $this->quotation_list(); } public function quotation_list(){ $this->load->model('upload_file_model','upload_file'); $this->p->db->select('*'); $this->p->db->from('quotation'); $this->p->db->where(array('is_deleted'=>0)); $this->p->db->limit(0,20); $res = $this->p->db->get()->result_array(); foreach($res as &$r){ if(!intval($r['reply_price'])){ $r['reply_price'] = ''; } $r['addtime'] = intval($r['addtime']) ? date('Y-m-d',$r['addtime']) : '-'; if($r['enquiry_attach']){ $r['<API key>'] = array(); $enquiry_attach_ids = explode(',',$r['enquiry_attach']); foreach($enquiry_attach_ids as $key => $enquiry_id){ $upload_file_info = $this->upload_file-><API key>($enquiry_id); $r['<API key>'][$key]['enquiry_origin_name'] = $upload_file_info['origin_name'] ? $upload_file_info['origin_name'] : ''; $r['<API key>'][$key]['enquiry_file_path'] = $upload_file_info['file_path'] ? $upload_file_info['file_path'] : ''; } } if($r['reply_attach']){ $upload_file_info = $this->upload_file-><API key>($r['reply_attach']); $r['reply_origin_name'] = $upload_file_info['origin_name'] ? $upload_file_info['origin_name'] : ''; $r['reply_file_path'] = $upload_file_info['file_path'] ? $upload_file_info['file_path'] : ''; } unset($r); } $this->load->view('<API key>.html',array('list'=>$res)); } public function view_test(){ $this->load->view('<API key>.html'); } public function quotation_edit(){ $qid = $this->input->get('qid',true); $this->load->model('upload_file_model','upload_file'); if(IS_POST){ $this->load->library('file'); $price = trim($this->input->post('reply_price','trim')); $reply_content = trim($this->input->post('reply_content','trim')); $data = array( 'reply_price'=>$price, 'reply_content'=>$reply_content, 'is_reply'=>1, ); if(isset($_FILES['reply_attach']) && $_FILES['reply_attach']['name']){ $reply_attach = $_FILES['reply_attach']; $upload_ojb = $this->file->upload_file($reply_attach); if($upload_ojb->err){ do_frame($upload_ojb->err); } $upload_file_id = $this->upload_file-><API key>($upload_ojb); $data['reply_attach'] = $upload_file_id; } $this->p->db->where(array('quotation_id'=>$qid)); $result = $this->p->db->update('quotation',$data); if($result){ do_frame('!','/admin/quotation_list'); } } $this->p->db->select('*'); $this->p->db->from('quotation'); $this->p->db->where(array('quotation_id'=>$qid)); $res = $this->p->db->get()->row_array(); if($res['enquiry_attach']){ $upload_file_info = $this->upload_file-><API key>($res['enquiry_attach']); $res['enquiry_origin_name'] = $upload_file_info['origin_name'] ? $upload_file_info['origin_name'] : ''; $res['enquiry_file_path'] = $upload_file_info['file_path'] ? $upload_file_info['file_path'] : ''; } if($res['reply_attach']){ $upload_file_info = $this->upload_file-><API key>($res['reply_attach']); $res['reply_origin_name'] = $upload_file_info['origin_name'] ? $upload_file_info['origin_name'] : ''; $res['reply_file_path'] = $upload_file_info['file_path'] ? $upload_file_info['file_path'] : ''; } $this->load->view('<API key>.html',array('quo'=>$res)); } public function quotation_del(){ $this->load->model('quotation_model','quotation'); $qid = $this->input->get('qid',true); if(!$qid){ echo ''; header('Location: /admin/quotation_list'); } $res = $this->quotation->del($qid); header('Location: /admin/quotation_list'); } public function wish_list(){ $this->load->model('wish_model','wish'); $this->load->model('upload_file_model','upload_file'); $wish = $this->wish-><API key>(); $this->load->view('admin_wish_list.html',array('wish'=>$wish)); } public function wish_comment_list(){ $wish_id = $this->input->get('wish_id',true); if(!$wish_id){ echo "<script>alert('');</script>"; header('Location: /admin/wish_list'); } $this->load->model('wish_model','wish'); $comment = $this->wish-><API key>($wish_id); //$this->load->view('admin_common_header.html'); $this->load->view('<API key>.html',array('comment'=>$comment,'wish_id'=>$wish_id)); } public function <API key>(){ if(IS_POST){ $res = $this->wish-><API key>(); $wish_id = $this->input->post('wish_id',true); if($res){ echo "<script>alert('');</script>"; header('Location: /admin/wish_comment_list?wish_id='.$wish_id); } } } public function wish_list_del(){ $wish_id = $this->input->get('wish_id',true); if(!$wish_id){ echo "<script>alert('');</script>"; header('Location: /admin/wish_list'); } $res = $this->wish-><API key>(); if($res){ echo "<script>alert('');</script>"; header('Location: /admin/wish_list'); } } public function wish_comment_del(){ $comment_id = $this->input->get('comment_id',true); $wish_id = $this->input->get('wish_id',true); if(!$comment_id || !$wish_id){ echo "<script>alert('');</script>"; header('Location: /admin/wish_comment_list?wish_id='.$wish_id); } $this->load->model('wish_model','wish'); $res = $this->wish-><API key>(); if($res){ echo "<script>alert('');</script>"; header('Location: /admin/wish_comment_list?wish_id='.$wish_id); } } public function logout(){ $_SESSION = array(); session_destroy(); $this->index(); } }
/*Problem 9. Print a Sequence Write a program that prints the first 10 members of the sequence: 2, -3, 4, -5, 6, -7, ... */ using System; class PrintSequence { static void Main() { for (int i = 0; i < 10; i++) { if (i % 2 == 0) { Console.Write("{0}, ", i + 2); } else { Console.Write("{0}, ", -(i + 2)); } } Console.WriteLine(); } }
package net.popsim.src.util.io; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; public class HeadedPrintStream extends PrintStream { /** * The header of the day. Formatted as * <br><tt>[ DD:MM:YYYY ]</tt> */ private static final String HEADER_DAY = "[ %1$td-%1$tm-%1$tY ]"; /** * The header of the time. Formatted as * <br><tt>[HH:MM:SS:mmm]</tt> */ private static final String HEADER_TIME = "[%1$tH:%1$tM:%1$tS:%1$tL] "; /** * Header format for new threads. */ private static final String HEADER_THREAD_NEW = "%s (%d)"; /** * The number of milliseconds in a day. This is used to calculate when a day passes and the day header should be * reprinted. */ private static final long MILLIS_PER_DAY = 1000 * 60 * 60 * 24; /** * A flag used when checking if a header must be written. This allows us to "inject" a header before a line is written. */ private boolean mNeedsHeader; /** * The name of the last Thread to print to this stream. When a different Thread prints, a nifty header is printed. */ private String mLastThread; /** * Days since the epoch. Used to keep track of when day headers should be printed. */ private long mDay; /** * @see PrintStream#PrintStream(OutputStream, boolean) */ public HeadedPrintStream(OutputStream out, boolean autoFlush) { super(out, autoFlush); mNeedsHeader = true; } // Overridden to make sure we catch newlines public void write(int b) { super.write(b); mNeedsHeader = b == '\n'; } @Override public void write(byte[] buf, int off, int len) { // Inject header if (mNeedsHeader) { buf = Arrays.copyOfRange(buf, off, len); off = 0; writeHeader(); } // Write the original stuff super.write(buf, off, len); // Buffers with new lines typically end with them... mNeedsHeader = len > 0 && buf[off + len - 1] == '\n'; } /** * Prints the header. */ private void writeHeader() { // Make sure we don't just keep printing headers mNeedsHeader = false; // Get the current time long t = System.currentTimeMillis(); // Calculate the day long day = t / MILLIS_PER_DAY; // Check if we need to print a day header if (mDay != day) { mDay = day; printf(HEADER_DAY, t); println(); // Printing the newline character will prompt another header to be written: make sure this does not happen mNeedsHeader = false; } // Print the time header printf(HEADER_TIME, t); // Get the current thread and its ID Thread current = Thread.currentThread(); String name = current.getName(); long id = current.getId(); // If the map doesn't contain the id or the names do not match if (!name.equals(mLastThread)) { // Update the last thread mLastThread = name; // Print that a new thread has printed printf(HEADER_THREAD_NEW, name, id); println(); // Rewrite the header so we can have a normal line writeHeader(); } else print(" "); } }
<?php declare(strict_types=1); namespace <API key>\Fixture\C; class FixtureC873 { public function __construct(FixtureC872 $dependency) { } }
<ul class="heroes"> <li *ngFor=" <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul>
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>blowbox: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="customdoxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">blowbox </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>blowbox</b></li><li class="navelem"><a class="el" href="<API key>.html">D3D11InputLayout</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">blowbox::D3D11InputLayout Member List</div> </div> </div><!--header <div class="contents"> <p>This is the complete list of members for <a class="el" href="<API key>.html">blowbox::D3D11InputLayout</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">D3D11InputLayout</a>(<API key> *input_layout_desc, UINT stride, D3D11Shader *shader)</td><td class="entry"><a class="el" href="<API key>.html">blowbox::D3D11InputLayout</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="<API key>.html#<API key>">Set</a>(ID3D11DeviceContext *context)</td><td class="entry"><a class="el" href="<API key>.html">blowbox::D3D11InputLayout</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">~D3D11InputLayout</a>()</td><td class="entry"><a class="el" href="<API key>.html">blowbox::D3D11InputLayout</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Mar 31 2015 19:14:55 for blowbox by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
<?php declare(strict_types=1); namespace Ramsey\Uuid\Test\Nonstandard; use DateTimeImmutable; use Mockery; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\<API key>; use Ramsey\Uuid\Converter\<API key>; use Ramsey\Uuid\Exception\DateTimeException; use Ramsey\Uuid\Exception\<API key>; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Nonstandard\UuidV6; use Ramsey\Uuid\Rfc4122\FieldsInterface; use Ramsey\Uuid\Test\TestCase; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Time; use Ramsey\Uuid\Uuid; class UuidV6Test extends TestCase { /** * @dataProvider provideTestVersions */ public function <API key>(int $version): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getVersion' => $version, ]); $numberConverter = Mockery::mock(<API key>::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(<API key>::class); $this->expectException(<API key>::class); $this-><API key>( 'Fields used to create a UuidV6 must represent a ' . 'version 6 (ordered-time) UUID' ); new UuidV6($fields, $numberConverter, $codec, $timeConverter); } /** * @phpcsSuppress <API key>.TypeHints.ReturnTypeHint.<API key> */ public function provideTestVersions(): array { return [ ['version' => 0], ['version' => 1], ['version' => 2], ['version' => 3], ['version' => 4], ['version' => 5], ['version' => 7], ['version' => 8], ['version' => 9], ]; } /** * @param non-empty-string $uuid * * @dataProvider <API key> */ public function <API key>(string $uuid, string $expected): void { /** @var UuidV6 $object */ $object = Uuid::fromString($uuid); $date = $object->getDateTime(); $this->assertInstanceOf(DateTimeImmutable::class, $date); $this->assertSame($expected, $date->format('U.u')); } /** * @phpcsSuppress <API key>.TypeHints.ReturnTypeHint.<API key> */ public function <API key>(): array { return [ [ 'uuid' => '<API key>', 'expected' => '1.677722', ], [ 'uuid' => '<API key>', 'expected' => '0.104858', ], [ 'uuid' => '<API key>', 'expected' => '0.105267', ], [ 'uuid' => '<API key>', 'expected' => '-1.000000', ], ]; } /** * @param non-empty-string $uuidv6 * @param non-empty-string $uuidv1 * * @dataProvider <API key> */ public function testToUuidV1(string $uuidv6, string $uuidv1): void { /** @var UuidV6 $uuid6 */ $uuid6 = Uuid::fromString($uuidv6); $uuid1 = $uuid6->toUuidV1(); $this->assertSame($uuidv6, $uuid6->toString()); $this->assertSame($uuidv1, $uuid1->toString()); $this->assertSame( $uuid6->getDateTime()->format('U.u'), $uuid1->getDateTime()->format('U.u') ); } /** * @param non-empty-string $uuidv6 * @param non-empty-string $uuidv1 * * @dataProvider <API key> */ public function testFromUuidV1(string $uuidv6, string $uuidv1): void { /** @var LazyUuidFromString $uuid */ $uuid = Uuid::fromString($uuidv1); $uuid1 = $uuid->toUuidV1(); $uuid6 = UuidV6::fromUuidV1($uuid1); $this->assertSame($uuidv1, $uuid1->toString()); $this->assertSame($uuidv6, $uuid6->toString()); $this->assertSame( $uuid1->getDateTime()->format('U.u'), $uuid6->getDateTime()->format('U.u') ); } /** * @phpcsSuppress <API key>.TypeHints.ReturnTypeHint.<API key> */ public function <API key>(): array { return [ [ 'uuidv6' => '<API key>', 'uuidv1' => '<API key>', ], [ 'uuidv6' => '<API key>', 'uuidv1' => '<API key>', ], [ 'uuidv6' => '<API key>', 'uuidv1' => '<API key>', ], [ 'uuidv6' => '<API key>', 'uuidv1' => '<API key>', ], ]; } public function <API key>(): void { $fields = Mockery::mock(FieldsInterface::class, [ 'getVersion' => 6, 'getTimestamp' => new Hexadecimal('0'), ]); $numberConverter = Mockery::mock(<API key>::class); $codec = Mockery::mock(CodecInterface::class); $timeConverter = Mockery::mock(<API key>::class, [ 'convertTime' => new Time('0', '1234567'), ]); $uuid = new UuidV6($fields, $numberConverter, $codec, $timeConverter); $this->expectException(DateTimeException::class); $uuid->getDateTime(); } }
#include <stdio.h> #include <string.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/file.h> #include <errno.h> #include <signal.h> #define ECHOMAX (255) #define TIMEOUT (2) int SendEchoMessage(struct sockaddr_in *pServAddr); int ReceiveEchoMessage(struct sockaddr_in *pServAddr); int sock; void IOSignalHandler(int signo); int main(int argc, char *argv[]) { unsigned short servPort; struct sockaddr_in servAddr; struct sigaction sigAction; char *servIP; struct sockaddr_in servAddr2; int maxDescriptor; fd_set fdSet; struct timeval tout; if((argc < 2) || (argc > 3)) { fprintf(stderr, "Usage: %s <Server IP> [<Echo Port>]\n", argv[0]); exit(1); } servIP = argv[1]; if(argc == 3) { servPort = atoi(argv[2]); } else { servPort = 7; } sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if(sock < 0) { fprintf(stderr, "socket() failed\n"); exit(1); } memset(&servAddr2, 0, sizeof(servAddr2)); servAddr2.sin_family = AF_INET; servAddr2.sin_addr.s_addr = inet_addr(servIP); servAddr2.sin_port = htons(servPort); maxDescriptor = sock; memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(servPort); if(bind(sock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0) { fprintf(stderr, "bind() failed\n"); exit(1); } sigAction.sa_handler = IOSignalHandler; if(sigfillset(&sigAction.sa_mask) < 0) { fprintf(stderr, "sigfillset() failed\n"); exit(1); } sigAction.sa_flags = 0; if(sigaction(SIGIO, &sigAction, 0) < 0) { fprintf(stderr, "sigaction() failed\n"); exit(1); } if(fcntl(sock, F_SETOWN, getpid()) < 0) { fprintf(stderr, "Unable to set process owner to us\n"); exit(1); } if(fcntl(sock, F_SETFL, O_NONBLOCK | FASYNC) < 0) { fprintf(stderr, "Unable to put the sock into nonblocking/async mode\n"); exit(1); } for(;;) { FD_ZERO(&fdSet); FD_SET(STDIN_FILENO, &fdSet); FD_SET(sock, &fdSet); tout.tv_sec = TIMEOUT; tout.tv_usec = 0; if(select(maxDescriptor +1, &fdSet, NULL, NULL, &tout) == 0) { //printf(".\n"); continue; } if(FD_ISSET(STDIN_FILENO, &fdSet)) { if(SendEchoMessage(&servAddr2) < 0) { break; } } if(FD_ISSET(sock, &fdSet)) { if(ReceiveEchoMessage(&servAddr2) < 0) { break; } } } close(sock); exit(0); } void IOSignalHandler(int signo) { struct sockaddr_in clntAddr; unsigned int clntAddrLen; char msgBuffer[ECHOMAX]; int recvMsgLen; int sendMsgLen; do { clntAddrLen = sizeof(clntAddr); recvMsgLen = recvfrom(sock, msgBuffer, ECHOMAX, 0, (struct sockaddr *)&clntAddr, &clntAddrLen); if(recvMsgLen < 0) { if(errno != EWOULDBLOCK) { fprintf(stderr, "recvfrom() failed\n"); exit(1); } } else { printf("Handling client %s\n", inet_ntoa(clntAddr.sin_addr)); sendMsgLen = sendto(sock, msgBuffer, recvMsgLen, 0, (struct sockaddr *)&clntAddr, sizeof(clntAddr)); if(recvMsgLen != sendMsgLen) { fprintf(stderr, "sendto() sent a differrent number of bytes than expected\n"); exit(1); } } } while(recvMsgLen >= 0); } int SendEchoMessage(struct sockaddr_in *pServAddr) { char echoString[ECHOMAX + 1]; int echoStringLen; int sendMsgLen; if(fgets(echoString, ECHOMAX +1, stdin) == NULL) { return -1; } echoStringLen = strlen(echoString); if(echoStringLen < 1 ) { fprintf(stderr, "No input string.\n"); return -1; } sendMsgLen = sendto(sock, echoString, echoStringLen, 0, (struct sockaddr*)pServAddr, sizeof(*pServAddr)); if(echoStringLen != sendMsgLen) { fprintf(stderr, "sendto() sent a different number of bytes than expected\n"); return -1; } return 0; } int ReceiveEchoMessage(struct sockaddr_in *pServAddr) { struct sockaddr_in fromAddr; unsigned int fromAddrLen; char msgBuffer[ECHOMAX +1]; int recvMsgLen; fromAddrLen = sizeof(fromAddr); recvMsgLen = recvfrom(sock, msgBuffer, ECHOMAX, 0, (struct sockaddr *)&fromAddr, &fromAddrLen); if(recvMsgLen < 0) { fprintf(stderr, "recvfrom() failed\n"); return -1; } if(fromAddr.sin_addr.s_addr != pServAddr->sin_addr.s_addr) { fprintf(stderr, "Error: received a packet from unknown source.\n"); return -1; } msgBuffer[recvMsgLen] = '\0'; printf("Received: %s\n", msgBuffer); return 0; }
var myArray = ['Bob', 'Fred']; var myStr = myArray[0]; myArray['key1'] = 'Alice'; myArray[1] = 1; // Type '1' is not assignable to type 'string'.