code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# gautamramuvel.github.io My github page
gautamramuvel/gautamramuvel.github.io
README.md
Markdown
mit
41
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.admin.message; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.zimbra.common.soap.AdminConstants; import com.zimbra.soap.type.ZmBoolean; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name=AdminConstants.E_CHECK_HEALTH_RESPONSE) @XmlType(propOrder = {}) public class CheckHealthResponse { /** * @zm-api-field-description Flags whether healthy or not */ @XmlAttribute(name=AdminConstants.A_HEALTHY, required=true) private ZmBoolean healthy; public CheckHealthResponse() { } public CheckHealthResponse(boolean healthy) { this.healthy = ZmBoolean.fromBool(healthy); } public void setHealthy(boolean healthy) { this.healthy = ZmBoolean.fromBool(healthy); } public boolean isHealthy() { return ZmBoolean.toBool(healthy); } }
nico01f/z-pec
ZimbraSoap/src/java/com/zimbra/soap/admin/message/CheckHealthResponse.java
Java
mit
1,528
--- title: ako11 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: o11 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
pblack/kaldi-hugo-cms-template
site/content/pages2/ako11.md
Markdown
mit
339
/** * Party.java */ package Simulation;/* * Simulation.Party.java * * Version: * $Id$ * * Revisions: * $Log: Simulation.Party.java,v $ * Revision 1.3 2003/02/09 21:21:31 ??? * Added lots of comments * * Revision 1.2 2003/01/12 22:23:32 ??? * *** empty log message *** * * Revision 1.1 2003/01/12 19:09:12 ??? * Adding Simulation.Party, Lanes.Lanes, Simulation.Bowler, and desk.Alley. * */ /** * Container that holds bowlers * */ import java.util.*; public class Party implements CustomCollection{ /** Vector of bowlers in this party */ private ArrayList<Bowler> myBowlers; /** * Constructor for a Simulation.Party * * @param bowlers Vector of bowlers that are in this party */ public Party( ArrayList<Bowler> bowlers ) { myBowlers = new ArrayList<Bowler>(bowlers); } /** * Accessor for members in this party * * @return A vector of the bowlers in this party */ public ArrayList<Bowler> getMembers() { return myBowlers; } public int getSize() { return this.myBowlers.size(); } /** * Returns the iterator for this class * @return the iterator generated for this class */ @Override public CustomIterator getIterator() { return new PartyIterator(this); } }
Ziggypop/BowlingAlleyManagementSystem
src/Simulation/Party.java
Java
mit
1,275
import _ from '../lib/utils' import App from './app' let Cards = { Plains: 401994, Island: 401927, Swamp: 402059, Mountain: 401961, Forest: 401886 } export let BASICS = Object.keys(Cards) let COLORS_TO_LANDS = { 'W': 'Plains', 'U': 'Island', 'B': 'Swamp', 'R': 'Mountain', 'G': 'Forest', } for (let name in Cards) Cards[name] = {name, cmc: 0, code: 'BFZ', color: 'colorless', rarity: 'basic', type: 'Land', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&' + `multiverseid=${Cards[name]}` } let rawPack, clicked export let Zones = { pack: {}, main: {}, side: {}, junk: {} } function hash() { let {main, side} = Zones App.send('hash', { main, side }) } let events = { side() { let dst = Zones[App.state.side ? 'side' : 'main'] let srcName = App.state.side ? 'main' : 'side' let src = Zones[srcName] _.add(src, dst) Zones[srcName] = {} }, add(cardName) { let zone = Zones[App.state.side ? 'side' : 'main'] zone[cardName] || (zone[cardName] = 0) zone[cardName]++ App.update() }, click(zoneName, cardName, e) { if (zoneName === 'pack') return clickPack(cardName) let src = Zones[zoneName] let dst = Zones[e.shiftKey ? zoneName === 'junk' ? 'main' : 'junk' : zoneName === 'side' ? 'main' : 'side'] dst[cardName] || (dst[cardName] = 0) src[cardName]-- dst[cardName]++ if (!src[cardName]) delete src[cardName] App.update() }, copy(ref) { let node = ref.getDOMNode() node.value = filetypes.txt() node.select() hash() }, download() { let {filename, filetype} = App.state let data = filetypes[filetype]() _.download(data, filename + '.' + filetype) hash() }, start() { let {addBots, useTimer, timerLength} = App.state let options = {addBots, useTimer, timerLength} App.send('start', options) }, pack(cards) { rawPack = cards let pack = Zones.pack = {} for (let card of cards) { let {name} = card Cards[name] = card pack[name] = 1 } App.update() if (App.state.beep) document.getElementById('beep').play() }, create() { let {type, seats, title, isPrivate} = App.state seats = Number(seats) let options = { type, seats, title, isPrivate } if (/cube/.test(type)) options.cube = cube() else { let {sets} = App.state if (type === 'draft') sets = sets.slice(0, 3) options.sets = sets } App.send('create', options) }, pool(cards) { ['main', 'side', 'junk'].forEach(zoneName => Zones[zoneName] = {}) let zone = Zones[App.state.side ? 'side' : 'main'] for (let card of cards) { let {name} = card Cards[name] = card zone[name] || (zone[name] = 0) zone[name]++ } App.update() }, land(zoneName, cardName, e) { let n = Number(e.target.value) if (n) Zones[zoneName][cardName] = n else delete Zones[zoneName][cardName] App.update() }, deckSize(e) { let n = Number(e.target.value) if (n && n > 0) App.state.deckSize = n App.update() }, suggestLands() { // Algorithm: count the number of mana symbols appearing in the costs of // the cards in the pool, then assign lands roughly commensurately. let colors = ['W', 'U', 'B', 'R', 'G'] let colorRegex = /\{[^}]+\}/g let manaSymbols = {} colors.forEach(x => manaSymbols[x] = 0) // Count the number of mana symbols of each type. for (let card of Object.keys(Zones['main'])) { let quantity = Zones['main'][card] card = Cards[card] if (!card.manaCost) continue let cardManaSymbols = card.manaCost.match(colorRegex) for (let color of colors) for (let symbol of cardManaSymbols) // Test to see if '{U}' contains 'U'. This also handles things like // '{G/U}' triggering both 'G' and 'U'. if (symbol.indexOf(color) !== -1) manaSymbols[color] += quantity } _resetLands() // NB: We could set only the sideboard lands of the colors we are using to // 5, but this reveals information to the opponent on Cockatrice (and // possibly other clients) since it tells the opponent the sideboard size. colors.forEach(color => Zones['side'][COLORS_TO_LANDS[color]] = 5) colors = colors.filter(x => manaSymbols[x] > 0) colors.forEach(x => manaSymbols[x] = Math.max(3, manaSymbols[x])) colors.sort((a, b) => manaSymbols[b] - manaSymbols[a]) // Round-robin choose the lands to go into the deck. For example, if the // mana symbol counts are W: 2, U: 2, B: 1, cycle through the sequence // [Plains, Island, Swamp, Plains, Island] infinitely until the deck is // finished. // // This has a few nice effects: // // * Colors with greater mana symbol counts get more lands. // // * When in a typical two color deck adding 17 lands, the 9/8 split will // be in favor of the color with slightly more mana symbols of that // color. // // * Every color in the deck is represented, if it is possible to do so // in the remaining number of cards. // // * Because of the minimum mana symbol count for each represented color, // splashing cards doesn't add exactly one land of the given type // (although the land count may still be low for that color). // // * The problem of deciding how to round land counts is now easy to // solve. let manaSymbolsToAdd = colors.map(color => manaSymbols[color]) let colorsToAdd = [] for (let i = 0; true; i = (i + 1) % colors.length) { if (manaSymbolsToAdd.every(x => x === 0)) break if (manaSymbolsToAdd[i] === 0) continue colorsToAdd.push(colors[i]) manaSymbolsToAdd[i]-- } let mainDeckSize = Object.keys(Zones['main']) .map(x => Zones['main'][x]) .reduce((a, b) => a + b) let landsToAdd = App.state.deckSize - mainDeckSize let j = 0 for (let i = 0; i < landsToAdd; i++) { let color = colorsToAdd[j] let land = COLORS_TO_LANDS[color] if (!Zones['main'].hasOwnProperty(land)) Zones['main'][land] = 0 Zones['main'][land]++ j = (j + 1) % colorsToAdd.length } App.update() }, resetLands() { _resetLands() App.update() }, } function _resetLands() { Object.keys(COLORS_TO_LANDS).forEach((key) => { let land = COLORS_TO_LANDS[key] Zones['main'][land] = Zones['side'][land] = 0 }) } for (let event in events) App.on(event, events[event]) function codify(zone) { let arr = [] for (let name in zone) arr.push(` <card number="${zone[name]}" name="${name}"/>`) return arr.join('\n') } let filetypes = { cod() { return `\ <?xml version="1.0" encoding="UTF-8"?> <cockatrice_deck version="1"> <deckname>${App.state.filename}</deckname> <zone name="main"> ${codify(Zones.main)} </zone> <zone name="side"> ${codify(Zones.side)} </zone> </cockatrice_deck>` }, mwdeck() { let arr = [] ;['main', 'side'].forEach(zoneName => { let prefix = zoneName === 'side' ? 'SB: ' : '' let zone = Zones[zoneName] for (let name in zone) { let {code} = Cards[name] let count = zone[name] name = name.replace(' // ', '/') arr.push(`${prefix}${count} [${code}] ${name}`) } }) return arr.join('\n') }, json() { let {main, side} = Zones return JSON.stringify({ main, side }, null, 2) }, txt() { let arr = [] ;['main', 'side'].forEach(zoneName => { if (zoneName === 'side') arr.push('Sideboard') let zone = Zones[zoneName] for (let name in zone) { let count = zone[name] arr.push(count + ' ' + name) } }) return arr.join('\n') } } function cube() { let {list, cards, packs} = App.state cards = Number(cards) packs = Number(packs) list = list .split('\n') .map(x => x .trim() .replace(/^\d+.\s*/, '') .replace(/\s*\/+\s*/g, ' // ') .toLowerCase()) .filter(x => x) .join('\n') return { list, cards, packs } } function clickPack(cardName) { let index = rawPack.findIndex(x => x.name === cardName) let card = rawPack[index] if (clicked !== cardName) { clicked = cardName // There may be duplicate cards in a pack, but only one copy of a card is // shown in the pick view. We must be sure to mark them all since we don't // know which one is being displayed. rawPack.forEach(card => card.isAutopick = card.name === cardName) App.update() App.send('autopick', index) return clicked } clicked = null Zones.pack = {} App.update() App.send('pick', index) } function Key(groups, sort) { let keys = Object.keys(groups) switch(sort) { case 'cmc': let arr = [] for (let key in groups) if (parseInt(key) > 6) { ;[].push.apply(arr, groups[key]) delete groups[key] } if (arr.length) { groups['6'] || (groups['6'] = []) ;[].push.apply(groups['6'], arr) } return groups case 'color': keys = ['colorless', 'white', 'blue', 'black', 'red', 'green', 'multicolor'] .filter(x => keys.indexOf(x) > -1) break case 'rarity': keys = ['basic', 'common', 'uncommon', 'rare', 'mythic', 'special'] .filter(x => keys.indexOf(x) > -1) break case 'type': keys = keys.sort() break } let o = {} for (let key of keys) o[key] = groups[key] return o } function sortLandsBeforeNonLands(lhs, rhs) { let isLand = x => x.type.toLowerCase().indexOf('land') !== -1 let lhsIsLand = isLand(lhs) let rhsIsLand = isLand(rhs) return rhsIsLand - lhsIsLand } export function getZone(zoneName) { let zone = Zones[zoneName] let cards = [] for (let cardName in zone) for (let i = 0; i < zone[cardName]; i++) cards.push(Cards[cardName]) let {sort} = App.state let groups = _.group(cards, sort) for (let key in groups) _.sort(groups[key], sortLandsBeforeNonLands, 'color', 'cmc', 'name') groups = Key(groups, sort) return groups }
arxanas/drafts.ninja
public/src/cards.js
JavaScript
mit
10,318
--- layout: page title: Osborn Air Executive Retreat date: 2016-05-24 author: Howard Copeland tags: weekly links, java status: published summary: Aliquam erat volutpat. Aenean finibus odio. banner: images/banner/office-01.jpg booking: startDate: 10/12/2018 endDate: 10/15/2018 ctyhocn: WELMEHX groupCode: OAER published: true --- Maecenas at nisi at ex tempor eleifend. Vestibulum risus dui, convallis ut nisl ac, bibendum consequat ex. Nam a sapien ac nisi cursus tristique eu quis sem. Sed a porta erat. Proin ipsum erat, fringilla in convallis sit amet, suscipit ultrices justo. Nulla blandit nec nulla in vulputate. Nam ultrices viverra mattis. Etiam et eros et ligula dictum posuere. Ut nec erat sit amet tortor volutpat ullamcorper eget a purus. Sed in velit eget nisl euismod convallis sed et est. Donec molestie nisi non tortor viverra lacinia ut id erat. * Duis suscipit libero et nunc venenatis, vitae rhoncus mi aliquam * Nam placerat magna sit amet magna malesuada blandit * Etiam facilisis diam ac consequat scelerisque * Morbi pretium risus ut maximus finibus. Curabitur mollis tortor massa. Donec ut urna ut purus malesuada tincidunt id vel ipsum. Mauris pulvinar, nunc quis euismod faucibus, enim quam bibendum orci, vel fringilla dui lacus nec mauris. Cras quam leo, elementum at ligula nec, euismod euismod odio. Sed sem sapien, pellentesque eu lectus id, porta porttitor nisl. Proin efficitur dolor mi, et gravida turpis laoreet a. Vivamus ac posuere dui, et porttitor metus. Maecenas sem magna, suscipit sed vulputate ut, finibus in tellus. Etiam sit amet cursus erat, in vestibulum magna. Phasellus euismod enim eget nunc tincidunt vestibulum.
KlishGroup/prose-pogs
pogs/W/WELMEHX/OAER/index.md
Markdown
mit
1,675
package com.bioxx.tfc.api; import java.util.HashMap; import java.util.Map; import net.minecraft.item.Item; import com.bioxx.tfc.api.Enums.EnumFoodGroup; public class FoodRegistry { private static final FoodRegistry instance = new FoodRegistry(); public static final FoodRegistry getInstance() { return instance; } private int proteinCount = 0; private Map<Integer, Item> proteinMap; private int vegetableCount = 10000; private Map<Integer, Item> vegetableMap; private int fruitCount = 20000; private Map<Integer, Item> fruitMap; private int grainCount = 30000; private Map<Integer, Item> grainMap; private int dairyCount = 40000; private Map<Integer, Item> dairyMap; private FoodRegistry() { proteinMap = new HashMap<Integer, Item>(); vegetableMap = new HashMap<Integer, Item>(); fruitMap = new HashMap<Integer, Item>(); grainMap = new HashMap<Integer, Item>(); dairyMap = new HashMap<Integer, Item>(); } public int registerFood(EnumFoodGroup efg, Item i) { switch(efg) { case Protein: { proteinMap.put(proteinCount, i); return proteinCount++; } case Vegetable: { vegetableMap.put(vegetableCount, i); return vegetableCount++; } case Fruit: { fruitMap.put(fruitCount, i); return fruitCount++; } case Grain: { grainMap.put(grainCount, i); return grainCount++; } case Dairy: { dairyMap.put(dairyCount, i); return dairyCount++; } default: { return -1; } } } public Item getFood(int id) { if(proteinMap.containsKey(id)) return proteinMap.get(id); if(vegetableMap.containsKey(id)) return vegetableMap.get(id); if(fruitMap.containsKey(id)) return fruitMap.get(id); if(grainMap.containsKey(id)) return grainMap.get(id); if(dairyMap.containsKey(id)) return dairyMap.get(id); return null; } public EnumFoodGroup getFoodGroup(int id) { if(proteinMap.containsKey(id)) return EnumFoodGroup.Protein; if(vegetableMap.containsKey(id)) return EnumFoodGroup.Vegetable; if(fruitMap.containsKey(id)) return EnumFoodGroup.Fruit; if(grainMap.containsKey(id)) return EnumFoodGroup.Grain; if(dairyMap.containsKey(id)) return EnumFoodGroup.Dairy; return EnumFoodGroup.None; } }
vidaj/TFCWaterCompatibility
src/api/java/com/bioxx/tfc/api/FoodRegistry.java
Java
mit
2,230
package achan.nl.uitstelgedrag.ui.presenters; import android.content.Context; import android.location.Location; import android.util.Log; import java.util.List; import achan.nl.uitstelgedrag.domain.models.Task; import achan.nl.uitstelgedrag.persistence.Repository; import achan.nl.uitstelgedrag.persistence.gateways.LabelGateway; import achan.nl.uitstelgedrag.persistence.gateways.TaskGateway; /** * Created by Etienne on 29-5-2016. */ public class TaskPresenterImpl implements TaskPresenter { // Note - there is no gateway for labels because they // are but extra data/part of to other entities. TaskGateway database; Context context; public TaskPresenterImpl(Context context) { this.context = context; this.database = new TaskGateway(context); } @Override public Task addTask(Task task) { Log.i("TaskPresenter", "Added task!"); task.labels.forEach(label -> {label.title = label.title.trim().toLowerCase();}); return database.insert(task); } @Override public Task deleteTask(Task task) { Log.i("TaskPresenter", "Deleted task!"); database.delete(task); return task; } @Override public Task editTask(Task task) { Log.i("TaskPresenter", "Edited task!"); database.update(task); return task; } @Override public List<Task> viewTasks() { return TaskGateway.sortByCreationDate(database.getAll()); } @Override public List<Task> filterTasks(List<Task> tasks, Location location){ return TaskGateway.filterByLocation(tasks, location); } @Override public Task viewTask(Task task) { Log.i("TaskPresenter", "Showing task!"); return database.get(task.id); } @Override public Location getCurrentLocation() { return null; } @Override public Location geocode(String address) { return null; } @Override public String reverseGeocode(Location location) { return null; } }
ikbenpinda/uitstelgedrag_android
app/src/main/java/achan/nl/uitstelgedrag/ui/presenters/TaskPresenterImpl.java
Java
mit
2,046
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Linq; using System.Net.Http; using System.Reflection; using System.Web; using Microsoft.Dash.Common.Diagnostics; using Microsoft.Dash.Common.Handlers; using Microsoft.Dash.Common.Utils; using Microsoft.Dash.Server.Authorization; using Microsoft.Dash.Server.Utils; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; namespace Microsoft.Dash.Server.Handlers { public static class ControllerOperations { public static Uri ForwardUriToNamespace(HttpRequestBase request) { UriBuilder forwardUri = new UriBuilder() { Scheme = request.Url.Scheme, Host = DashConfiguration.NamespaceAccount.BlobEndpoint.Host, Path = request.Path, Query = HttpUtility.ParseQueryString(request.Url.Query).ToString() }; return forwardUri.Uri; } public static Uri GetRedirectUri(HttpRequestBase request, CloudStorageAccount account, string containerName, string blobName, bool decodeQueryParams = true) { return GetRedirectUri(request.Url, request.HttpMethod, account, containerName, blobName, decodeQueryParams); } public static Uri GetRedirectUri(Uri originalUri, string method, CloudStorageAccount account, string containerName, string blobName, bool decodeQueryParams = true) { var redirectUri = GetRedirectUriBuilder(method, originalUri.Scheme, account, containerName, blobName, true, originalUri.Query, decodeQueryParams); return redirectUri.Uri; } public static UriBuilder GetRedirectUriBuilder(string method, string scheme, CloudStorageAccount account, string containerName, string blobName, bool useSas, string queryString, bool decodeQueryParams = true) { CloudBlobContainer container = NamespaceHandler.GetContainerByName(account, containerName); // Strip any existing SAS query params as we'll replace them with our own SAS calculation var queryParams = RequestQueryParameters.Create(queryString, decodeQueryParams); SharedAccessSignature.RemoveSasQueryParameters(queryParams); if (useSas) { // Be careful to preserve the URL encoding in the signature queryParams.Append(CalculateSASStringForContainer(method, container), false); } return new UriBuilder { Scheme = scheme, Host = account.BlobEndpoint.Host, Path = PathUtils.CombineContainerAndBlob(containerName, PathUtils.PathEncode(blobName)), Query = queryParams.ToString(), }; } //calculates Shared Access Signature (SAS) string based on type of request (GET, HEAD, DELETE, PUT) static SharedAccessBlobPolicy GetSasPolicy(HttpRequestBase request) { return GetSasPolicy(request.HttpMethod); } static SharedAccessBlobPolicy GetSasPolicy(string method) { return GetSasPolicy(new HttpMethod(method)); } static SharedAccessBlobPolicy GetSasPolicy(HttpMethod httpMethod) { //Default to read only SharedAccessBlobPermissions permission = SharedAccessBlobPermissions.Read; if (httpMethod == HttpMethod.Delete) { permission = SharedAccessBlobPermissions.Delete; } else if (httpMethod == HttpMethod.Put) { permission = SharedAccessBlobPermissions.Write; } return new SharedAccessBlobPolicy() { Permissions = permission, SharedAccessStartTime = DateTime.Now.AddMinutes(-5), SharedAccessExpiryTime = DateTime.Now.AddMinutes(54) }; } //calculates SAS string to have access to a container public static string CalculateSASStringForContainer(string method, CloudBlobContainer container) { SharedAccessBlobPolicy sasConstraints = GetSasPolicy(method); //Generate the shared access signature on the container, setting the constraints directly on the signature. return container.GetSharedAccessSignature(sasConstraints); } } }
CedarLogic/Dash
DashServer/Handlers/ControllerOperations.cs
C#
mit
4,761
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Java的安全性</title> <link rel="stylesheet" href="/styles/css/index.css"> <link rel="stylesheet" href="/styles/css/fontawesome/css/font-awesome.min.css"> <link rel="canonical" href="/2016/11/22/DEEP_IN_JAVA_VM__security/"> <link rel="alternate" type="application/rss+xml" title="Jun Xi Gu 的博客" href="/feed.xml"> <meta name="description" content="顾俊喜;个人博客"> <style type="text/css"> .docs-content{ margin-bottom: 10px; } </style> </head> <body class="index"> <header class="navbar navbar-inverse navbar-fixed-top docs-nav" role="banner"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation"> <ul class="nav navbar-nav"> <li> <a href="/">主页</a> </li> <li> <a href="/categories/">分类博客</a> </li> <li> <a href="/tag">标签博客</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">关于<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a rel="nofollow" target="_blank" href="https://github.com/junxigu/">Github</a></li> <li><a rel="nofollow" target="_blank" href="https://github.com/luoyan35714/LessOrMore.git">本博客模板</a></li> </ul> </li> </ul> </nav> </div> </header> <div class="docs-header" id="content"> <div class="container"> <!-- <h1>Java的安全性</h1> <p>Post on Nov 22, 2016 by <a href="/about">Jun Xi Gu</a></p> --> <h1>Stay Hungry Stay Foolish</h1> </div> </div> <div class="banner"> <div class="container"> <a href="/categories/#技术-ref">技术</a> / <a href="/tag/#Java-ref">Java</a> </div> </div> <div class="container docs-container"> <div class="row"> <div class="col-md-3"> <div class="sidebar hidden-print" role="complementary"> <div id="navigation"> <h1>目录</h1> <ul class="nav sidenav"> <!-- <li><a href="#year_2017">2017</a> <ul class="nav"> <li><a href="#month_2017_September">September</a></li> <li><a href="#month_2017_August">August</a></li> <li><a href="#month_2017_May">May</a></li> <li><a href="#month_2017_February">February</a></li> <li><a href="#month_2017_January">January</a></li> </ul> </li> <li><a href="#year_2016">2016</a> <ul class="nav"> <li><a href="#month_2016_December">December</a></li> <li><a href="#month_2016_November">November</a></li> <li><a href="#month_2016_October">October</a></li> <li><a href="#month_2016_September">September</a></li> </ul> </li> --> </ul> </div> </div> </div> <div class="col-md-9" role="main"> <div class="panel docs-content"> <div class="wrapper"> <header class="post-header"> <h1 class="post-title">Java的安全性</h1> <!-- <p class="post-meta">Nov 22, 2016</p> --> <div class="meta">Posted on <span class="postdate">Nov 22, 2016</span> By <a target="_blank" href="">Jun Xi Gu</a></div> <br /> </header> <article class="post-content"> <ul id="markdown-toc"> <li><a href="#java-安全性是什么" id="markdown-toc-java-安全性是什么">Java 安全性是什么</a></li> <li><a href="#java-为什么需要安全性" id="markdown-toc-java-为什么需要安全性">Java 为什么需要安全性</a></li> <li><a href="#java-怎么样实现安全性" id="markdown-toc-java-怎么样实现安全性">Java 怎么样实现安全性</a> <ul> <li><a href="#类加载器体系结构" id="markdown-toc-类加载器体系结构">类加载器体系结构</a></li> <li><a href="#class文件检验器" id="markdown-toc-class文件检验器">class文件检验器</a></li> <li><a href="#java虚拟机中内置的安全特性" id="markdown-toc-java虚拟机中内置的安全特性">Java虚拟机中内置的安全特性</a></li> <li><a href="#安全管理器和java-api" id="markdown-toc-安全管理器和java-api">安全管理器和Java API</a></li> </ul> </li> </ul> <p><strong>本文是对Java的安全性的汇总和个人理解,此处的内容是针对旧版的Java</strong></p> <hr /> <h2 id="java-安全性是什么">Java 安全性是什么</h2> <p>Java 通过其安全模型 来保护终端用户免受从网路下载的、来自不可靠来源的、恶意程序的侵犯</p> <h2 id="java-为什么需要安全性">Java 为什么需要安全性</h2> <p>Java 程序是可从任意来源获取并运行的,因此需要保证运行这些代码时能进行限制,免受恶意代码的破坏</p> <h2 id="java-怎么样实现安全性">Java 怎么样实现安全性</h2> <p>Java 使用沙箱模型来对程序运行进行限制,防止其进行破坏,沙箱模型由一些基本组件组成</p> <ul> <li>类加载器体系结构</li> <li>class文件检验器</li> <li>内置于Java虚拟机(及语言)的安全特性</li> <li>安全管理器及Java API</li> </ul> <p><img src="../../../../styles/images/java_security.png" alt="alt text" /></p> <p>前三个组成部分是为了保证JVM和它正在运行的应用程序的完整性,免受下载的恶意程序的侵犯;最后一个部分是为了保护外部资源不被JVM中运行的恶意程序侵犯</p> <h3 id="类加载器体系结构">类加载器体系结构</h3> <p><strong>是什么?</strong></p> <ul> <li>类加载器是用于动态的加载类二进制流的对象</li> <li>类加载有4类:启动类加载器(java内部实现,负责加载java核心API)、标准扩展类加载器(java自带,加载ext目录下的类)、类路径类加载器(java自带,加载CLASS_PATH环境变量下的类)、自定义类加载器</li> <li>类加载器使用双亲委派模式进行类的加载(非启动类加载器都有一个双亲类加载器的引用,加载类时会先让双亲加载,若双亲加载不到才自己加载),启动类加载器 &lt;- 标准扩展类加载器 &lt;- 类路径类加载器 &lt;- 自定义类加载器,保证可信的类由可信的类加载器优先加载</li> </ul> <p><strong>为什么?</strong></p> <p>类加载器是可信和不可信程序的入口,通过类加载器体系机构能够在一定程度上实现可信程序和不可信程序的隔离,并能对不可信的程序的资源访问进行限制</p> <p><strong>怎么样?</strong></p> <p>类加载器体系结构的作用</p> <ul> <li>防止恶意代码干涉正常代码</li> </ul> <p>不同的类加载器加载的代码属于不同的命名空间(相同的类可以用不同类加载器多次加载到JVM),不同的命名空间中的代码不能互相访问(除非显式运行交互),达到隔离恶意代码的效果</p> <ul> <li>守护了被信任的类库的边界</li> </ul> <p>使用类加载器双亲委托模型来保证所有信任的类库都通过信任的加载器来加载,不可靠的类可以使用自定义的加载器加载</p> <ul> <li>为类创建保护域,由保护域来确定类所拥有的权限</li> </ul> <p>每个类都属于一个保护域,用户可以为某个保护域的类设置资源的访问权限策略,这样就能起到限制代码权限的作用</p> <h3 id="class文件检验器">class文件检验器</h3> <p><strong>是什么?</strong></p> <p>class文件检验器是对 类加载器加载的类 进行检查的对象</p> <p><strong>为什么?</strong></p> <p>虚拟机不能保证 加载的类 是由合法的编译器生成的,需要对类二进制流的 结构,类型,语义,符号引用信息 进行检查,保证其完整性和健壮性</p> <p><strong>怎么样?</strong></p> <p>class文件检验器需要进行四趟扫描来完成校验</p> <ul> <li>class文件的结构检查</li> </ul> <p>检查class文件的结构是否满足java对于一个类型的结构的定义,包括魔数、结构、长度等</p> <ul> <li>类型数据的语义检查</li> </ul> <p>检查各个组成部分的类型是否满足其所属的类型的定义,并检查这个类文件本身的类是否满足编译器所规定的条件</p> <ul> <li>字节码验证</li> </ul> <p>通过对字节码流中的操作码,操作数进行检查,保证所有字节码都能安全的执行</p> <ul> <li>符号引用的验证</li> </ul> <p>在执行过程中第一次引用新的类型时需要进行动态链接,这时候需要对引用的合法性(存在性等)进行校验,从而保证被引用的类文件的二进制兼容性</p> <h3 id="java虚拟机中内置的安全特性">Java虚拟机中内置的安全特性</h3> <p>JVM通过在执行过程中加入以下特性来增强程序的健壮性</p> <ul> <li>类型安全的引用转换</li> <li>结构化的内存访问</li> <li>自动垃圾收集</li> <li>数组边界检查</li> <li>空引用检查</li> </ul> <h3 id="安全管理器和java-api">安全管理器和Java API</h3> <p><strong>是什么?</strong></p> <p>安全访问器是一个对象,它能确定一个程序是否有权限访问一个受保护的资源</p> <p>所有对资源的访问都是通过Java API来完成的,当给应用程序赋予了一个安全管理器实例时,则Java API在访问资源前都会让安全管理器确认程序是否有权限访问资源</p> <p><strong>为什么?</strong></p> <p>通过把对资源的访问封装在Java API里,然后API在访问资源前使用安全管理器确认程序是否有权限访问资源,这样就能保护外部资源不被不受信任的程序访问</p> <p><strong>怎么样?</strong></p> <p>Java通过签名对 受信任的代码 确定其身份和完整性</p> <p>一个class文件有它的代码来源,代码来源是指 代码从哪来、若被签名则是从谁那里来</p> <p>代码对资源所拥有的访问权限都与代码的代码来源相关联,所以在给某段代码赋予权限时,要制定其来源和所拥有权限</p> <p>所有的代码权限赋予都记录在一个ASCII策略文件里,文件里的内容有固定的语法,内容大意是 给 某个代码来源的代码 赋予 访问某种资源的权限</p> <p>类加载器 在加载类时 会给类创建一个保护域,保护域里有策略文件里定义的代码来源 和 所拥有的权限(类加载器也可以不参考策略文件),当程序使用Java API时,安全管理器 能通过代码的保护域中的权限来确定代码是否有权访问资源</p> <p>安全管理器通过获取Java栈中 从资源访问调用开始到栈顶的所有栈帧,然后从每个栈帧所关联的class中获取保护域,并根据保护域中的权限来确定每个栈帧关联的类能否访问资源</p> <p><img src="../../../../styles/images/java_access_permision_check.png" alt="alt text" /></p> </article> </div> </div> <div class="panel docs-content"> <article class="post-content"> <div class="wrapper"> </div> </article> </div> </div> </div> </div> <footer class="footer" role="contentinfo"> <div class="container"> <p class="copyright">Copyright &copy; 2014-2020 <a href=""><code>Jun Xi Gu</code></a>.</p> <p>Customizied from <a href="https://github.com/luoyan35714/LessOrMore">LessOrMore</a></p></p> <p>Powered by <a href="http://jekyllrb.com">Jekyll</a>, theme from <a href="http://lesscss.cn/">Less</a></p> </div> </footer> <script src="/styles/js/jquery.min.js"></script> <script src="/styles/js/bootstrap.min.js"></script> <script src="/styles/js/holder.min.js"></script> <script src="/styles/js/application.js"></script> <script src="/styles/js/lessismore.js"></script> </body> </html>
junxigu/junxigu.github.io
2016/11/22/DEEP_IN_JAVA_VM__security/index.html
HTML
mit
15,052
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>W28714_text</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;"> <div style="float: left;"> <a href="page18.html">&laquo;</a> </div> <div style="float: right;"> </div> </div> <hr/> <div style="position: absolute; margin-left: 385px; margin-top: 247px;"> <p class="styleSans27.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/>awwoéo; 00> gwnd , - ooonmo - (3— _ H - mm cod m2}: Eomfivnvél wwénmdom om: foam.— - cemvo - H22 fl _ - _ mm 3.0 memxg 38-8012 demfimmm om: Axbwd - ooohmn - :_2 , ~ _ - mm mod «max: "38-604: vmhmwdwm ooi AXbcd - 00060 - H2: _ w - wm cod 0506— 38-30-: vcwmfiowm ooh A$320 - ooodn - ~22 _ H - mm W cod owed $2-606— vfimomdnm as: $8.3 0N coonwm a; 92 Cw Nfi 3 04» ca 092 owed EoméoOé adoonmhm oQon fiewmdfi ON 25va Sum :56 0— N“ mg» _m 91: nmmd EONLQOJW mwdwvfiwm , 0Q: $mw.2 ON coo. I» mfim :52w 0 2 w.m om mmd. 054w ioméoO$ o_.0mx,mmm oQE $052 QN coed? Em ZBCw I E E» S 2.2 mmvro 3om-80-c wnémbnm—m cméh famed” ON ooohov mom Rim w a 0+ _ om 00A: o5.m ,Eom-aoo-m i ECU m=H=>m< <br/> <br/> </p> </div> <div style="position: absolute; margin-left: 220px; margin-top: 1457px;"> <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">QmOUm—m ODE </p> </div> <div style="position: absolute; margin-left: 2392px; margin-top: 1650px;"> <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p> </div> </body> </html>
datamade/elpc_bakken
ocr_extracted/W28714_text/page19.html
HTML
mit
2,002
<?php namespace Comodojo\WPAPI; use \Comodojo\Exception\WPException; /** * Comodojo Wordpress API Wrapper. This class is an iterator for WPMedia class * * It allows to fetch through media object into the Wordpress media library. * * @package Comodojo Spare Parts * @author Marco Castiello <marco.castiello@gmail.com> * @license MIT * * LICENSE: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE 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. */ class WPMediaIterator extends WPIteratorObject { /** * Post ID * * @var int */ private $post = 0; /** * Mime-Type of the media object to fetch * * @var int */ private $mime = ""; /** * Class constructor * * @param Object $blog Reference to a blog object * @param int $post Post ID (optional) * * @throws \Comodojo\Exception\WPException */ public function __construct($blog, $post=0, $mime=null) { if ( is_null($blog) || is_null($blog->getWordpress()) || !$blog->getWordpress()->isLogged() ) { throw new WPException("You must be logged to fetch media items"); } $this->blog = $blog; $this->mime = $mime; $this->post = intval($post); } /** * Check if there is another element in the media library * * @return boolean $hasNext * * @throws \Comodojo\Exception\WPException */ public function hasNext() { if (!$this->has_next) { $image = new WPMedia($this->getBlog()); $image->setPostID($this->post); $this->object = $image->loadFromLibrary($this->current, $this->mime); if (!is_null($this->object)) { $this->has_next = true; } } return $this->has_next; } /** * Get next element in the media library * * @return WPMedia $object * * @throws \Comodojo\Exception\WPException */ public function getNext() { if ($this->has_next || $this->hasNext()) { $this->current++; $this->has_next = false; return $this->object; } return null; } }
comodojo/wpapi
src/Iterator/WPMediaIterator.php
PHP
mit
2,781
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Setup_cc_type extends Root_Controller { private $message; public $permissions; public $controller_url; public function __construct() { parent::__construct(); $this->message=""; $this->permissions=User_helper::get_permission('Setup_cc_type'); $this->controller_url='setup_cc_type'; } public function index($action="list",$id=0) { if($action=="list") { $this->system_list($id); } elseif($action=="get_items") { $this->get_items(); } elseif($action=="add") { $this->system_add(); } elseif($action=="edit") { $this->system_edit($id); } elseif($action=="save") { $this->system_save(); } else { $this->system_list($id); } } private function system_list() { if(isset($this->permissions['action0'])&&($this->permissions['action0']==1)) { $data['title']="Classification List"; $ajax['status']=true; $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view("setup_cc_type/list",$data,true)); if($this->message) { $ajax['system_message']=$this->message; } $ajax['system_page_url']=site_url($this->controller_url); $this->jsonReturn($ajax); } else { $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS"); $this->jsonReturn($ajax); } } private function get_items() { $this->db->from($this->config->item('table_cc_types').' types'); $this->db->select('types.id id,types.name type_name'); $this->db->select('types.remarks remarks,types.status status,types.ordering ordering'); $this->db->select('crops.name crop_name'); $this->db->select('classifications.name classification_name'); $this->db->join($this->config->item('table_cc_classifications').' classifications','classifications.id = types.classification_id','INNER'); $this->db->join($this->config->item('table_cc_crops').' crops','crops.id = classifications.crop_id','INNER'); $this->db->where('types.status !=',$this->config->item('system_status_delete')); $classifications=$this->db->get()->result_array(); $this->jsonReturn($classifications); } private function system_add() { if(isset($this->permissions['action1'])&&($this->permissions['action1']==1)) { $data['title']="Create New Type"; $data['type']['id']=0; $data['type']['crop_id']=0; $data['type']['classification_id']=0; $data['type']['name']=''; $data['type']['remarks']=''; $data['type']['ordering']=99; $data['type']['status']=$this->config->item('system_status_active'); $data['crops']=Query_helper::get_info($this->config->item('table_cc_crops'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'),0,0,array('ordering ASC')); $data['classifications']=array(); $ajax['status']=true; $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view("setup_cc_type/add_edit",$data,true)); if($this->message) { $ajax['system_message']=$this->message; } $ajax['system_page_url']=site_url($this->controller_url.'/index/add'); $this->jsonReturn($ajax); } else { $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS"); $this->jsonReturn($ajax); } } private function system_edit($id) { if(isset($this->permissions['action2'])&&($this->permissions['action2']==1)) { if(($this->input->post('id'))) { $type_id=$this->input->post('id'); } else { $type_id=$id; } $this->db->from($this->config->item('table_cc_types').' types'); $this->db->select('types.*'); $this->db->select('classifications.crop_id crop_id'); $this->db->join($this->config->item('table_cc_classifications').' classifications','classifications.id = types.classification_id','INNER'); $this->db->where('types.id',$type_id); $data['type']=$this->db->get()->row_array(); $data['crops']=Query_helper::get_info($this->config->item('table_cc_crops'),array('id value','name text'),array('status ="'.$this->config->item('system_status_active').'"'),0,0,array('ordering ASC')); $data['classifications']=Query_helper::get_info($this->config->item('table_cc_classifications'),array('id value','name text'),array('crop_id ='.$data['type']['crop_id']),0,0,array('ordering ASC')); $data['title']="Edit Type (".$data['type']['name'].')'; $ajax['status']=true; $ajax['system_content'][]=array("id"=>"#system_content","html"=>$this->load->view("setup_cc_type/add_edit",$data,true)); if($this->message) { $ajax['system_message']=$this->message; } $ajax['system_page_url']=site_url($this->controller_url.'/index/edit/'.$type_id); $this->jsonReturn($ajax); } else { $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS"); $this->jsonReturn($ajax); } } private function system_save() { $user=User_helper::get_user(); $time=time(); $id = $this->input->post("id"); if($id>0) { if(!(isset($this->permissions['action2'])&&($this->permissions['action2']==1))) { $ajax['status']=false; $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS"); $this->jsonReturn($ajax); die(); } } else { if(!(isset($this->permissions['action1'])&&($this->permissions['action1']==1))) { $ajax['status']=false; $ajax['system_message']=$this->lang->line("YOU_DONT_HAVE_ACCESS"); $this->jsonReturn($ajax); die(); } } if(!$this->check_validation()) { $ajax['status']=false; $ajax['system_message']=$this->message; $this->jsonReturn($ajax); } else { $data = $this->input->post('type'); $this->db->trans_start(); //DB Transaction Handle START if($id>0) { $data['user_updated']=$user->user_id; $data['date_updated']=$time; Query_helper::update($this->config->item('table_cc_types'),$data,array("id = ".$id)); } else { $data['user_created'] = $user->user_id; $data['date_created'] = $time; Query_helper::add($this->config->item('table_cc_types'),$data); } $this->db->trans_complete(); //DB Transaction Handle END if ($this->db->trans_status() === TRUE) { $save_and_new=$this->input->post('system_save_new_status'); $this->message=$this->lang->line("MSG_SAVED_SUCCESS"); if($save_and_new==1) { $this->system_add(); } else { $this->system_list(); } } else { $ajax['status']=false; $ajax['system_message']=$this->lang->line("MSG_SAVED_FAIL"); $this->jsonReturn($ajax); } } } private function check_validation() { $this->load->library('form_validation'); $this->form_validation->set_rules('type[classification_id]',$this->lang->line('LABEL_CLASSIFICATION_NAME'),'required'); $this->form_validation->set_rules('type[name]',$this->lang->line('LABEL_TYPE_NAME'),'required'); if($this->form_validation->run() == FALSE) { $this->message=validation_errors(); return false; } return true; } }
islambuet/pms
application/controllers/Setup_cc_type.php
PHP
mit
8,644
# goingnative **A NodeSchool style workshopper for learning how to write native Node.js addons** [![NPM](https://nodei.co/npm/goingnative.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/goingnative/) [![NPM](https://nodei.co/npm-dl/goingnative.png?months=3&height=3)](https://nodei.co/npm/goingnative/) ![goingnative](https://github.com/rvagg/goingnative/raw/master/goingnative.png) ***Please note this is a work in progress and is far from complete but will serve as an interesting introduction*** ```sh sudo npm install goingnative -g goingnative ``` ## Contributors * [Will Blankenship](https://github.com/wblankenship) * [Benjamin Byholm](https://github.com/kkoopa) * [Trevor Norris](https://github.com/trevnorris) * [Adam Brady](https://github.com/someoneweird) ## License **goingnative** is Copyright (c) 2014 Rod Vagg [@rvagg](https://twitter.com/rvagg) and contributors licensed under the MIT License. All rights not explicitly granted in the MIT License are reserved. See the included [LICENSE.md](./LICENSE.md) file for more details.
workshopper/goingnative
README.md
Markdown
mit
1,076
#!/bin/bash puppet agent -td
aepod/Magento-Vagrant-Puppet-Sandbox
scripts/web/initial_setup.sh
Shell
mit
29
require 'stella' TEST_URI = 'http://bff.heroku.com/' ## Stella::Engine is aware of all available modes Stella::Engine.modes #=> { :checkup => Stella::Engine::Checkup } ## Checkup has a mode Stella::Engine::Checkup.mode #=> :checkup ## Can run checkup @plan = Stella::Testplan.new TEST_URI @run = Stella::Testrun.new @plan, :checkup, :repetitions => 3, :agent => :poop Stella::Engine::Checkup.run @run @report = @run.report @report.processed? #=> true ## Knows about errors @report.errors? #=> false ## Can be yaml @report.to_yaml.size > 100 #=> true
solutious/stella
try/00_basics_try.rb
Ruby
mit
558
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; }); /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\ContactForm::class, function (Faker\Generator $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'question' => $faker->text, ]; });
jasonlbeggs/personal-website
database/factories/ModelFactory.php
PHP
mit
1,038
#!/usr/bin/env python import atexit import argparse import getpass import sys import textwrap import time from pyVim import connect from pyVmomi import vim import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default pass else: # Handle target environment that doesn't support HTTPS verification ssl._create_default_https_context = _create_unverified_https_context def get_args(): parser = argparse.ArgumentParser() # because -h is reserved for 'help' we use -s for service parser.add_argument('-s', '--host', required=True, action='store', help='vSphere service to connect to') # because we want -p for password, we use -o for port parser.add_argument('-o', '--port', type=int, default=443, action='store', help='Port to connect on') parser.add_argument('-u', '--user', required=True, action='store', help='User name to use when connecting to host') parser.add_argument('-p', '--password', required=False, action='store', help='Password to use when connecting to host') parser.add_argument('-n', '--name', required=True, action='store', help='Name of the virtual_machine to look for.') args = parser.parse_args() if not args.password: args.password = getpass.getpass( prompt='Enter password for host %s and user %s: ' % (args.host, args.user)) return args def _create_char_spinner(): """Creates a generator yielding a char based spinner. """ while True: for c in '|/-\\': yield c _spinner = _create_char_spinner() def spinner(label=''): """Prints label with a spinner. When called repeatedly from inside a loop this prints a one line CLI spinner. """ sys.stdout.write("\r\t%s %s" % (label, _spinner.next())) sys.stdout.flush() def answer_vm_question(virtual_machine): print "\n" choices = virtual_machine.runtime.question.choice.choiceInfo default_option = None if virtual_machine.runtime.question.choice.defaultIndex is not None: ii = virtual_machine.runtime.question.choice.defaultIndex default_option = choices[ii] choice = None while choice not in [o.key for o in choices]: print "VM power on is paused by this question:\n\n" print "\n".join(textwrap.wrap( virtual_machine.runtime.question.text, 60)) for option in choices: print "\t %s: %s " % (option.key, option.label) if default_option is not None: print "default (%s): %s\n" % (default_option.label, default_option.key) choice = raw_input("\nchoice number: ").strip() print "..." return choice # form a connection... args = get_args() si = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=args.port) # doing this means you don't need to remember to disconnect your script/objects atexit.register(connect.Disconnect, si) # search the whole inventory tree recursively... a brutish but effective tactic vm = None entity_stack = si.content.rootFolder.childEntity while entity_stack: entity = entity_stack.pop() if entity.name == args.name: vm = entity del entity_stack[0:len(entity_stack)] elif hasattr(entity, 'childEntity'): entity_stack.extend(entity.childEntity) elif isinstance(entity, vim.Datacenter): entity_stack.append(entity.vmFolder) if not isinstance(vm, vim.VirtualMachine): print "could not find a virtual machine with the name %s" % args.name sys.exit(-1) print "Found VirtualMachine: %s Name: %s" % (vm, vm.name) if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: # using time.sleep we just wait until the power off action # is complete. Nothing fancy here. print "reset the vm" task = vm.ResetVM_Task() while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]: time.sleep(1) print "resetting vm ..." sys.exit(0)
kenelite/vmapi
005reset.py
Python
mit
4,622
#include <string.h> #include "object.h" #include "strproc.h" #include "procdef.h" #include "mem.h" #include "sstream.h" #include "gc.h" #include "sstream.h" static int make_string_proc(object *params, object **result) { object *len_obj, *char_obj; char c; long len; char *buf; check_null(result); if (is_empty_list(params)) { return SC_E_ARITY; } len_obj = car(params); if (!is_fixnum(len_obj)) { return SC_E_ARG_TYPE; } len = obj_nv(len_obj); if (is_empty_list(cdr(params))) { c = 'x'; } else if (is_empty_list(cddr(params))) { char_obj = cadr(params); if (!is_character(char_obj)) { return SC_E_ARG_TYPE; } c = obj_cv(char_obj); } else { return SC_E_ARITY; } buf = sc_malloc(len + 1); memset(buf, c, len); buf[len] = '\0'; *result = make_string(buf); sc_free(buf); if (*result == NULL) { return SC_E_NO_MEM; } return 0; } static int string_proc(object *params, object **result) { sstream *stream; object *obj, *rest; char *str; int ret; check_null(result); if (is_empty_list(params)) { return SC_E_ARITY; } stream = sstream_new(-1); if (stream == NULL) { return SC_E_NO_MEM; } rest = params; while (!is_empty_list(rest)) { obj = car(rest); if (!is_character(obj)) { sstream_dispose(stream); return SC_E_ARG_TYPE; } ret = sstream_append(stream, obj_cv(obj)); if (ret != 0) { sstream_dispose(stream); return SC_E_NO_MEM; } rest = cdr(rest); } str = sstream_cstr(stream); if (str == NULL) { sstream_dispose(stream); return SC_E_NO_MEM; } *result = make_string(str); sc_free(str); if (*result == NULL) { return SC_E_NO_MEM; } sstream_dispose(stream); return 0; } static int string_length_proc(object *params, object **result) { object *obj; check_null(result); check_arg1(params); obj = car(params); if (!is_string(obj)) { return SC_E_ARG_TYPE; } *result = make_fixnum(obj_slenv(obj)); if (*result == NULL) { return SC_E_NO_MEM; } return 0; } static int string_ref_proc(object *params, object **result) { int i, len; object *obj, *idx_obj; char *str; check_null(result); check_arg2(params); obj = car(params); if (!is_string(obj)) { return SC_E_ARG_TYPE; } idx_obj = cadr(params); if (!is_fixnum(idx_obj)) { return SC_E_ARG_TYPE; } len = obj_slenv(obj); i = (int)obj_nv(idx_obj); if (i < 0 || i >= len) { return SC_E_INVL_INDEX; } str = obj_sv(obj); *result = make_character(str[i]); if (*result == NULL) { return SC_E_NO_MEM; } return 0; } static int string_set_proc(object *params, object **result) { object *str_obj, *idx_obj, *char_obj; char *str; int i, len; check_null(result); check_arg3(params); str_obj = car(params); if (!is_string(str_obj)) { return SC_E_ARG_TYPE; } idx_obj = cadr(params); if (!is_fixnum(idx_obj)) { return SC_E_ARG_TYPE; } char_obj = caddr(params); if (!is_character(char_obj)) { return SC_E_ARG_TYPE; } len = obj_slenv(str_obj); i = (int)obj_nv(idx_obj); if (i < 0 || i >= len) { return SC_E_INVL_INDEX; } str = obj_sv(str_obj); str[i] = obj_cv(char_obj); *result = str_obj; return 0; } static int compare_string(object *a, object *b) { char *p, *q; p = obj_sv(a); q = obj_sv(b); return strcmp(p, q); } static int string_is_equal_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string(a, b); if (ret == 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_is_greater_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string(a, b); if (ret > 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_is_less_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string(a, b); if (ret < 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_is_not_less_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string(a, b); if (ret >= 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_is_not_greater_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string(a, b); if (ret <= 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int compare_string_ci(object *a, object *b) { char *p, *q; p = obj_sv(a); q = obj_sv(b); return strcasecmp(p, q); } static int string_ci_equal_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string_ci(a, b); if (ret == 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_ci_greater_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string_ci(a, b); if (ret > 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_ci_less_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string_ci(a, b); if (ret < 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_ci_not_less_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string_ci(a, b); if (ret >= 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int string_ci_not_greater_proc(object *params, object **result) { object *a, *b; int ret; check_null(result); check_arg2(params); a = car(params); b = cadr(params); if (!is_string(a) || !is_string(b)) { return SC_E_ARG_TYPE; } ret = compare_string_ci(a, b); if (ret <= 0) { *result = get_true_obj(); } else { *result = get_false_obj(); } return 0; } static int substring_proc(object *params, object **result) { object *str_obj, *s_obj, *e_obj; int start, end, len, buflen; char *str, *buf; check_null(result); check_arg3(params); str_obj = car(params); if (!is_string(str_obj)) { return SC_E_ARG_TYPE; } str = obj_sv(str_obj); len = obj_slenv(str_obj); s_obj = cadr(params); e_obj = caddr(params); if (!is_fixnum(s_obj) || !is_fixnum(e_obj)) { return SC_E_ARG_TYPE; } start = (int)obj_nv(s_obj); end = (int)obj_nv(e_obj); if (start < 0 || end > len || start > end) { return SC_E_ARG_INVL; } buflen = end - start; buf = sc_malloc(buflen + 1); if (buf == NULL) { return SC_E_NO_MEM; } strncpy(buf, str + start, buflen); /* no NUL at end */ buf[buflen] = '\0'; *result = make_string(buf); sc_free(buf); if (*result == NULL) { return SC_E_NO_MEM; } return 0; } static int string_copy_proc(object *params, object **result) { object *src; check_null(result); check_arg1(params); src = car(params); if (!is_string(src)) { return SC_E_ARG_TYPE; } *result = make_string(obj_sv(src)); if (*result == NULL) { return SC_E_NO_MEM; } return 0; } static int string_fill_proc(object *params, object **result) { object *str, *ch; check_null(result); check_arg2(params); str = car(params); ch = cadr(params); if (!is_string(str) || !is_character(ch)) { return SC_E_ARG_TYPE; } memset(obj_sv(str), obj_cv(ch), obj_slenv(str)); *result = str; return 0; } static int total_length(object *seq) { object *elem, *rest; int len = 0; rest = seq; while (!is_empty_list(rest)) { elem = car(rest); if (!is_string(elem)) { return -1; } len += obj_slenv(elem); rest = cdr(rest); } return len; } static int string_append_proc(object *params, object **result) { object *rest, *elem; int len; char *buf; check_null(result); if (is_empty_list(params)) { return SC_E_ARITY; } len = total_length(params); if (len == -1) { return SC_E_ARG_TYPE; } buf = sc_malloc(len + 1); if (buf == NULL) { return SC_E_NO_MEM; } buf[0] = '\0'; rest = params; while (!is_empty_list(rest)) { elem = car(rest); strcat(buf, obj_sv(elem)); rest = cdr(rest); } *result = make_string(buf); if (*result == NULL) { return SC_E_NO_MEM; } return 0; } static int string_to_list_proc(object *params, object **result) { object *str_obj, *list, *ch; char *str; int len, i; check_null(result); check_arg1(params); str_obj = car(params); if (!is_string(str_obj)) { return SC_E_ARG_TYPE; } str = obj_sv(str_obj); len = obj_slenv(str_obj); list = get_empty_list(); ch = make_character(str[len-1]); gc_protect(ch); list = cons(ch, list); gc_protect(list); for (i = len - 2; i >= 0; i--) { ch = make_character(str[i]); list = cons(ch, list); } gc_abandon(); gc_abandon(); *result = list; return 0; } static int list_to_string_proc(object *params, object **result) { object *list, *ch; sstream *stream; char *str; int ret; check_null(result); check_arg1(params); list = car(params); if (!is_pair(list)) { return SC_E_ARG_TYPE; } stream = sstream_new(-1); if (stream == NULL) { return SC_E_NO_MEM; } while (!is_empty_list(list)) { ch = car(list); if (!is_character(ch)) { sstream_dispose(stream); return SC_E_ARG_TYPE; } ret = sstream_append(stream, obj_cv(ch)); if (ret != 0) { sstream_dispose(stream); return SC_E_NO_MEM; } list = cdr(list); if (!is_pair(list) && !is_empty_list(list)) { sstream_dispose(stream); return SC_E_ARG_TYPE; } } str = sstream_cstr(stream); if (str == NULL) { sstream_dispose(stream); return SC_E_NO_MEM; } *result = make_string(str); sc_free(str); sstream_dispose(stream); if (*result == NULL) { return SC_E_NO_MEM; } return 0; } int init_str_primitive(object *env) { define_proc("make-string", make_string_proc); define_proc("string", string_proc); define_proc("string-length", string_length_proc); define_proc("string-ref", string_ref_proc); define_proc("string-set!", string_set_proc); define_proc("string=?", string_is_equal_proc); define_proc("string-ci=?", string_ci_equal_proc); define_proc("string<?", string_is_less_proc); define_proc("string>?", string_is_greater_proc); define_proc("string<=?", string_is_not_greater_proc); define_proc("string>=?", string_is_not_less_proc); define_proc("string-ci<?", string_ci_less_proc); define_proc("string-ci>?", string_ci_greater_proc); define_proc("string-ci<=?", string_ci_not_greater_proc); define_proc("string-ci>=?", string_ci_not_less_proc); define_proc("substring", substring_proc); define_proc("string-copy", string_copy_proc); define_proc("string-fill!", string_fill_proc); define_proc("string-append", string_append_proc); define_proc("string->list", string_to_list_proc); define_proc("list->string", list_to_string_proc); return 0; }
cpylua/scheme
strproc.c
C
mit
13,814
require 'rails_helper' RSpec.describe ResourceController, vcr: true do describe 'GET index' do it 'should raise a routing error (404)' do expect{get :index}.to raise_error(ActionController::RoutingError) end end describe 'GET grom nodes' do context 'successfully' do before(:each) do get :show, params: { resource_id: 'xP2kB45W' } end it 'assigns @results if grom nodes can be found' do assigns(:results).each do |result| expect(result).to be_a(Grom::Node) end end end context 'unsuccessfully' do it 'raises error if no grom nodes can be found (404)' do expect{get :show, params: { resource_id: '12345678' }}.to raise_error(ActionController::RoutingError) end end end describe 'Handling response' do context 'when a route exits' do before(:each) do get :show, params: { resource_id: 'xP2kB45W' } end it 'redirects to correct path' do expect(response).to redirect_to(person_path('xP2kB45W')) end end context 'when no route exists' do before(:each) do get :show, params: { resource_id: 'sYpq0s7D' } end it 'renders the show template' do expect(response).to render_template('show') end end end end
cwaszczuk/parliament.uk-prototype
spec/controllers/resource_controller_spec.rb
Ruby
mit
1,323
// <copyright file="RepeatableQueue{T}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System.Collections; using System.Diagnostics.CodeAnalysis; using IX.StandardExtensions.Contracts; using JetBrains.Annotations; namespace IX.System.Collections.Generic; /// <summary> /// A queue that is able to accurately repeat the sequence of items that has been dequeued from it. /// </summary> /// <typeparam name="T">The type of items contained in this queue.</typeparam> /// <seealso cref="IQueue{T}" /> [PublicAPI] [SuppressMessage( "Design", "CA1010:Generic interface should also be implemented", Justification = "This is not necessary.")] public class RepeatableQueue<T> : IQueue<T> { #region Internal state private readonly IQueue<T> internalQueue; private readonly IQueue<T> internalRepeatingQueue; #endregion #region Constructors and destructors /// <summary> /// Initializes a new instance of the <see cref="RepeatableQueue{T}" /> class. /// </summary> public RepeatableQueue() { this.internalQueue = new Queue<T>(); this.internalRepeatingQueue = new Queue<T>(); } /// <summary> /// Initializes a new instance of the <see cref="RepeatableQueue{T}" /> class. /// </summary> /// <param name="originalQueue">The original queue.</param> public RepeatableQueue(IQueue<T> originalQueue) { Requires.NotNull( out this.internalQueue, originalQueue, nameof(originalQueue)); this.internalRepeatingQueue = new Queue<T>(); } /// <summary> /// Initializes a new instance of the <see cref="RepeatableQueue{T}" /> class. /// </summary> /// <param name="originalData">The original data.</param> public RepeatableQueue(IEnumerable<T> originalData) { Requires.NotNull( originalData, nameof(originalData)); this.internalQueue = new Queue<T>(originalData); this.internalRepeatingQueue = new Queue<T>(); } #endregion #region Properties and indexers /// <summary>Gets the number of elements in the collection.</summary> /// <returns>The number of elements in the collection. </returns> public int Count => ((IReadOnlyCollection<T>)this.internalQueue).Count; /// <summary> /// Gets a value indicating whether this queue is empty. /// </summary> /// <value> /// <c>true</c> if this queue is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty => this.Count == 0; /// <summary>Gets the number of elements contained in the <see cref="ICollection" />.</summary> /// <returns>The number of elements contained in the <see cref="ICollection" />.</returns> int ICollection.Count => this.Count; /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection" /> is synchronized /// (thread safe). /// </summary> /// <returns> /// <see langword="true" /> if access to the <see cref="ICollection" /> is synchronized (thread /// safe); otherwise, <see langword="false" />. /// </returns> bool ICollection.IsSynchronized => this.internalQueue.IsSynchronized; /// <summary>Gets an object that can be used to synchronize access to the <see cref="ICollection" />.</summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection" />.</returns> object ICollection.SyncRoot => this.internalQueue.SyncRoot; #endregion #region Methods #region Interface implementations /// <summary> /// Copies the elements of the <see cref="RepeatableQueue{T}" /> to an <see cref="Array" />, starting at /// a particular <see cref="Array" /> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array" /> that is the destination of the elements copied /// from <see cref="RepeatableQueue{T}" />. The <see cref="Array" /> must have zero-based indexing. /// </param> /// <param name="index">The zero-based index in <paramref name="array" /> at which copying begins. </param> /// <exception cref="ArgumentNullException"> /// <paramref name="array" /> is <see langword="null" />. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index" /> is less than zero. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="array" /> is multidimensional.-or- The number of elements in the source /// <see cref="RepeatableQueue{T}" /> is greater than the available space from <paramref name="index" /> to the end of /// the destination <paramref name="array" />.-or-The type of the source <see cref="RepeatableQueue{T}" /> cannot be /// cast automatically to the type of the destination <paramref name="array" />. /// </exception> public void CopyTo( Array array, int index) => this.internalQueue.CopyTo( array, index); /// <summary>Returns an enumerator that iterates through the collection.</summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "Unavoidable.")] public IEnumerator<T> GetEnumerator() => this.internalQueue.GetEnumerator(); /// <summary> /// Clears the queue of all elements. /// </summary> public void Clear() { this.internalQueue.Clear(); this.internalRepeatingQueue.Clear(); } /// <summary> /// Verifies whether or not an item is contained in the queue. /// </summary> /// <param name="item">The item to verify.</param> /// <returns><see langword="true" /> if the item is queued, <see langword="false" /> otherwise.</returns> public bool Contains(T item) => this.internalQueue.Contains(item); /// <summary> /// De-queues an item and removes it from the queue. /// </summary> /// <returns>The item that has been de-queued.</returns> public T Dequeue() { T dequeuedItem = this.internalQueue.Dequeue(); this.internalRepeatingQueue.Enqueue(dequeuedItem); return dequeuedItem; } /// <summary> /// Queues an item, adding it to the queue. /// </summary> /// <param name="item">The item to enqueue.</param> public void Enqueue(T item) => this.internalQueue.Enqueue(item); /// <summary> /// Queues a range of elements, adding them to the queue. /// </summary> /// <param name="items">The item range to push.</param> public void EnqueueRange(T[] items) => this.internalQueue.EnqueueRange(items); /// <summary> /// Queues a range of elements, adding them to the queue. /// </summary> /// <param name="items">The item range to enqueue.</param> /// <param name="startIndex">The start index.</param> /// <param name="count">The number of items to enqueue.</param> public void EnqueueRange( T[] items, int startIndex, int count) => this.internalQueue.EnqueueRange( items, startIndex, count); /// <summary> /// Peeks at the topmost element in the queue, without removing it. /// </summary> /// <returns>The item peeked at, if any.</returns> public T Peek() => this.internalQueue.Peek(); /// <summary> /// Copies all elements of the queue into a new array. /// </summary> /// <returns>The created array with all element of the queue.</returns> public T[] ToArray() => this.internalQueue.ToArray(); /// <summary> /// Trims the excess free space from within the queue, reducing the capacity to the actual number of elements. /// </summary> public void TrimExcess() => this.internalQueue.TrimExcess(); /// <summary> /// Attempts to de-queue an item and to remove it from queue. /// </summary> /// <param name="item">The item that has been de-queued, default if unsuccessful.</param> /// <returns> /// <see langword="true" /> if an item is de-queued successfully, <see langword="false" /> otherwise, or if the /// queue is empty. /// </returns> public bool TryDequeue([MaybeNullWhen(false)] out T item) { if (!this.internalQueue.TryDequeue(out item)) { return false; } this.internalRepeatingQueue.Enqueue(item); return true; } /// <summary> /// Attempts to peek at the current queue and return the item that is next in line to be dequeued. /// </summary> /// <param name="item">The item, or default if unsuccessful.</param> /// <returns> /// <see langword="true" /> if an item is found, <see langword="false" /> otherwise, or if the queue is empty. /// </returns> public bool TryPeek([MaybeNullWhen(false)] out T item) => this.internalQueue.TryPeek(out item); /// <summary>Returns an enumerator that iterates through a collection.</summary> /// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns> [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "Unavoidable.")] [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #endregion /// <summary> /// Gets a repeat of the sequence of elements dequeued from this instance. /// </summary> /// <returns>A repeating queue.</returns> public IQueue<T> Repeat() => new Queue<T>(this.internalRepeatingQueue.ToArray()); #endregion }
adimosh/IX.StandardExtensions
src/IX.StandardExtensions/System/Collections/Generic/RepeatableQueue{T}.cs
C#
mit
9,914
/** * This file does the main work of building a domTree structure from a parse * tree. The entry point is the `buildHTML` function, which takes a parse tree. * Then, the buildExpression, buildGroup, and various groupTypes functions are * called, to produce a final HTML tree. */ var Options = require("./Options"); var ParseError = require("./ParseError"); var Style = require("./Style"); var buildCommon = require("./buildCommon"); var delimiter = require("./delimiter"); var domTree = require("./domTree"); var fontMetrics = require("./fontMetrics"); var utils = require("./utils"); var makeSpan = buildCommon.makeSpan; /** * Take a list of nodes, build them in order, and return a list of the built * nodes. This function handles the `prev` node correctly, and passes the * previous element from the list as the prev of the next element. */ var buildExpression = function(expression, options, prev) { var groups = []; for (var i = 0; i < expression.length; i++) { var group = expression[i]; groups.push(buildGroup(group, options, prev)); prev = group; } return groups; }; // List of types used by getTypeOfGroup, // see https://github.com/Khan/KaTeX/wiki/Examining-TeX#group-types var groupToType = { mathord: "mord", textord: "mord", bin: "mbin", rel: "mrel", text: "mord", open: "mopen", close: "mclose", inner: "minner", genfrac: "mord", array: "mord", spacing: "mord", punct: "mpunct", ordgroup: "mord", op: "mop", katex: "mord", overline: "mord", rule: "mord", leftright: "minner", sqrt: "mord", accent: "mord" }; /** * Gets the final math type of an expression, given its group type. This type is * used to determine spacing between elements, and affects bin elements by * causing them to change depending on what types are around them. This type * must be attached to the outermost node of an element as a CSS class so that * spacing with its surrounding elements works correctly. * * Some elements can be mapped one-to-one from group type to math type, and * those are listed in the `groupToType` table. * * Others (usually elements that wrap around other elements) often have * recursive definitions, and thus call `getTypeOfGroup` on their inner * elements. */ var getTypeOfGroup = function(group) { if (group == null) { // Like when typesetting $^3$ return groupToType.mathord; } else if (group.type === "supsub") { return getTypeOfGroup(group.value.base); } else if (group.type === "llap" || group.type === "rlap") { return getTypeOfGroup(group.value); } else if (group.type === "color") { return getTypeOfGroup(group.value.value); } else if (group.type === "sizing") { return getTypeOfGroup(group.value.value); } else if (group.type === "styling") { return getTypeOfGroup(group.value.value); } else if (group.type === "delimsizing") { return groupToType[group.value.delimType]; } else { return groupToType[group.type]; } }; /** * Sometimes, groups perform special rules when they have superscripts or * subscripts attached to them. This function lets the `supsub` group know that * its inner element should handle the superscripts and subscripts instead of * handling them itself. */ var shouldHandleSupSub = function(group, options) { if (!group) { return false; } else if (group.type === "op") { // Operators handle supsubs differently when they have limits // (e.g. `\displaystyle\sum_2^3`) return group.value.limits && (options.style.size === Style.DISPLAY.size || group.value.alwaysHandleSupSub); } else if (group.type === "accent") { return isCharacterBox(group.value.base); } else { return null; } }; /** * Sometimes we want to pull out the innermost element of a group. In most * cases, this will just be the group itself, but when ordgroups and colors have * a single element, we want to pull that out. */ var getBaseElem = function(group) { if (!group) { return false; } else if (group.type === "ordgroup") { if (group.value.length === 1) { return getBaseElem(group.value[0]); } else { return group; } } else if (group.type === "color") { if (group.value.value.length === 1) { return getBaseElem(group.value.value[0]); } else { return group; } } else { return group; } }; /** * TeXbook algorithms often reference "character boxes", which are simply groups * with a single character in them. To decide if something is a character box, * we find its innermost group, and see if it is a single character. */ var isCharacterBox = function(group) { var baseElem = getBaseElem(group); // These are all they types of groups which hold single characters return baseElem.type === "mathord" || baseElem.type === "textord" || baseElem.type === "bin" || baseElem.type === "rel" || baseElem.type === "inner" || baseElem.type === "open" || baseElem.type === "close" || baseElem.type === "punct"; }; var makeNullDelimiter = function(options) { return makeSpan([ "sizing", "reset-" + options.size, "size5", options.style.reset(), Style.TEXT.cls(), "nulldelimiter" ]); }; /** * This is a map of group types to the function used to handle that type. * Simpler types come at the beginning, while complicated types come afterwards. */ var groupTypes = { mathord: function(group, options, prev) { return buildCommon.makeOrd(group, options, "mathord"); }, textord: function(group, options, prev) { return buildCommon.makeOrd(group, options, "textord"); }, bin: function(group, options, prev) { var className = "mbin"; // Pull out the most recent element. Do some special handling to find // things at the end of a \color group. Note that we don't use the same // logic for ordgroups (which count as ords). var prevAtom = prev; while (prevAtom && prevAtom.type === "color") { var atoms = prevAtom.value.value; prevAtom = atoms[atoms.length - 1]; } // See TeXbook pg. 442-446, Rules 5 and 6, and the text before Rule 19. // Here, we determine whether the bin should turn into an ord. We // currently only apply Rule 5. if (!prev || utils.contains(["mbin", "mopen", "mrel", "mop", "mpunct"], getTypeOfGroup(prevAtom))) { group.type = "textord"; className = "mord"; } return buildCommon.mathsym( group.value, group.mode, options.getColor(), [className]); }, rel: function(group, options, prev) { return buildCommon.mathsym( group.value, group.mode, options.getColor(), ["mrel"]); }, open: function(group, options, prev) { return buildCommon.mathsym( group.value, group.mode, options.getColor(), ["mopen"]); }, close: function(group, options, prev) { return buildCommon.mathsym( group.value, group.mode, options.getColor(), ["mclose"]); }, inner: function(group, options, prev) { return buildCommon.mathsym( group.value, group.mode, options.getColor(), ["minner"]); }, punct: function(group, options, prev) { return buildCommon.mathsym( group.value, group.mode, options.getColor(), ["mpunct"]); }, ordgroup: function(group, options, prev) { return makeSpan( ["mord", options.style.cls()], buildExpression(group.value, options.reset()) ); }, text: function(group, options, prev) { return makeSpan(["text", "mord", options.style.cls()], buildExpression(group.value.body, options.reset())); }, color: function(group, options, prev) { var elements = buildExpression( group.value.value, options.withColor(group.value.color), prev ); // \color isn't supposed to affect the type of the elements it contains. // To accomplish this, we wrap the results in a fragment, so the inner // elements will be able to directly interact with their neighbors. For // example, `\color{red}{2 +} 3` has the same spacing as `2 + 3` return new buildCommon.makeFragment(elements); }, supsub: function(group, options, prev) { // Superscript and subscripts are handled in the TeXbook on page // 445-446, rules 18(a-f). // Here is where we defer to the inner group if it should handle // superscripts and subscripts itself. if (shouldHandleSupSub(group.value.base, options)) { return groupTypes[group.value.base.type](group, options, prev); } var base = buildGroup(group.value.base, options.reset()); var supmid, submid, sup, sub; if (group.value.sup) { sup = buildGroup(group.value.sup, options.withStyle(options.style.sup())); supmid = makeSpan( [options.style.reset(), options.style.sup().cls()], [sup]); } if (group.value.sub) { sub = buildGroup(group.value.sub, options.withStyle(options.style.sub())); submid = makeSpan( [options.style.reset(), options.style.sub().cls()], [sub]); } // Rule 18a var supShift, subShift; if (isCharacterBox(group.value.base)) { supShift = 0; subShift = 0; } else { supShift = base.height - fontMetrics.metrics.supDrop; subShift = base.depth + fontMetrics.metrics.subDrop; } // Rule 18c var minSupShift; if (options.style === Style.DISPLAY) { minSupShift = fontMetrics.metrics.sup1; } else if (options.style.cramped) { minSupShift = fontMetrics.metrics.sup3; } else { minSupShift = fontMetrics.metrics.sup2; } // scriptspace is a font-size-independent size, so scale it // appropriately var multiplier = Style.TEXT.sizeMultiplier * options.style.sizeMultiplier; var scriptspace = (0.5 / fontMetrics.metrics.ptPerEm) / multiplier + "em"; var supsub; if (!group.value.sup) { // Rule 18b subShift = Math.max( subShift, fontMetrics.metrics.sub1, sub.height - 0.8 * fontMetrics.metrics.xHeight); supsub = buildCommon.makeVList([ {type: "elem", elem: submid} ], "shift", subShift, options); supsub.children[0].style.marginRight = scriptspace; // Subscripts shouldn't be shifted by the base's italic correction. // Account for that by shifting the subscript back the appropriate // amount. Note we only do this when the base is a single symbol. if (base instanceof domTree.symbolNode) { supsub.children[0].style.marginLeft = -base.italic + "em"; } } else if (!group.value.sub) { // Rule 18c, d supShift = Math.max(supShift, minSupShift, sup.depth + 0.25 * fontMetrics.metrics.xHeight); supsub = buildCommon.makeVList([ {type: "elem", elem: supmid} ], "shift", -supShift, options); supsub.children[0].style.marginRight = scriptspace; } else { supShift = Math.max( supShift, minSupShift, sup.depth + 0.25 * fontMetrics.metrics.xHeight); subShift = Math.max(subShift, fontMetrics.metrics.sub2); var ruleWidth = fontMetrics.metrics.defaultRuleThickness; // Rule 18e if ((supShift - sup.depth) - (sub.height - subShift) < 4 * ruleWidth) { subShift = 4 * ruleWidth - (supShift - sup.depth) + sub.height; var psi = 0.8 * fontMetrics.metrics.xHeight - (supShift - sup.depth); if (psi > 0) { supShift += psi; subShift -= psi; } } supsub = buildCommon.makeVList([ {type: "elem", elem: submid, shift: subShift}, {type: "elem", elem: supmid, shift: -supShift} ], "individualShift", null, options); // See comment above about subscripts not being shifted if (base instanceof domTree.symbolNode) { supsub.children[0].style.marginLeft = -base.italic + "em"; } supsub.children[0].style.marginRight = scriptspace; supsub.children[1].style.marginRight = scriptspace; } return makeSpan([getTypeOfGroup(group.value.base)], [base, supsub]); }, genfrac: function(group, options, prev) { // Fractions are handled in the TeXbook on pages 444-445, rules 15(a-e). // Figure out what style this fraction should be in based on the // function used var fstyle = options.style; if (group.value.size === "display") { fstyle = Style.DISPLAY; } else if (group.value.size === "text") { fstyle = Style.TEXT; } var nstyle = fstyle.fracNum(); var dstyle = fstyle.fracDen(); var numer = buildGroup(group.value.numer, options.withStyle(nstyle)); var numerreset = makeSpan([fstyle.reset(), nstyle.cls()], [numer]); var denom = buildGroup(group.value.denom, options.withStyle(dstyle)); var denomreset = makeSpan([fstyle.reset(), dstyle.cls()], [denom]); var ruleWidth; if (group.value.hasBarLine) { ruleWidth = fontMetrics.metrics.defaultRuleThickness / options.style.sizeMultiplier; } else { ruleWidth = 0; } // Rule 15b var numShift; var clearance; var denomShift; if (fstyle.size === Style.DISPLAY.size) { numShift = fontMetrics.metrics.num1; if (ruleWidth > 0) { clearance = 3 * ruleWidth; } else { clearance = 7 * fontMetrics.metrics.defaultRuleThickness; } denomShift = fontMetrics.metrics.denom1; } else { if (ruleWidth > 0) { numShift = fontMetrics.metrics.num2; clearance = ruleWidth; } else { numShift = fontMetrics.metrics.num3; clearance = 3 * fontMetrics.metrics.defaultRuleThickness; } denomShift = fontMetrics.metrics.denom2; } var frac; if (ruleWidth === 0) { // Rule 15c var candiateClearance = (numShift - numer.depth) - (denom.height - denomShift); if (candiateClearance < clearance) { numShift += 0.5 * (clearance - candiateClearance); denomShift += 0.5 * (clearance - candiateClearance); } frac = buildCommon.makeVList([ {type: "elem", elem: denomreset, shift: denomShift}, {type: "elem", elem: numerreset, shift: -numShift} ], "individualShift", null, options); } else { // Rule 15d var axisHeight = fontMetrics.metrics.axisHeight; if ((numShift - numer.depth) - (axisHeight + 0.5 * ruleWidth) < clearance) { numShift += clearance - ((numShift - numer.depth) - (axisHeight + 0.5 * ruleWidth)); } if ((axisHeight - 0.5 * ruleWidth) - (denom.height - denomShift) < clearance) { denomShift += clearance - ((axisHeight - 0.5 * ruleWidth) - (denom.height - denomShift)); } var mid = makeSpan( [options.style.reset(), Style.TEXT.cls(), "frac-line"]); // Manually set the height of the line because its height is // created in CSS mid.height = ruleWidth; var midShift = -(axisHeight - 0.5 * ruleWidth); frac = buildCommon.makeVList([ {type: "elem", elem: denomreset, shift: denomShift}, {type: "elem", elem: mid, shift: midShift}, {type: "elem", elem: numerreset, shift: -numShift} ], "individualShift", null, options); } // Since we manually change the style sometimes (with \dfrac or \tfrac), // account for the possible size change here. frac.height *= fstyle.sizeMultiplier / options.style.sizeMultiplier; frac.depth *= fstyle.sizeMultiplier / options.style.sizeMultiplier; // Rule 15e var delimSize; if (fstyle.size === Style.DISPLAY.size) { delimSize = fontMetrics.metrics.delim1; } else { delimSize = fontMetrics.metrics.getDelim2(fstyle); } var leftDelim, rightDelim; if (group.value.leftDelim == null) { leftDelim = makeNullDelimiter(options); } else { leftDelim = delimiter.customSizedDelim( group.value.leftDelim, delimSize, true, options.withStyle(fstyle), group.mode); } if (group.value.rightDelim == null) { rightDelim = makeNullDelimiter(options); } else { rightDelim = delimiter.customSizedDelim( group.value.rightDelim, delimSize, true, options.withStyle(fstyle), group.mode); } return makeSpan( ["mord", options.style.reset(), fstyle.cls()], [leftDelim, makeSpan(["mfrac"], [frac]), rightDelim], options.getColor()); }, array: function(group, options, prev) { var r, c; var nr = group.value.body.length; var nc = 0; var body = new Array(nr); // Horizontal spacing var pt = 1 / fontMetrics.metrics.ptPerEm; var arraycolsep = 5 * pt; // \arraycolsep in article.cls // Vertical spacing var baselineskip = 12 * pt; // see size10.clo // Default \arraystretch from lttab.dtx // TODO(gagern): may get redefined once we have user-defined macros var arraystretch = utils.deflt(group.value.arraystretch, 1); var arrayskip = arraystretch * baselineskip; var arstrutHeight = 0.7 * arrayskip; // \strutbox in ltfsstrc.dtx and var arstrutDepth = 0.3 * arrayskip; // \@arstrutbox in lttab.dtx var totalHeight = 0; for (r = 0; r < group.value.body.length; ++r) { var inrow = group.value.body[r]; var height = arstrutHeight; // \@array adds an \@arstrut var depth = arstrutDepth; // to each tow (via the template) if (nc < inrow.length) { nc = inrow.length; } var outrow = new Array(inrow.length); for (c = 0; c < inrow.length; ++c) { var elt = buildGroup(inrow[c], options); if (depth < elt.depth) { depth = elt.depth; } if (height < elt.height) { height = elt.height; } outrow[c] = elt; } var gap = 0; if (group.value.rowGaps[r]) { gap = group.value.rowGaps[r].value; switch (gap.unit) { case "em": gap = gap.number; break; case "ex": gap = gap.number * fontMetrics.metrics.emPerEx; break; default: console.error("Can't handle unit " + gap.unit); gap = 0; } if (gap > 0) { // \@argarraycr gap += arstrutDepth; if (depth < gap) { depth = gap; // \@xargarraycr } gap = 0; } } outrow.height = height; outrow.depth = depth; totalHeight += height; outrow.pos = totalHeight; totalHeight += depth + gap; // \@yargarraycr body[r] = outrow; } var offset = totalHeight / 2 + fontMetrics.metrics.axisHeight; var coldescriptions = group.value.cols || []; var cols = []; var colsep; for (c = 0; c < nc; ++c) { var coldescr = coldescriptions[c] || {}; var sepwidth; if (c > 0 || group.value.hskipBeforeAndAfter) { sepwidth = utils.deflt(coldescr.pregap, arraycolsep); if (sepwidth !== 0) { colsep = makeSpan(["arraycolsep"], []); colsep.style.width = sepwidth + "em"; cols.push(colsep); } } var col = []; for (r = 0; r < nr; ++r) { var row = body[r]; var elem = row[c]; if (!elem) { continue; } var shift = row.pos - offset; elem.depth = row.depth; elem.height = row.height; col.push({type: "elem", elem: elem, shift: shift}); } col = buildCommon.makeVList(col, "individualShift", null, options); col = makeSpan( ["col-align-" + (coldescr.align || "c")], [col]); cols.push(col); if (c < nc - 1 || group.value.hskipBeforeAndAfter) { sepwidth = utils.deflt(coldescr.postgap, arraycolsep); if (sepwidth !== 0) { colsep = makeSpan(["arraycolsep"], []); colsep.style.width = sepwidth + "em"; cols.push(colsep); } } } body = makeSpan(["mtable"], cols); return makeSpan(["mord"], [body], options.getColor()); }, spacing: function(group, options, prev) { if (group.value === "\\ " || group.value === "\\space" || group.value === " " || group.value === "~") { // Spaces are generated by adding an actual space. Each of these // things has an entry in the symbols table, so these will be turned // into appropriate outputs. return makeSpan( ["mord", "mspace"], [buildCommon.mathsym(group.value, group.mode)] ); } else { // Other kinds of spaces are of arbitrary width. We use CSS to // generate these. return makeSpan( ["mord", "mspace", buildCommon.spacingFunctions[group.value].className]); } }, llap: function(group, options, prev) { var inner = makeSpan( ["inner"], [buildGroup(group.value.body, options.reset())]); var fix = makeSpan(["fix"], []); return makeSpan( ["llap", options.style.cls()], [inner, fix]); }, rlap: function(group, options, prev) { var inner = makeSpan( ["inner"], [buildGroup(group.value.body, options.reset())]); var fix = makeSpan(["fix"], []); return makeSpan( ["rlap", options.style.cls()], [inner, fix]); }, op: function(group, options, prev) { // Operators are handled in the TeXbook pg. 443-444, rule 13(a). var supGroup; var subGroup; var hasLimits = false; if (group.type === "supsub" ) { // If we have limits, supsub will pass us its group to handle. Pull // out the superscript and subscript and set the group to the op in // its base. supGroup = group.value.sup; subGroup = group.value.sub; group = group.value.base; hasLimits = true; } // Most operators have a large successor symbol, but these don't. var noSuccessor = [ "\\smallint" ]; var large = false; if (options.style.size === Style.DISPLAY.size && group.value.symbol && !utils.contains(noSuccessor, group.value.body)) { // Most symbol operators get larger in displaystyle (rule 13) large = true; } var base; var baseShift = 0; var slant = 0; if (group.value.symbol) { // If this is a symbol, create the symbol. var style = large ? "Size2-Regular" : "Size1-Regular"; base = buildCommon.makeSymbol( group.value.body, style, "math", options.getColor(), ["op-symbol", large ? "large-op" : "small-op", "mop"]); // Shift the symbol so its center lies on the axis (rule 13). It // appears that our fonts have the centers of the symbols already // almost on the axis, so these numbers are very small. Note we // don't actually apply this here, but instead it is used either in // the vlist creation or separately when there are no limits. baseShift = (base.height - base.depth) / 2 - fontMetrics.metrics.axisHeight * options.style.sizeMultiplier; // The slant of the symbol is just its italic correction. slant = base.italic; } else { // Otherwise, this is a text operator. Build the text from the // operator's name. // TODO(emily): Add a space in the middle of some of these // operators, like \limsup var output = []; for (var i = 1; i < group.value.body.length; i++) { output.push(buildCommon.mathsym(group.value.body[i], group.mode)); } base = makeSpan(["mop"], output, options.getColor()); } if (hasLimits) { // IE 8 clips \int if it is in a display: inline-block. We wrap it // in a new span so it is an inline, and works. base = makeSpan([], [base]); var supmid, supKern, submid, subKern; // We manually have to handle the superscripts and subscripts. This, // aside from the kern calculations, is copied from supsub. if (supGroup) { var sup = buildGroup( supGroup, options.withStyle(options.style.sup())); supmid = makeSpan( [options.style.reset(), options.style.sup().cls()], [sup]); supKern = Math.max( fontMetrics.metrics.bigOpSpacing1, fontMetrics.metrics.bigOpSpacing3 - sup.depth); } if (subGroup) { var sub = buildGroup( subGroup, options.withStyle(options.style.sub())); submid = makeSpan( [options.style.reset(), options.style.sub().cls()], [sub]); subKern = Math.max( fontMetrics.metrics.bigOpSpacing2, fontMetrics.metrics.bigOpSpacing4 - sub.height); } // Build the final group as a vlist of the possible subscript, base, // and possible superscript. var finalGroup, top, bottom; if (!supGroup) { top = base.height - baseShift; finalGroup = buildCommon.makeVList([ {type: "kern", size: fontMetrics.metrics.bigOpSpacing5}, {type: "elem", elem: submid}, {type: "kern", size: subKern}, {type: "elem", elem: base} ], "top", top, options); // Here, we shift the limits by the slant of the symbol. Note // that we are supposed to shift the limits by 1/2 of the slant, // but since we are centering the limits adding a full slant of // margin will shift by 1/2 that. finalGroup.children[0].style.marginLeft = -slant + "em"; } else if (!subGroup) { bottom = base.depth + baseShift; finalGroup = buildCommon.makeVList([ {type: "elem", elem: base}, {type: "kern", size: supKern}, {type: "elem", elem: supmid}, {type: "kern", size: fontMetrics.metrics.bigOpSpacing5} ], "bottom", bottom, options); // See comment above about slants finalGroup.children[1].style.marginLeft = slant + "em"; } else if (!supGroup && !subGroup) { // This case probably shouldn't occur (this would mean the // supsub was sending us a group with no superscript or // subscript) but be safe. return base; } else { bottom = fontMetrics.metrics.bigOpSpacing5 + submid.height + submid.depth + subKern + base.depth + baseShift; finalGroup = buildCommon.makeVList([ {type: "kern", size: fontMetrics.metrics.bigOpSpacing5}, {type: "elem", elem: submid}, {type: "kern", size: subKern}, {type: "elem", elem: base}, {type: "kern", size: supKern}, {type: "elem", elem: supmid}, {type: "kern", size: fontMetrics.metrics.bigOpSpacing5} ], "bottom", bottom, options); // See comment above about slants finalGroup.children[0].style.marginLeft = -slant + "em"; finalGroup.children[2].style.marginLeft = slant + "em"; } return makeSpan(["mop", "op-limits"], [finalGroup]); } else { if (group.value.symbol) { base.style.top = baseShift + "em"; } return base; } }, katex: function(group, options, prev) { // The KaTeX logo. The offsets for the K and a were chosen to look // good, but the offsets for the T, E, and X were taken from the // definition of \TeX in TeX (see TeXbook pg. 356) var k = makeSpan( ["k"], [buildCommon.mathsym("K", group.mode)]); var a = makeSpan( ["a"], [buildCommon.mathsym("A", group.mode)]); a.height = (a.height + 0.2) * 0.75; a.depth = (a.height - 0.2) * 0.75; var t = makeSpan( ["t"], [buildCommon.mathsym("T", group.mode)]); var e = makeSpan( ["e"], [buildCommon.mathsym("E", group.mode)]); e.height = (e.height - 0.2155); e.depth = (e.depth + 0.2155); var x = makeSpan( ["x"], [buildCommon.mathsym("X", group.mode)]); return makeSpan( ["katex-logo", "mord"], [k, a, t, e, x], options.getColor()); }, overline: function(group, options, prev) { // Overlines are handled in the TeXbook pg 443, Rule 9. // Build the inner group in the cramped style. var innerGroup = buildGroup(group.value.body, options.withStyle(options.style.cramp())); var ruleWidth = fontMetrics.metrics.defaultRuleThickness / options.style.sizeMultiplier; // Create the line above the body var line = makeSpan( [options.style.reset(), Style.TEXT.cls(), "overline-line"]); line.height = ruleWidth; line.maxFontSize = 1.0; // Generate the vlist, with the appropriate kerns var vlist = buildCommon.makeVList([ {type: "elem", elem: innerGroup}, {type: "kern", size: 3 * ruleWidth}, {type: "elem", elem: line}, {type: "kern", size: ruleWidth} ], "firstBaseline", null, options); return makeSpan(["overline", "mord"], [vlist], options.getColor()); }, sqrt: function(group, options, prev) { // Square roots are handled in the TeXbook pg. 443, Rule 11. // First, we do the same steps as in overline to build the inner group // and line var inner = buildGroup(group.value.body, options.withStyle(options.style.cramp())); var ruleWidth = fontMetrics.metrics.defaultRuleThickness / options.style.sizeMultiplier; var line = makeSpan( [options.style.reset(), Style.TEXT.cls(), "sqrt-line"], [], options.getColor()); line.height = ruleWidth; line.maxFontSize = 1.0; var phi = ruleWidth; if (options.style.id < Style.TEXT.id) { phi = fontMetrics.metrics.xHeight; } // Calculate the clearance between the body and line var lineClearance = ruleWidth + phi / 4; var innerHeight = (inner.height + inner.depth) * options.style.sizeMultiplier; var minDelimiterHeight = innerHeight + lineClearance + ruleWidth; // Create a \surd delimiter of the required minimum size var delim = makeSpan(["sqrt-sign"], [ delimiter.customSizedDelim("\\surd", minDelimiterHeight, false, options, group.mode)], options.getColor()); var delimDepth = (delim.height + delim.depth) - ruleWidth; // Adjust the clearance based on the delimiter size if (delimDepth > inner.height + inner.depth + lineClearance) { lineClearance = (lineClearance + delimDepth - inner.height - inner.depth) / 2; } // Shift the delimiter so that its top lines up with the top of the line var delimShift = -(inner.height + lineClearance + ruleWidth) + delim.height; delim.style.top = delimShift + "em"; delim.height -= delimShift; delim.depth += delimShift; // We add a special case here, because even when `inner` is empty, we // still get a line. So, we use a simple heuristic to decide if we // should omit the body entirely. (note this doesn't work for something // like `\sqrt{\rlap{x}}`, but if someone is doing that they deserve for // it not to work. var body; if (inner.height === 0 && inner.depth === 0) { body = makeSpan(); } else { body = buildCommon.makeVList([ {type: "elem", elem: inner}, {type: "kern", size: lineClearance}, {type: "elem", elem: line}, {type: "kern", size: ruleWidth} ], "firstBaseline", null, options); } if (!group.value.index) { return makeSpan(["sqrt", "mord"], [delim, body]); } else { // Handle the optional root index // The index is always in scriptscript style var root = buildGroup( group.value.index, options.withStyle(Style.SCRIPTSCRIPT)); var rootWrap = makeSpan( [options.style.reset(), Style.SCRIPTSCRIPT.cls()], [root]); // Figure out the height and depth of the inner part var innerRootHeight = Math.max(delim.height, body.height); var innerRootDepth = Math.max(delim.depth, body.depth); // The amount the index is shifted by. This is taken from the TeX // source, in the definition of `\r@@t`. var toShift = 0.6 * (innerRootHeight - innerRootDepth); // Build a VList with the superscript shifted up correctly var rootVList = buildCommon.makeVList( [{type: "elem", elem: rootWrap}], "shift", -toShift, options); // Add a class surrounding it so we can add on the appropriate // kerning var rootVListWrap = makeSpan(["root"], [rootVList]); return makeSpan(["sqrt", "mord"], [rootVListWrap, delim, body]); } }, sizing: function(group, options, prev) { // Handle sizing operators like \Huge. Real TeX doesn't actually allow // these functions inside of math expressions, so we do some special // handling. var inner = buildExpression(group.value.value, options.withSize(group.value.size), prev); var span = makeSpan(["mord"], [makeSpan(["sizing", "reset-" + options.size, group.value.size, options.style.cls()], inner)]); // Calculate the correct maxFontSize manually var fontSize = buildCommon.sizingMultiplier[group.value.size]; span.maxFontSize = fontSize * options.style.sizeMultiplier; return span; }, styling: function(group, options, prev) { // Style changes are handled in the TeXbook on pg. 442, Rule 3. // Figure out what style we're changing to. var style = { "display": Style.DISPLAY, "text": Style.TEXT, "script": Style.SCRIPT, "scriptscript": Style.SCRIPTSCRIPT }; var newStyle = style[group.value.style]; // Build the inner expression in the new style. var inner = buildExpression( group.value.value, options.withStyle(newStyle), prev); return makeSpan([options.style.reset(), newStyle.cls()], inner); }, font: function(group, options, prev) { var font = group.value.font; return buildGroup(group.value.body, options.withFont(font), prev); }, delimsizing: function(group, options, prev) { var delim = group.value.value; if (delim === ".") { // Empty delimiters still count as elements, even though they don't // show anything. return makeSpan([groupToType[group.value.delimType]]); } // Use delimiter.sizedDelim to generate the delimiter. return makeSpan( [groupToType[group.value.delimType]], [delimiter.sizedDelim( delim, group.value.size, options, group.mode)]); }, leftright: function(group, options, prev) { // Build the inner expression var inner = buildExpression(group.value.body, options.reset()); var innerHeight = 0; var innerDepth = 0; // Calculate its height and depth for (var i = 0; i < inner.length; i++) { innerHeight = Math.max(inner[i].height, innerHeight); innerDepth = Math.max(inner[i].depth, innerDepth); } // The size of delimiters is the same, regardless of what style we are // in. Thus, to correctly calculate the size of delimiter we need around // a group, we scale down the inner size based on the size. innerHeight *= options.style.sizeMultiplier; innerDepth *= options.style.sizeMultiplier; var leftDelim; if (group.value.left === ".") { // Empty delimiters in \left and \right make null delimiter spaces. leftDelim = makeNullDelimiter(options); } else { // Otherwise, use leftRightDelim to generate the correct sized // delimiter. leftDelim = delimiter.leftRightDelim( group.value.left, innerHeight, innerDepth, options, group.mode); } // Add it to the beginning of the expression inner.unshift(leftDelim); var rightDelim; // Same for the right delimiter if (group.value.right === ".") { rightDelim = makeNullDelimiter(options); } else { rightDelim = delimiter.leftRightDelim( group.value.right, innerHeight, innerDepth, options, group.mode); } // Add it to the end of the expression. inner.push(rightDelim); return makeSpan( ["minner", options.style.cls()], inner, options.getColor()); }, rule: function(group, options, prev) { // Make an empty span for the rule var rule = makeSpan(["mord", "rule"], [], options.getColor()); // Calculate the shift, width, and height of the rule, and account for units var shift = 0; if (group.value.shift) { shift = group.value.shift.number; if (group.value.shift.unit === "ex") { shift *= fontMetrics.metrics.xHeight; } } var width = group.value.width.number; if (group.value.width.unit === "ex") { width *= fontMetrics.metrics.xHeight; } var height = group.value.height.number; if (group.value.height.unit === "ex") { height *= fontMetrics.metrics.xHeight; } // The sizes of rules are absolute, so make it larger if we are in a // smaller style. shift /= options.style.sizeMultiplier; width /= options.style.sizeMultiplier; height /= options.style.sizeMultiplier; // Style the rule to the right size rule.style.borderRightWidth = width + "em"; rule.style.borderTopWidth = height + "em"; rule.style.bottom = shift + "em"; // Record the height and width rule.width = width; rule.height = height + shift; rule.depth = -shift; return rule; }, accent: function(group, options, prev) { // Accents are handled in the TeXbook pg. 443, rule 12. var base = group.value.base; var supsubGroup; if (group.type === "supsub") { // If our base is a character box, and we have superscripts and // subscripts, the supsub will defer to us. In particular, we want // to attach the superscripts and subscripts to the inner body (so // that the position of the superscripts and subscripts won't be // affected by the height of the accent). We accomplish this by // sticking the base of the accent into the base of the supsub, and // rendering that, while keeping track of where the accent is. // The supsub group is the group that was passed in var supsub = group; // The real accent group is the base of the supsub group group = supsub.value.base; // The character box is the base of the accent group base = group.value.base; // Stick the character box into the base of the supsub group supsub.value.base = base; // Rerender the supsub group with its new base, and store that // result. supsubGroup = buildGroup( supsub, options.reset(), prev); } // Build the base group var body = buildGroup( base, options.withStyle(options.style.cramp())); // Calculate the skew of the accent. This is based on the line "If the // nucleus is not a single character, let s = 0; otherwise set s to the // kern amount for the nucleus followed by the \skewchar of its font." // Note that our skew metrics are just the kern between each character // and the skewchar. var skew; if (isCharacterBox(base)) { // If the base is a character box, then we want the skew of the // innermost character. To do that, we find the innermost character: var baseChar = getBaseElem(base); // Then, we render its group to get the symbol inside it var baseGroup = buildGroup( baseChar, options.withStyle(options.style.cramp())); // Finally, we pull the skew off of the symbol. skew = baseGroup.skew; // Note that we now throw away baseGroup, because the layers we // removed with getBaseElem might contain things like \color which // we can't get rid of. // TODO(emily): Find a better way to get the skew } else { skew = 0; } // calculate the amount of space between the body and the accent var clearance = Math.min(body.height, fontMetrics.metrics.xHeight); // Build the accent var accent = buildCommon.makeSymbol( group.value.accent, "Main-Regular", "math", options.getColor()); // Remove the italic correction of the accent, because it only serves to // shift the accent over to a place we don't want. accent.italic = 0; // The \vec character that the fonts use is a combining character, and // thus shows up much too far to the left. To account for this, we add a // specific class which shifts the accent over to where we want it. // TODO(emily): Fix this in a better way, like by changing the font var vecClass = group.value.accent === "\\vec" ? "accent-vec" : null; var accentBody = makeSpan(["accent-body", vecClass], [ makeSpan([], [accent])]); accentBody = buildCommon.makeVList([ {type: "elem", elem: body}, {type: "kern", size: -clearance}, {type: "elem", elem: accentBody} ], "firstBaseline", null, options); // Shift the accent over by the skew. Note we shift by twice the skew // because we are centering the accent, so by adding 2*skew to the left, // we shift it to the right by 1*skew. accentBody.children[1].style.marginLeft = 2 * skew + "em"; var accentWrap = makeSpan(["mord", "accent"], [accentBody]); if (supsubGroup) { // Here, we replace the "base" child of the supsub with our newly // generated accent. supsubGroup.children[0] = accentWrap; // Since we don't rerun the height calculation after replacing the // accent, we manually recalculate height. supsubGroup.height = Math.max(accentWrap.height, supsubGroup.height); // Accents should always be ords, even when their innards are not. supsubGroup.classes[0] = "mord"; return supsubGroup; } else { return accentWrap; } }, phantom: function(group, options, prev) { var elements = buildExpression( group.value.value, options.withPhantom(), prev ); // \phantom isn't supposed to affect the elements it contains. // See "color" for more details. return new buildCommon.makeFragment(elements); } }; /** * buildGroup is the function that takes a group and calls the correct groupType * function for it. It also handles the interaction of size and style changes * between parents and children. */ var buildGroup = function(group, options, prev) { if (!group) { return makeSpan(); } if (groupTypes[group.type]) { // Call the groupTypes function var groupNode = groupTypes[group.type](group, options, prev); var multiplier; // If the style changed between the parent and the current group, // account for the size difference if (options.style !== options.parentStyle) { multiplier = options.style.sizeMultiplier / options.parentStyle.sizeMultiplier; groupNode.height *= multiplier; groupNode.depth *= multiplier; } // If the size changed between the parent and the current group, account // for that size difference. if (options.size !== options.parentSize) { multiplier = buildCommon.sizingMultiplier[options.size] / buildCommon.sizingMultiplier[options.parentSize]; groupNode.height *= multiplier; groupNode.depth *= multiplier; } return groupNode; } else { throw new ParseError( "Got group of unknown type: '" + group.type + "'"); } }; /** * Take an entire parse tree, and build it into an appropriate set of HTML * nodes. */ var buildHTML = function(tree, settings) { // buildExpression is destructive, so we need to make a clone // of the incoming tree so that it isn't accidentally changed tree = JSON.parse(JSON.stringify(tree)); var startStyle = Style.TEXT; if (settings.displayMode) { startStyle = Style.DISPLAY; } // Setup the default options var options = new Options({ style: startStyle, size: "size5" }); // Build the expression contained in the tree var expression = buildExpression(tree, options); var body = makeSpan(["base", options.style.cls()], expression); // Add struts, which ensure that the top of the HTML element falls at the // height of the expression, and the bottom of the HTML element falls at the // depth of the expression. var topStrut = makeSpan(["strut"]); var bottomStrut = makeSpan(["strut", "bottom"]); topStrut.style.height = body.height + "em"; bottomStrut.style.height = (body.height + body.depth) + "em"; // We'd like to use `vertical-align: top` but in IE 9 this lowers the // baseline of the box to the bottom of this strut (instead staying in the // normal place) so we use an absolute value for vertical-align instead bottomStrut.style.verticalAlign = -body.depth + "em"; // Wrap the struts and body together var htmlNode = makeSpan(["katex-html"], [topStrut, bottomStrut, body]); htmlNode.setAttribute("aria-hidden", "true"); return htmlNode; }; module.exports = buildHTML;
zhanghuiguoanlige/KaTeX
src/buildHTML.js
JavaScript
mit
50,238
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; namespace BioInfo.Web.ExternalWeb.Models { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } public class ManageLoginsViewModel { public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationDescription> OtherLogins { get; set; } } public class FactorViewModel { public string Purpose { get; set; } } public class SetPasswordViewModel { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "Phone Number")] public string Number { get; set; } } public class VerifyPhoneNumberViewModel { [Required] [Display(Name = "Code")] public string Code { get; set; } [Required] [Phone] [Display(Name = "Phone Number")] public string PhoneNumber { get; set; } } public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } } }
drcrook1/BioInformatics
Web/ExternalWeb/Models/ManageViewModels.cs
C#
mit
2,669
/** ****************************************************************************** * @file stm32l4xx_hal_crc.c * @author MCD Application Team * @brief CRC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the CRC peripheral: * + Initialization and de-initialization functions * + Peripheral Control functions * + Peripheral State functions * @verbatim =============================================================================== ##### How to use this driver ##### =============================================================================== [..] (+) Enable CRC AHB clock using __HAL_RCC_CRC_CLK_ENABLE(); (+) Initialize CRC calculator (++) specify generating polynomial (IP default or non-default one) (++) specify initialization value (IP default or non-default one) (++) specify input data format (++) specify input or output data inversion mode if any (+) Use HAL_CRC_Accumulate() function to compute the CRC value of the input data buffer starting with the previously computed CRC as initialization value (+) Use HAL_CRC_Calculate() function to compute the CRC value of the input data buffer starting with the defined initialization value (default or non-default) to initiate CRC calculation @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32l4xx_hal.h" /** @addtogroup STM32L4xx_HAL_Driver * @{ */ /** @defgroup CRC CRC * @brief CRC HAL module driver. * @{ */ #ifdef HAL_CRC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @defgroup CRC_Private_Functions CRC Private Functions * @{ */ static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength); static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup CRC_Exported_Functions CRC Exported Functions * @{ */ /** @defgroup CRC_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions. * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Initialize the CRC according to the specified parameters in the CRC_InitTypeDef and create the associated handle (+) DeInitialize the CRC peripheral (+) Initialize the CRC MSP (MCU Specific Package) (+) DeInitialize the CRC MSP @endverbatim * @{ */ /** * @brief Initialize the CRC according to the specified * parameters in the CRC_InitTypeDef and create the associated handle. * @param hcrc: CRC handle * @retval HAL status */ HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc) { /* Check the CRC handle allocation */ if(hcrc == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance)); if(hcrc->State == HAL_CRC_STATE_RESET) { /* Allocate lock resource and initialize it */ hcrc->Lock = HAL_UNLOCKED; /* Init the low level hardware */ HAL_CRC_MspInit(hcrc); } hcrc->State = HAL_CRC_STATE_BUSY; /* check whether or not non-default generating polynomial has been * picked up by user */ assert_param(IS_DEFAULT_POLYNOMIAL(hcrc->Init.DefaultPolynomialUse)); if (hcrc->Init.DefaultPolynomialUse == DEFAULT_POLYNOMIAL_ENABLE) { /* initialize IP with default generating polynomial */ WRITE_REG(hcrc->Instance->POL, DEFAULT_CRC32_POLY); MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, CRC_POLYLENGTH_32B); } else { /* initialize CRC IP with generating polynomial defined by user */ if (HAL_CRCEx_Polynomial_Set(hcrc, hcrc->Init.GeneratingPolynomial, hcrc->Init.CRCLength) != HAL_OK) { return HAL_ERROR; } } /* check whether or not non-default CRC initial value has been * picked up by user */ assert_param(IS_DEFAULT_INIT_VALUE(hcrc->Init.DefaultInitValueUse)); if (hcrc->Init.DefaultInitValueUse == DEFAULT_INIT_VALUE_ENABLE) { WRITE_REG(hcrc->Instance->INIT, DEFAULT_CRC_INITVALUE); } else { WRITE_REG(hcrc->Instance->INIT, hcrc->Init.InitValue); } /* set input data inversion mode */ assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(hcrc->Init.InputDataInversionMode)); MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, hcrc->Init.InputDataInversionMode); /* set output data inversion mode */ assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(hcrc->Init.OutputDataInversionMode)); MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, hcrc->Init.OutputDataInversionMode); /* makes sure the input data format (bytes, halfwords or words stream) * is properly specified by user */ assert_param(IS_CRC_INPUTDATA_FORMAT(hcrc->InputDataFormat)); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief DeInitialize the CRC peripheral. * @param hcrc: CRC handle * @retval HAL status */ HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc) { /* Check the CRC handle allocation */ if(hcrc == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance)); /* Check the CRC peripheral state */ if(hcrc->State == HAL_CRC_STATE_BUSY) { return HAL_BUSY; } /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; /* Reset CRC calculation unit */ __HAL_CRC_DR_RESET(hcrc); /* Reset IDR register content */ CLEAR_BIT(hcrc->Instance->IDR, CRC_IDR_IDR) ; /* DeInit the low level hardware */ HAL_CRC_MspDeInit(hcrc); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_RESET; /* Process unlocked */ __HAL_UNLOCK(hcrc); /* Return function status */ return HAL_OK; } /** * @brief Initializes the CRC MSP. * @param hcrc: CRC handle * @retval None */ __weak void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hcrc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_CRC_MspInit can be implemented in the user file */ } /** * @brief DeInitialize the CRC MSP. * @param hcrc: CRC handle * @retval None */ __weak void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hcrc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_CRC_MspDeInit can be implemented in the user file */ } /** * @} */ /** @defgroup CRC_Exported_Functions_Group2 Peripheral Control functions * @brief management functions. * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This section provides functions allowing to: (+) compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer using the combination of the previous CRC value and the new one [..] or (+) compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer independently of the previous CRC value. @endverbatim * @{ */ /** * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer * starting with the previously computed CRC as initialization value. * @param hcrc: CRC handle * @param pBuffer: pointer to the input data buffer, exact input data format is * provided by hcrc->InputDataFormat. * @param BufferLength: input data buffer length (number of bytes if pBuffer * type is * uint8_t, number of half-words if pBuffer type is * uint16_t, * number of words if pBuffer type is * uint32_t). * @note By default, the API expects a uint32_t pointer as input buffer parameter. * Input buffer pointers with other types simply need to be cast in uint32_t * and the API will internally adjust its input data processing based on the * handle field hcrc->InputDataFormat. * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) { uint32_t index = 0; /* CRC input data buffer index */ uint32_t temp = 0; /* CRC output (read from hcrc->Instance->DR register) */ /* Process locked */ __HAL_LOCK(hcrc); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; switch (hcrc->InputDataFormat) { case CRC_INPUTDATA_FORMAT_WORDS: /* Enter Data to the CRC calculator */ for(index = 0; index < BufferLength; index++) { hcrc->Instance->DR = pBuffer[index]; } temp = hcrc->Instance->DR; break; case CRC_INPUTDATA_FORMAT_BYTES: temp = CRC_Handle_8(hcrc, (uint8_t*)pBuffer, BufferLength); break; case CRC_INPUTDATA_FORMAT_HALFWORDS: temp = CRC_Handle_16(hcrc, (uint16_t*)pBuffer, BufferLength); break; default: break; } /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hcrc); /* Return the CRC computed value */ return temp; } /** * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer * starting with hcrc->Instance->INIT as initialization value. * @param hcrc: CRC handle * @param pBuffer: pointer to the input data buffer, exact input data format is * provided by hcrc->InputDataFormat. * @param BufferLength: input data buffer length (number of bytes if pBuffer * type is * uint8_t, number of half-words if pBuffer type is * uint16_t, * number of words if pBuffer type is * uint32_t). * @note By default, the API expects a uint32_t pointer as input buffer parameter. * Input buffer pointers with other types simply need to be cast in uint32_t * and the API will internally adjust its input data processing based on the * handle field hcrc->InputDataFormat. * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) { uint32_t index = 0; /* CRC input data buffer index */ uint32_t temp = 0; /* CRC output (read from hcrc->Instance->DR register) */ /* Process locked */ __HAL_LOCK(hcrc); /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_BUSY; /* Reset CRC Calculation Unit (hcrc->Instance->INIT is * written in hcrc->Instance->DR) */ __HAL_CRC_DR_RESET(hcrc); switch (hcrc->InputDataFormat) { case CRC_INPUTDATA_FORMAT_WORDS: /* Enter 32-bit input data to the CRC calculator */ for(index = 0; index < BufferLength; index++) { hcrc->Instance->DR = pBuffer[index]; } temp = hcrc->Instance->DR; break; case CRC_INPUTDATA_FORMAT_BYTES: /* Specific 8-bit input data handling */ temp = CRC_Handle_8(hcrc, (uint8_t*)pBuffer, BufferLength); break; case CRC_INPUTDATA_FORMAT_HALFWORDS: /* Specific 16-bit input data handling */ temp = CRC_Handle_16(hcrc, (uint16_t*)pBuffer, BufferLength); break; default: break; } /* Change CRC peripheral state */ hcrc->State = HAL_CRC_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hcrc); /* Return the CRC computed value */ return temp; } /** * @} */ /** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions * @brief Peripheral State functions. * @verbatim =============================================================================== ##### Peripheral State functions ##### =============================================================================== [..] This subsection permits to get in run-time the status of the peripheral. @endverbatim * @{ */ /** * @brief Return the CRC handle state. * @param hcrc: CRC handle * @retval HAL state */ HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc) { /* Return CRC handle state */ return hcrc->State; } /** * @} */ /** * @} */ /** @defgroup CRC_Private_Functions CRC Private Functions * @{ */ /** * @brief Enter 8-bit input data to the CRC calculator. * Specific data handling to optimize processing time. * @param hcrc: CRC handle * @param pBuffer: pointer to the input data buffer * @param BufferLength: input data buffer length * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength) { uint32_t i = 0; /* input data buffer index */ /* Processing time optimization: 4 bytes are entered in a row with a single word write, * last bytes must be carefully fed to the CRC calculator to ensure a correct type * handling by the IP */ for(i = 0; i < (BufferLength/4); i++) { hcrc->Instance->DR = ((uint32_t)pBuffer[4*i]<<24) | ((uint32_t)pBuffer[4*i+1]<<16) | ((uint32_t)pBuffer[4*i+2]<<8) | (uint32_t)pBuffer[4*i+3]; } /* last bytes specific handling */ if ((BufferLength%4) != 0) { if (BufferLength%4 == 1) { *(uint8_t volatile*) (&hcrc->Instance->DR) = pBuffer[4*i]; } if (BufferLength%4 == 2) { *(uint16_t volatile*) (&hcrc->Instance->DR) = ((uint32_t)pBuffer[4*i]<<8) | (uint32_t)pBuffer[4*i+1]; } if (BufferLength%4 == 3) { *(uint16_t volatile*) (&hcrc->Instance->DR) = ((uint32_t)pBuffer[4*i]<<8) | (uint32_t)pBuffer[4*i+1]; *(uint8_t volatile*) (&hcrc->Instance->DR) = pBuffer[4*i+2]; } } /* Return the CRC computed value */ return hcrc->Instance->DR; } /** * @brief Enter 16-bit input data to the CRC calculator. * Specific data handling to optimize processing time. * @param hcrc: CRC handle * @param pBuffer: pointer to the input data buffer * @param BufferLength: input data buffer length * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) */ static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength) { uint32_t i = 0; /* input data buffer index */ /* Processing time optimization: 2 HalfWords are entered in a row with a single word write, * in case of odd length, last HalfWord must be carefully fed to the CRC calculator to ensure * a correct type handling by the IP */ for(i = 0; i < (BufferLength/2); i++) { hcrc->Instance->DR = ((uint32_t)pBuffer[2*i]<<16) | (uint32_t)pBuffer[2*i+1]; } if ((BufferLength%2) != 0) { *(uint16_t volatile*) (&hcrc->Instance->DR) = pBuffer[2*i]; } /* Return the CRC computed value */ return hcrc->Instance->DR; } /** * @} */ #endif /* HAL_CRC_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
PPA-Kerhoas-BLE/MeteoStation
STM32CubeExpansion_MEMS1_V4.1.0/Drivers/STM32L4xx_HAL_Driver/Src/stm32l4xx_hal_crc.c
C
mit
18,655
module Belugas module Php module Parser class FrameworkData FRAMEWORKS = %w(laravel cakephp codeigniter zend yii).freeze def initialize(requirements) @requirements = requirements @name = nil @version = nil extract end def extract find_name find_version end def name @name || 'non-supported' end def version @version || 0.0 end private def find_name @requirements.each do |key, _value| find_framework(key) end end def find_framework(key) FRAMEWORKS.each do |framework| @name = framework if @requirements[key].to_s.downcase.include?(framework) end end def find_version return unless @name require_fields.keys.each do |key| @version = extract_version_from_required(key) if key.include?(@name) end end def extract_version_from_required(key) value = require_fields[key].to_f value == "" ? 0.0 : value end def require_fields @require_fields ||= @requirements.fetch('require', {}) end end end end end
Gueils/belugas-php
lib/belugas/php/parser/framework_data.rb
Ruby
mit
1,305
package cmc.ps.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cmc.ps.dao.HistoryDAO; import cmc.ps.model.History; import com.googlecode.genericdao.search.ISearch; import com.googlecode.genericdao.search.SearchResult; /* * This is the implementation for our History Service. The @Service annotation * allows Spring to automatically detect this as a component rather than having * to configure it in XML. The @Autowired annotation tells Spring to inject our * History DAO using the setDao() method. */ @Service @Transactional public class HistoryServiceImpl implements HistoryService { HistoryDAO dao; @Autowired public void setDao(HistoryDAO dao) { this.dao = dao; } public boolean save(History history) { return dao.save(history); } public List<History> findAll() { return dao.findAll(); } public void flush() { dao.flush(); } public List<History> search(ISearch search) { return dao.search(search); } public History findById(Integer id) { return dao.find(id); } public boolean removeById(Integer id) { return dao.removeById(id); } public boolean remove(History history) { return dao.remove(history); } public SearchResult<History> searchAndCount(ISearch search) { return dao.searchAndCount(search); } @Override public void refresh(History history) { dao.refresh(history); } }
xm-repo/java-web-app
src/main/java/cmc/ps/service/HistoryServiceImpl.java
Java
mit
1,579
package eu.greenlightning.hypercubepdf.align; import java.util.Objects; import org.apache.pdfbox.pdmodel.common.PDRectangle; /** * Combination of a {@link HCPHorizontalAlignment} and {@link HCPVerticalAlignment}. * <p> * Describes an alignment in a 2D space where the x-axis points right and the y-axis points upwards (see also * {@linkplain HCPVerticalAlignment}). * * @author Green Lightning */ public enum HCPAlignment { /** The left (smaller) x-coordinates and the upper (larger) y-coordinates will be aligned. */ TOP_LEFT(HCPHorizontalAlignment.LEFT, HCPVerticalAlignment.TOP), /** The center x-coordinates and the upper (larger) y-coordinates will be aligned. */ TOP(HCPHorizontalAlignment.CENTER, HCPVerticalAlignment.TOP), /** The right (larger) x-coordinates and the upper (larger) y-coordinates will be aligned. */ TOP_RIGHT(HCPHorizontalAlignment.RIGHT, HCPVerticalAlignment.TOP), /** The left (smaller) x-coordinates and the center y-coordinates will be aligned. */ LEFT(HCPHorizontalAlignment.LEFT, HCPVerticalAlignment.CENTER), /** The center x-coordinates and the center y-coordinates will be aligned. */ CENTER(HCPHorizontalAlignment.CENTER, HCPVerticalAlignment.CENTER), /** The right (larger) x-coordinates and the center y-coordinates will be aligned. */ RIGHT(HCPHorizontalAlignment.RIGHT, HCPVerticalAlignment.CENTER), /** The left (smaller) x-coordinates and the lower (smaller) y-coordinates will be aligned. */ BOTTOM_LEFT(HCPHorizontalAlignment.LEFT, HCPVerticalAlignment.BOTTOM), /** The center x-coordinates and the lower (smaller) y-coordinates will be aligned. */ BOTTOM(HCPHorizontalAlignment.CENTER, HCPVerticalAlignment.BOTTOM), /** The right (larger) x-coordinates and the lower (smaller) y-coordinates will be aligned. */ BOTTOM_RIGHT(HCPHorizontalAlignment.RIGHT, HCPVerticalAlignment.BOTTOM); /** * Returns the {@link HCPAlignment} with the specified {@link HCPHorizontalAlignment} and * {@link HCPVerticalAlignment}. * * @param horizontal not {@code null} * @param vertical not {@code null} * @return the {@link HCPAlignment} with the specified horizontal and vertical alignment * @throws NullPointerException if horizontal or vertical is {@code null} */ public static HCPAlignment valueOf(HCPHorizontalAlignment horizontal, HCPVerticalAlignment vertical) { Objects.requireNonNull(horizontal, "Horizontal must not be null."); Objects.requireNonNull(vertical, "Vertical must not be null."); // @formatter:off switch (vertical) { case TOP: switch (horizontal) { case LEFT: return TOP_LEFT; case CENTER: return TOP; case RIGHT: return TOP_RIGHT; default: throw new IllegalArgumentException("Unknown horizontal alignment: " + horizontal + "."); } case CENTER: switch (horizontal) { case LEFT: return LEFT; case CENTER: return CENTER; case RIGHT: return RIGHT; default: throw new IllegalArgumentException("Unknown horizontal alignment: " + horizontal + "."); } case BOTTOM: switch (horizontal) { case LEFT: return BOTTOM_LEFT; case CENTER: return BOTTOM; case RIGHT: return BOTTOM_RIGHT; default: throw new IllegalArgumentException("Unknown horizontal alignment: " + horizontal + "."); } default: throw new IllegalArgumentException("Unknown vertical alignment: " + vertical + "."); } // @formatter:on } private final HCPHorizontalAlignment horizontalAlignment; private final HCPVerticalAlignment verticalAlignment; private HCPAlignment(HCPHorizontalAlignment horizontalAlignment, HCPVerticalAlignment verticalAlignment) { this.horizontalAlignment = Objects.requireNonNull(horizontalAlignment); this.verticalAlignment = Objects.requireNonNull(verticalAlignment); } /** * Returns the horizontal alignment. * * @return the horizontal alignment */ public HCPHorizontalAlignment getHorizontalAlignment() { return horizontalAlignment; } /** * Returns the vertical alignment. * * @return the vertical alignment */ public HCPVerticalAlignment getVerticalAlignment() { return verticalAlignment; } /** * Aligns the child {@link PDRectangle} inside the parent {@link PDRectangle}. * <p> * The width and height of both rectangles should be positive. * <p> * Note that, if the child is wider or higher than the parent, although correctly aligned, some part(s) of it will * be outside of the parent. If this is undesired behavior, a size check should be performed before calling this * method. * <p> * If the arguments do not satisfy the given constraints the coordinates of the child after this method returns are * unspecified. Otherwise, the child will be aligned with the parent. * * @param child not {@code null} and {@linkplain PDRectangle#getWidth() getWidth()} and * {@linkplain PDRectangle#getHeight() getHeight()} should be {@literal >= 0} * @param parent not {@code null} and {@linkplain PDRectangle#getWidth() getWidth()} and * {@linkplain PDRectangle#getHeight() getHeight()} should be {@literal >= 0} * @throws NullPointerException if shape or parent is {@code null} */ public void alignChildWithParent(PDRectangle child, PDRectangle parent) { getHorizontalAlignment().alignChildWithParent(child, parent); getVerticalAlignment().alignChildWithParent(child, parent); } }
GreenLightning/hypercube
src/eu/greenlightning/hypercubepdf/align/HCPAlignment.java
Java
mit
5,358
// track page views var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-105747972-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); var currIcon = 0; updateState(null); // updates icon image function updateIcon() { currIcon = (currIcon + 1) % 2; chrome.browserAction.setIcon({path: "./../icons/ticker_sticker_" + currIcon + ".png"}); } // turning extension on and off chrome.browserAction.onClicked.addListener(function(tab) { updateState(tab); }); function updateState(tab) { updateIcon(); chrome.storage.sync.set({'state': currIcon}, function() { //message('Toggled on/off');e }); }
joejacob/ticker-sticker
extension/scripts/background.js
JavaScript
mit
835
package rpc import ( "fmt" "io" "net" "github.com/ugorji/go/codec" ) type packetizer interface { NextFrame() (rpcMessage, error) } type packetHandler struct { dec decoder reader io.Reader frameDecoder *decoderWrapper protocols *protocolHandler calls *callContainer } func newPacketHandler(reader io.Reader, protocols *protocolHandler, calls *callContainer) *packetHandler { return &packetHandler{ reader: reader, dec: codec.NewDecoder(reader, newCodecMsgpackHandle()), frameDecoder: newDecoderWrapper(), protocols: protocols, calls: calls, } } func (p *packetHandler) NextFrame() (rpcMessage, error) { bytes, err := p.loadNextFrame() if err != nil { return nil, err } if len(bytes) < 1 { return nil, NewPacketizerError("invalid frame size: %d", len(bytes)) } // Attempt to read the fixarray nb := int(bytes[0]) // Interpret the byte as the length field of a fixarray of up // to 15 elements: see // https://github.com/msgpack/msgpack/blob/master/spec.md#formats-array // . Do this so we can decode directly into the expected // fields without copying. if nb < 0x91 || nb > 0x9f { return nil, NewPacketizerError("wrong message structure prefix (%d)", nb) } p.frameDecoder.ResetBytes(bytes[1:]) return decodeRPC(nb-0x90, p.frameDecoder, p.protocols, p.calls) } func (p *packetHandler) loadNextFrame() ([]byte, error) { // Get the packet length var l int if err := p.dec.Decode(&l); err != nil { if _, ok := err.(*net.OpError); ok { // If the connection is reset or has been closed on this side, // return EOF return nil, io.EOF } return nil, err } bytes := make([]byte, l) lenRead, err := io.ReadFull(p.reader, bytes) if err != nil { return nil, err } if lenRead != l { return nil, fmt.Errorf("Unable to read desired length. Desired: %d, actual: %d", l, lenRead) } return bytes, nil }
jzila/go-framed-msgpack-rpc
packetizer.go
GO
mit
1,918
(() => { 'use strict'; angular .module('app') .service('TokenService', TokenService); function TokenService($localStorage) { this.get = get; this.save = save; this.clean = clean; //// function get() { return $localStorage.token; } function save(token) { return $localStorage.token = token; } function clean() { delete $localStorage.token; } } })();
royalrangers-ck/rr-web-app
app/utils/services/token.service.js
JavaScript
mit
505
import * as React from 'react'; import { SxProps } from '@mui/system'; import { OverridableStringUnion } from '@mui/types'; import { ExtendBadgeUnstyledTypeMap, BadgeUnstyledTypeMap } from '@mui/base/BadgeUnstyled'; import { Theme } from '../styles'; import { OverridableComponent, OverrideProps } from '../OverridableComponent'; export interface BadgePropsVariantOverrides {} export interface BadgePropsColorOverrides {} export type BadgeTypeMap< D extends React.ElementType = 'span', P = {}, > = ExtendBadgeUnstyledTypeMap<{ props: P & { /** * Override or extend the styles applied to the component. */ classes?: BadgeUnstyledTypeMap['props']['classes'] & { /** Styles applied to the badge `span` element if `color="primary"`. */ colorPrimary?: string; /** Styles applied to the badge `span` element if `color="secondary"`. */ colorSecondary?: string; /** Styles applied to the badge `span` element if `color="error"`. */ colorError?: string; /** Styles applied to the badge `span` element if `color="info"`. */ colorInfo?: string; /** Styles applied to the badge `span` element if `color="success"`. */ colorSuccess?: string; /** Styles applied to the badge `span` element if `color="warning"`. */ colorWarning?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'top', 'right' }} overlap="rectangular"`. */ anchorOriginTopRightRectangular?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'bottom', 'right' }} overlap="rectangular"`. */ anchorOriginBottomRightRectangular?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'top', 'left' }} overlap="rectangular"`. */ anchorOriginTopLeftRectangular?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'bottom', 'left' }} overlap="rectangular"`. */ anchorOriginBottomLeftRectangular?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'top', 'right' }} overlap="circular"`. */ anchorOriginTopRightCircular?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'bottom', 'right' }} overlap="circular"`. */ anchorOriginBottomRightCircular?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'top', 'left' }} overlap="circular"`. */ anchorOriginTopLeftCircular?: string; /** Class name applied to the badge `span` element if `anchorOrigin={{ 'bottom', 'left' }} overlap="circular"`. */ anchorOriginBottomLeftCircular?: string; /** Class name applied to the badge `span` element if `overlap="rectangular"`. */ overlapRectangular?: string; /** Class name applied to the badge `span` element if `overlap="circular"`. */ overlapCircular?: string; }; /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'default' */ color?: OverridableStringUnion< 'primary' | 'secondary' | 'default' | 'error' | 'info' | 'success' | 'warning', BadgePropsColorOverrides >; /** * Wrapped shape the badge should overlap. * @default 'rectangular' */ overlap?: 'rectangular' | 'circular'; /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx?: SxProps<Theme>; /** * The variant to use. * @default 'standard' */ variant?: OverridableStringUnion<'standard' | 'dot', BadgePropsVariantOverrides>; }; defaultComponent: D; }>; type BadgeRootProps = NonNullable<BadgeTypeMap['props']['componentsProps']>['root']; type BadgeBadgeProps = NonNullable<BadgeTypeMap['props']['componentsProps']>['badge']; export const BadgeRoot: React.FC<BadgeRootProps>; export const BadgeMark: React.FC<BadgeBadgeProps>; export type BadgeClassKey = keyof NonNullable<BadgeTypeMap['props']['classes']>; /** * * Demos: * * - [Avatars](https://mui.com/components/avatars/) * - [Badges](https://mui.com/components/badges/) * * API: * * - [Badge API](https://mui.com/api/badge/) * - inherits [BadgeUnstyled API](https://mui.com/api/badge-unstyled/) */ declare const Badge: OverridableComponent<BadgeTypeMap>; export type BadgeClasses = Record<BadgeClassKey, string>; export const badgeClasses: BadgeClasses; export type BadgeProps< D extends React.ElementType = BadgeTypeMap['defaultComponent'], P = {}, > = OverrideProps<BadgeTypeMap<D, P>, D>; export default Badge;
oliviertassinari/material-ui
packages/mui-material/src/Badge/Badge.d.ts
TypeScript
mit
4,622
import React from 'react'; import { mount } from 'enzyme'; import { AccountName } from './AccountName'; import { MockedProvider } from '@apollo/react-testing'; import { PublicAccount, AccountType } from '../../../common/types/graphql'; import { AccountQuery } from '../graphql'; jest.mock('../graphql/client'); function sleep(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } const account: PublicAccount & { __typename: string } = { __typename: 'PublicAccount', id: 'test-01', accountName: 'corvette', display: 'Yvette Deladrier', type: AccountType.User, photo: null, }; const mocks = [{ request: { query: AccountQuery, variables: { id: 'test-user', }, }, result: { data: { account, } }, }]; describe('controls.AccountName', () => { test('render', async () => { const wrapper = mount( <MockedProvider mocks={mocks} addTypename={true}> <AccountName id="test-user" /> </MockedProvider> ); await sleep(1); wrapper.update(); expect(wrapper.find('span')).toExist(); expect(wrapper).toHaveText('Yvette Deladrier'); expect(wrapper.find('span')).toHaveClassName('account-name'); }); });
viridia/klendathu
client/src/controls/AccountName.spec.tsx
TypeScript
mit
1,213
local L = Apollo.GetPackage("Gemini:Locale-1.0").tPackage:NewLocale("Gear_Durability", "frFR") if not L then return end L["GP_FLAVOR"] = "Durabilité des Objets pour chaque Profil." L["GP_O_SETTINGS"] = "Durabilité" L["GP_O_SETTING_1"] = "Déclencher l'Alarme lorsque l'état est < " L["GP_O_SETTING_2"] = "Afficher la Durabilité en %" L["GP_O_SETTING_3"] = "Indiquer la Localisation de l'Équipement" L["GP_O_SETTING_4"] = "Voir une Jauge sur chaque Objet" L["GP_FIRED"] = "Déclenchement de l'Alarme à &lt;" -- xml -- location L["GP_LOC_0"] = "Non trouvé" -- xml L["GP_LOC_1"] = Apollo.GetString("InterfaceMenu_Inventory") -- xml L["GP_LOC_2"] = Apollo.GetString("Bank_Header") -- xml L["GP_LOC_3"] = "Équipé" -- xml
scscgit/scsc_wildstar_addons
Gear_Durability/locale/frFR.lua
Lua
mit
789
package org.wmaop.util.jexl; public class ExpressionProcessor { private static final char BACKSLASH = '\\'; protected static final String ENC_COLON = "__col_"; protected static final String ENC_HYPHEN = "__hyp_"; protected static final String ENC_SPACE = "__spc_"; private ExpressionProcessor() {} public static String escapedToEncoded(String expr) { int slashPos = expr.indexOf(BACKSLASH); if (slashPos == -1) { return expr; } StringBuilder sb = new StringBuilder(); int lastSlash = -1; while (slashPos != -1) { sb.append(expr.substring(lastSlash + 1, slashPos)); char c = expr.charAt(slashPos + 1); switch (c) { case ':': sb.append(ENC_COLON); break; case '-': sb.append(ENC_HYPHEN); break; case ' ': sb.append(ENC_SPACE); break; default: throw new ExpressionProcessingException("Invalid escaped character: " + c); } lastSlash = ++slashPos; slashPos = expr.indexOf(BACKSLASH, lastSlash + 1); } if (lastSlash + 1 < expr.length()) { sb.append(expr.substring(lastSlash + 1)); } return sb.toString(); } public static String decode(String expr) { int undPos = expr.indexOf("__"); if (undPos == -1) { return expr; } // Inefficient, will replace as above return expr.replace(ENC_COLON, ":").replace(ENC_HYPHEN, "-").replace(ENC_SPACE, " "); } }
wmaop/wm-aop-util
src/main/java/org/wmaop/util/jexl/ExpressionProcessor.java
Java
mit
1,359
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Soluble\FlexStore\Column\Type\IntegerType | Soluble API</title> <link rel="stylesheet" type="text/css" href="../../../../css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../../../../css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="../../../../css/sami.css"> <script src="../../../../js/jquery-1.11.1.min.js"></script> <script src="../../../../js/bootstrap.min.js"></script> <script src="../../../../js/typeahead.min.js"></script> <script src="../../../../sami.js"></script> </head> <body id="class" data-name="class:Soluble_FlexStore_Column_Type_IntegerType" data-root-path="../../../../"> <div id="content"> <div id="left-column"> <div id="control-panel"> <form id="search-form" action="../../../../search.html" method="GET"> <span class="glyphicon glyphicon-search"></span> <input name="search" class="typeahead form-control" type="search" placeholder="Search"> </form> </div> <div id="api-tree"></div> </div> <div id="right-column"> <nav id="site-nav" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements"> <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="../../../../index.html">Soluble API</a> </div> <div class="collapse navbar-collapse" id="navbar-elements"> <ul class="nav navbar-nav"> <li><a href="../../../../classes.html">Classes</a></li> <li><a href="../../../../namespaces.html">Namespaces</a></li> <li><a href="../../../../interfaces.html">Interfaces</a></li> <li><a href="../../../../traits.html">Traits</a></li> <li><a href="../../../../doc-index.html">Index</a></li> <li><a href="../../../../search.html">Search</a></li> </ul> </div> </div> </nav> <div class="namespace-breadcrumbs"> <ol class="breadcrumb"> <li><span class="label label-default">class</span></li> <li><a href="../../../../Soluble.html">Soluble</a></li> <li><a href="../../../../Soluble/FlexStore.html">FlexStore</a></li> <li><a href="../../../../Soluble/FlexStore/Column.html">Column</a></li> <li><a href="../../../../Soluble/FlexStore/Column/Type.html">Type</a></li> <li>IntegerType</li> </ol> </div> <div id="page-content"> <div class="page-header"> <h1>IntegerType</h1> </div> <p> class <strong>IntegerType</strong> extends <a href="../../../../Soluble/FlexStore/Column/Type/AbstractType.html"><abbr title="Soluble\FlexStore\Column\Type\AbstractType">AbstractType</abbr></a></p> <h2>Methods</h2> <div class="container-fluid underlined"> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method_getName">getName</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method___toString">__toString</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"><small>from&nbsp;<a href="../../../../Soluble/FlexStore/Column/Type/AbstractType.html#method___toString"><abbr title="Soluble\FlexStore\Column\Type\AbstractType">AbstractType</abbr></a></small></div> </div> </div> <h2>Details</h2> <div id="method-details"> <div class="method-item"> <h3 id="method_getName"> <div class="location">at line 10</div> <code> string <strong>getName</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td>string</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method___toString"> <div class="location">in <a href="../../../../Soluble/FlexStore/Column/Type/AbstractType.html#method___toString"><abbr title="Soluble\FlexStore\Column\Type\AbstractType">AbstractType</abbr></a> at line 18</div> <code> string <strong>__toString</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td>string</td> <td> </td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/">Sami, the API Documentation Generator</a>. </div> </div> </div> </body> </html>
belgattitude/solublecomponents
docs/sphinx/source/_static/API/SAMI/Soluble/FlexStore/Column/Type/IntegerType.html
HTML
mit
6,580
<?php /** * * Created by mtils on 3/21/21 at 2:16 PM. **/ namespace Ems\Config\Exception; use RuntimeException; use Throwable; /** * Class EnvFileException * * Mark an error in the env file. Pass a line to help the developer * @package Ems\Config\Exception */ class EnvFileException extends RuntimeException { /** * @var int */ protected $envFileLine = 0; public function __construct( $envFileLine = 0, $message = '', Throwable $previous = null ) { if (!$message && $previous) { $message = "Error in line $envFileLine: " . $previous->getMessage(); } parent::__construct($message, 0, $previous); $this->envFileLine = $envFileLine; } /** * @return int */ public function getEnvFileLine() { return $this->envFileLine; } }
mtils/php-ems
src/Ems/Config/Exception/EnvFileException.php
PHP
mit
864
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Wrapper from '../components/wrapper' import Articles from '../components/articles' import Nav from '../components/nav' import Hero from '../components/hero' import Footer from '../components/footer' import DocumentMeta from 'react-document-meta' export default class BlogIndex extends React.Component { render() { const meta = { title: 'Wanderlust - A blog about digital nomad lifestyle', description: 'Digital nomads travel the world and work location independent.', canonical: 'https://wanderlust.tech/en/', locale: 'en' } this.props.route.path = '/en/' this.props.route.page.data = { locale: 'EN' } return ( <div> <DocumentMeta {...meta} /> <Nav route={this.props.route} /> <Hero route={this.props.route} /> <Wrapper> <Articles route={this.props.route} /> </Wrapper> <Footer /> </div> ) } }
meuschke/wanderlust.tech
pages/index_en.js
JavaScript
mit
1,026
namespace ItIsAlive.Extensions.NHibernate { using Autofac; using Bootstrapping.Tasks; using Composition.Discovery; using Composition.Markers; [Hidden] public class WarmupNHibernate : IInitializationTask, ISingleInstanceDependency { public void Execute(InitializationTaskContext context) { context.Builder.RegisterType<ResolveSessionFactoryOnce>().AsImplementedInterfaces(); } } }
pekkah/ItIsAlive
sources/ItIsAlive.Extensions.NHibernate/WarmupNHibernate.cs
C#
mit
467
<?php namespace App\Http\Middleware; use Closure; use Laralytics; use Illuminate\Contracts\Auth\Guard; /** * Class LaralyticsMiddleware * @package App\Http\Middleware */ class LaralyticsMiddleware { /** * The Guard implementation. * * @var Guard */ protected $auth; /** * Create a new filter instance. * * @param Guard $auth */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($request->is('laralytics')) { return $next($request); } return Laralytics::url($request, $next($request)); } }
bsharp/Laralytics
publish/Http/Middleware/LaralyticsMiddleware.php
PHP
mit
848
# Django Post Office Django Post Office is a simple app to send and manage your emails in Django. Some awesome features are: - Allows you to send email asynchronously - Multi backend support - Supports HTML email - Supports inlined images in HTML email - Supports database based email templates - Supports multilingual email templates (i18n) - Built in scheduling support - Works well with task queues like [RQ](http://python-rq.org) or [Celery](http://www.celeryproject.org) - Uses multiprocessing (and threading) to send a large number of emails in parallel ## Dependencies - [django \>= 2.2](https://djangoproject.com/) - [jsonfield](https://github.com/rpkilby/jsonfield) - [bleach](https://bleach.readthedocs.io/) With this optional dependency, HTML emails are nicely rendered inside the Django admin backend. Without this library, all HTML tags will otherwise be stripped for security reasons. ## Installation [![Build Status](https://travis-ci.org/ui/django-post_office.png?branch=master)](https://travis-ci.org/ui/django-post_office) [![PyPI version](https://img.shields.io/pypi/v/django-post_office.svg)](https://pypi.org/project/django-post_office/) ![Software license](https://img.shields.io/pypi/l/django-post_office.svg) Install from PyPI (or [manually download from PyPI](http://pypi.python.org/pypi/django-post_office)): ```sh pip install django-post_office ``` Add `post_office` to your INSTALLED_APPS in django's `settings.py`: ```python INSTALLED_APPS = ( # other apps "post_office", ) ``` Run `migrate`: ```sh python manage.py migrate ``` Set `post_office.EmailBackend` as your `EMAIL_BACKEND` in Django's `settings.py`: ```python EMAIL_BACKEND = 'post_office.EmailBackend' ``` ## Quickstart Send a simple email is really easy: ```python from post_office import mail mail.send( 'recipient@example.com', # List of email addresses also accepted 'from@example.com', subject='My email', message='Hi there!', html_message='Hi <strong>there</strong>!', ) ``` If you want to use templates, ensure that Django's admin interface is enabled. Create an `EmailTemplate` instance via `admin` and do the following: ```python from post_office import mail mail.send( 'recipient@example.com', # List of email addresses also accepted 'from@example.com', template='welcome_email', # Could be an EmailTemplate instance or name context={'foo': 'bar'}, ) ``` The above command will put your email on the queue so you can use the command in your webapp without slowing down the request/response cycle too much. To actually send them out, run `python manage.py send_queued_mail`. You can schedule this management command to run regularly via cron: * * * * * (/usr/bin/python manage.py send_queued_mail >> send_mail.log 2>&1) ## Usage ### mail.send() `mail.send` is the most important function in this library, it takes these arguments: | Argument | Required | Description | | --- | --- | --- | | recipients | Yes | List of recipient email addresses | | sender | No | Defaults to `settings.DEFAULT_FROM_EMAIL`, display name like `John <john@a.com>` is allowed | | subject | No | Email subject (if `template` is not specified) | | message | No | Email content (if `template` is not specified) | | html_message | No | HTML content (if `template` is not specified) | | template | No | `EmailTemplate` instance or name of template | | language | No | Language in which you want to send the email in (if you have multilingual email templates). | | cc | No | List of emails, will appear in `cc` field | | bcc | No | List of emails, will appear in `bcc` field | | attachments | No | Email attachments - a dict where the keys are the filenames and the values are files, file-like-objects or path to file | | context | No | A dict, used to render templated email | | headers | No | A dictionary of extra headers on the message | | scheduled_time | No | A date/datetime object indicating when the email should be sent | | expires_at | No | If specified, mails that are not yet sent won't be delivered after this date. | | priority | No | `high`, `medium`, `low` or `now` (sent immediately) | | backend | No | Alias of the backend you want to use, `default` will be used if not specified. | | render_on_delivery | No | Setting this to `True` causes email to be lazily rendered during delivery. `template` is required when `render_on_delivery` is True. With this option, the full email content is never stored in the DB. May result in significant space savings if you're sending many emails using the same template. | Here are a few examples. If you just want to send out emails without using database templates. You can call the `send` command without the `template` argument. ```python from post_office import mail mail.send( ['recipient1@example.com'], 'from@example.com', subject='Welcome!', message='Welcome home, {{ name }}!', html_message='Welcome home, <b>{{ name }}</b>!', headers={'Reply-to': 'reply@example.com'}, scheduled_time=date(2014, 1, 1), context={'name': 'Alice'}, ) ``` `post_office` is also task queue friendly. Passing `now` as priority into `send_mail` will deliver the email right away (instead of queuing it), regardless of how many emails you have in your queue: ```python from post_office import mail mail.send( ['recipient1@example.com'], 'from@example.com', template='welcome_email', context={'foo': 'bar'}, priority='now', ) ``` This is useful if you already use something like [django-rq](https://github.com/ui/django-rq) to send emails asynchronously and only need to store email related activities and logs. If you want to send an email with attachments: ```python from django.core.files.base import ContentFile from post_office import mail mail.send( ['recipient1@example.com'], 'from@example.com', template='welcome_email', context={'foo': 'bar'}, priority='now', attachments={ 'attachment1.doc': '/path/to/file/file1.doc', 'attachment2.txt': ContentFile('file content'), 'attachment3.txt': {'file': ContentFile('file content'), 'mimetype': 'text/plain'}, } ) ``` ### Template Tags and Variables `post-office` supports Django's template tags and variables. For example, if you put `Hello, {{ name }}` in the subject line and pass in `{'name': 'Alice'}` as context, you will get `Hello, Alice` as subject: ```python from post_office.models import EmailTemplate from post_office import mail EmailTemplate.objects.create( name='morning_greeting', subject='Morning, {{ name|capfirst }}', content='Hi {{ name }}, how are you feeling today?', html_content='Hi <strong>{{ name }}</strong>, how are you feeling today?', ) mail.send( ['recipient@example.com'], 'from@example.com', template='morning_greeting', context={'name': 'alice'}, ) # This will create an email with the following content: subject = 'Morning, Alice', content = 'Hi alice, how are you feeling today?' content = 'Hi <strong>alice</strong>, how are you feeling today?' ``` ### Multilingual Email Templates You can easily create email templates in various different languages. For example: ```python template = EmailTemplate.objects.create( name='hello', subject='Hello world!', ) # Add an Indonesian version of this template: indonesian_template = template.translated_templates.create( language='id', subject='Halo Dunia!' ) ``` Sending an email using template in a non default languange is similarly easy: ```python mail.send( ['recipient@example.com'], 'from@example.com', template=template, # Sends using the default template ) mail.send( ['recipient@example.com'], 'from@example.com', template=template, language='id', # Sends using Indonesian template ) ``` ### Inlined Images Often one wants to render images inside a template, which are attached as inlined `MIMEImage` to the outgoing email. This requires a slightly modified Django Template Engine, keeping a list of inlined images, which later will be added to the outgoing message. First we must add a special Django template backend to our list of template engines: ```python TEMPLATES = [ { ... }, { 'BACKEND': 'post_office.template.backends.post_office.PostOfficeTemplates', 'APP_DIRS': True, 'DIRS': [], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.request', ] } } ] ``` then we must tell Post-Office to use this template engine: ```python POST_OFFICE = { 'TEMPLATE_ENGINE': 'post_office', } ``` In templates used to render HTML for emails add ``` {% load post_office %} <p>... somewhere in the body ...</p> <img src="{% inline_image 'path/to/image.png' %}" /> ``` Here the templatetag named `inline_image` is used to keep track of inlined images. It takes a single parameter. This can either be the relative path to an image file located in one of the `static` directories, or the absolute path to an image file, or an image-file object itself. Templates rendered using this templatetag, render a reference ID for each given image, and store these images inside the context of the adopted template engine. Later on, when the rendered template is passed to the mailing library, those images will be transferred to the email message object as `MIMEImage`-attachments. To send an email containing both, a plain text body and some HTML with inlined images, use the following code snippet: ```python from django.core.mail import EmailMultiAlternatives subject, body = "Hello", "Plain text body" from_email, to_email = "no-reply@example.com", "john@example.com" email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) template = get_template('email-template-name.html', using='post_office') context = {...} html = template.render(context) email_message.attach_alternative(html, 'text/html') template.attach_related(email_message) email_message.send() ``` To send an email containing HTML with inlined images, but without a plain text body, use this code snippet: ```python from django.core.mail import EmailMultiAlternatives subject, from_email, to_email = "Hello", "no-reply@example.com", "john@example.com" template = get_template('email-template-name.html', using='post_office') context = {...} html = template.render(context) email_message = EmailMultiAlternatives(subject, html, from_email, [to_email]) email_message.content_subtype = 'html' template.attach_related(email_message) email_message.send() ``` ### Custom Email Backends By default, `post_office` uses django's `smtp.EmailBackend`. If you want to use a different backend, you can do so by configuring `BACKENDS`. For example if you want to use [django-ses](https://github.com/hmarr/django-ses): ```python # Put this in settings.py POST_OFFICE = { ... 'BACKENDS': { 'default': 'smtp.EmailBackend', 'ses': 'django_ses.SESBackend', } } ``` You can then choose what backend you want to use when sending mail: ```python # If you omit `backend_alias` argument, `default` will be used mail.send( ['recipient@example.com'], 'from@example.com', subject='Hello', ) # If you want to send using `ses` backend mail.send( ['recipient@example.com'], 'from@example.com', subject='Hello', backend='ses', ) ``` ### Management Commands - `send_queued_mail` - send queued emails, those aren't successfully sent will be marked as `failed`. Accepts the following arguments: | Argument | Description | | --- | --- | |`--processes` or `-p` | Number of parallel processes to send email. Defaults to 1 | | `--lockfile` or `-L` | Full path to file used as lock file. Defaults to `/tmp/post_office.lock` | - `cleanup_mail` - delete all emails created before an X number of days (defaults to 90). | Argument | Description | | --- | --- | | `--days` or `-d` | Email older than this argument will be deleted. Defaults to 90 | | `--delete-attachments` | Flag to delete orphaned attachment records and files on disk. If not specified, attachments won't be deleted. | You may want to set these up via cron to run regularly: * * * * * (cd $PROJECT; python manage.py send_queued_mail --processes=1 >> $PROJECT/cron_mail.log 2>&1) 0 1 * * * (cd $PROJECT; python manage.py cleanup_mail --days=30 --delete-attachments >> $PROJECT/cron_mail_cleanup.log 2>&1) ## Settings This section outlines all the settings and configurations that you can put in Django's `settings.py` to fine tune `post-office`'s behavior. ### Batch Size If you may want to limit the number of emails sent in a batch (sometimes useful in a low memory environment), use the `BATCH_SIZE` argument to limit the number of queued emails fetched in one batch. ```python # Put this in settings.py POST_OFFICE = { ... 'BATCH_SIZE': 50, } ``` ### Default Priority The default priority for emails is `medium`, but this can be altered by setting `DEFAULT_PRIORITY`. Integration with asynchronous email backends (e.g. based on Celery) becomes trivial when set to `now`. ```python # Put this in settings.py POST_OFFICE = { ... 'DEFAULT_PRIORITY': 'now', } ``` ### Override Recipients Defaults to `None`. This option is useful if you want to redirect all emails to specified a few email for development purposes. ```python # Put this in settings.py POST_OFFICE = { ... 'OVERRIDE_RECIPIENTS': ['to@example.com', 'to2@example.com'], } ``` ### Message-ID The SMTP standard requires that each email contains a unique [Message-ID](https://tools.ietf.org/html/rfc2822#section-3.6.4). Typically the Message-ID consists of two parts separated by the `@` symbol: The left part is a generated pseudo random number. The right part is a constant string, typically denoting the full qualified domain name of the sending server. By default, **Django** generates such a Message-ID during email delivery. Since **django-post_office** keeps track of all delivered emails, it can be very useful to create and store this Message-ID while creating each email in the database. This identifier then can be looked up in the Django admin backend. To enable this feature, add this to your Post-Office settings: ```python # Put this in settings.py POST_OFFICE = { ... 'MESSAGE_ID_ENABLED': True, } ``` It can further be fine tuned, using for instance another full qualified domain name: ```python # Put this in settings.py POST_OFFICE = { ... 'MESSAGE_ID_ENABLED': True, 'MESSAGE_ID_FQDN': 'example.com', } ``` Otherwise, if `MESSAGE_ID_FQDN` is unset (the default), **django-post_office** falls back to the DNS name of the server, which is determined by the network settings of the host. ### Retry Not activated by default. You can automatically requeue failed email deliveries. You can also configure failed deliveries to be retried after a specific time interval. ```python # Put this in settings.py POST_OFFICE = { ... 'MAX_RETRIES': 4, 'RETRY_INTERVAL': datetime.timedelta(minutes=15), # Schedule to be retried 15 minutes later } ``` ### Log Level Logs are stored in the database and is browseable via Django admin. The default log level is 2 (logs both successful and failed deliveries) This behavior can be changed by setting `LOG_LEVEL`. ```python # Put this in settings.py POST_OFFICE = { ... 'LOG_LEVEL': 1, # Log only failed deliveries } ``` The different options are: * `0` logs nothing * `1` logs only failed deliveries * `2` logs everything (both successful and failed delivery attempts) ### Sending Order The default sending order for emails is `-priority`, but this can be altered by setting `SENDING_ORDER`. For example, if you want to send queued emails in FIFO order : ```python # Put this in settings.py POST_OFFICE = { ... 'SENDING_ORDER': ['created'], } ``` ### Context Field Serializer If you need to store complex Python objects for deferred rendering (i.e. setting `render_on_delivery=True`), you can specify your own context field class to store context variables. For example if you want to use [django-picklefield](https://github.com/gintas/django-picklefield/tree/master/src/picklefield): ```python # Put this in settings.py POST_OFFICE = { ... 'CONTEXT_FIELD_CLASS': 'picklefield.fields.PickledObjectField', } ``` `CONTEXT_FIELD_CLASS` defaults to `jsonfield.JSONField`. ### Logging You can configure `post-office`'s logging from Django's `settings.py`. For example: ```python LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "post_office": { "format": "[%(levelname)s]%(asctime)s PID %(process)d: %(message)s", "datefmt": "%d-%m-%Y %H:%M:%S", }, }, "handlers": { "post_office": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "post_office" }, # If you use sentry for logging 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.handlers.SentryHandler', }, }, 'loggers': { "post_office": { "handlers": ["post_office", "sentry"], "level": "INFO" }, }, } ``` ### Threads `post-office` >= 3.0 allows you to use multiple threads to dramatically speed up the speed at which emails are sent. By default, `post-office` uses 5 threads per process. You can tweak this setting by changing `THREADS_PER_PROCESS` setting. This may dramatically increase the speed of bulk email delivery, depending on which email backends you use. In my tests, multi threading speeds up email backends that use HTTP based (REST) delivery mechanisms but doesn't seem to help SMTP based backends. ```python # Put this in settings.py POST_OFFICE = { ... 'THREADS_PER_PROCESS': 10, } ``` Performance ----------- ### Caching if Django's caching mechanism is configured, `post_office` will cache `EmailTemplate` instances . If for some reason you want to disable caching, set `POST_OFFICE_CACHE` to `False` in `settings.py`: ```python ## All cache key will be prefixed by post_office:template: ## To turn OFF caching, you need to explicitly set POST_OFFICE_CACHE to False in settings POST_OFFICE_CACHE = False ## Optional: to use a non default cache backend, add a "post_office" entry in CACHES CACHES = { 'post_office': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } } ``` ### send_many() `send_many()` is much more performant (generates less database queries) when sending a large number of emails. `send_many()` is almost identical to `mail.send()`, with the exception that it accepts a list of keyword arguments that you'd usually pass into `mail.send()`: ```python from post_office import mail first_email = { 'sender': 'from@example.com', 'recipients': ['alice@example.com'], 'subject': 'Hi!', 'message': 'Hi Alice!' } second_email = { 'sender': 'from@example.com', 'recipients': ['bob@example.com'], 'subject': 'Hi!', 'message': 'Hi Bob!' } kwargs_list = [first_email, second_email] mail.send_many(kwargs_list) ``` Attachments are not supported with `mail.send_many()`. ## Running Tests To run the test suite: ```python `which django-admin.py` test post_office --settings=post_office.test_settings --pythonpath=. ``` You can run the full test suite for all supported versions of Django and Python with: ```python tox ``` or: ```python python setup.py test ``` ## Integration with Celery If your Django project runs in a Celery enabled configuration, you can use its worker to send out queued emails. Compared to the solution with cron (see above), or the solution with uWSGI timers (see below) this setup has the big advantage that queued emails are send *immediately* after they have been added to the mail queue. The delivery is still performed in a separate and asynchronous task, which prevents sending emails during the request/response-cycle. If you [configured Celery](https://docs.celeryproject.org/en/latest/userguide/application.html) in your project and started the [Celery worker](https://docs.celeryproject.org/en/latest/userguide/workers.html), you should see something such as: ``` --------------- celery@halcyon.local v4.0 (latentcall) --- ***** ----- -- ******* ---- [Configuration] - *** --- * --- . broker: amqp://guest@localhost:5672// - ** ---------- . app: __main__:0x1012d8590 - ** ---------- . concurrency: 8 (processes) - ** ---------- . events: OFF (enable -E to monitor this worker) - ** ---------- - *** --- * --- [Queues] -- ******* ---- . celery: exchange:celery(direct) binding:celery --- ***** ----- [tasks] . post_office.tasks.cleanup_expired_mails . post_office.tasks.send_queued_mail ``` Delivering emails through the Celery worker must be explicitly enabled: ```python # Put this in settings.py POST_OFFICE = { ... 'CELERY_ENABLED': True, } ``` Emails will then be delivered immediately after they have been queued. In order to make this happen, the project's `celery.py` setup shall invoke the [autodiscoverttasks](https://docs.celeryproject.org/en/latest/reference/celery.html#celery.Celery.autodiscover_tasks) function. In case of a temporary delivery failure, we might want retrying to send those emails by a periodic task. This can be scheduled with a simple [Celery beat configuration](https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#entries), for instance through ```python app.conf.beat_schedule = { 'send-queued-mail': { 'task': 'post_office.tasks.send_queued_mail', 'schedule': 600.0, }, } ``` The email queue now will be processed every 10 minutes. If you are using [Django Celery Beat](https://django-celery-beat.readthedocs.io/en/latest/), then use the Django-Admin backend and add a periodic taks for `post_office.tasks.send_queued_mail`. Depending on your policy, you may also want to remove expired emails from the queue. This can be done by adding another periodic taks for `post_office.tasks.cleanup_mail`, which may run once a week or month. ## Integration with uWSGI If setting up Celery is too daunting and you use [uWSGI](https://uwsgi-docs.readthedocs.org/en/latest/) as application server, then uWSGI decorators can act as a poor men's scheduler. Just add this short snipped to the project's `wsgi.py` file: ```python from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # add this block of code try: import uwsgidecorators from django.core.management import call_command @uwsgidecorators.timer(10) def send_queued_mail(num): """Send queued mail every 10 seconds""" call_command('send_queued_mail', processes=1) except ImportError: print("uwsgidecorators not found. Cron and timers are disabled") ``` Alternatively you can also use the decorator `@uwsgidecorators.cron(minute, hour, day, month, weekday)`. This will schedule a task at specific times. Use `-1` to signal any time, it corresponds to the `*` in cron. Please note that `uwsgidecorators` are available only, if the application has been started with **uWSGI**. However, Django's internal `./manange.py runserver` also access this file, therefore wrap the block into an exception handler as shown above. This configuration can be useful in environments, such as Docker containers, where you don't have a running cron-daemon. ## Signals Each time an email is added to the mail queue, Post Office emits a special [Django signal](https://docs.djangoproject.com/en/stable/topics/signals/). Whenever a third party application wants to be informed about this event, it shall connect a callback function to the Post Office's signal handler `email_queued`, for instance: ```python from django.dispatch import receiver from post_office.signals import email_queued @receiver(email_queued) def my_callback(sender, emails, **kwargs): print("Added {} mails to the sending queue".format(len(emails))) ``` The Emails objects added to the queue are passed as list to the callback handler. ## Changelog Full changelog can be found [here](https://github.com/ui/django-post_office/blob/master/CHANGELOG.md). Created and maintained by the cool guys at [Stamps](https://stamps.co.id), Indonesia's most elegant CRM/loyalty platform.
ui/django-post_office
README.md
Markdown
mit
24,875
<?php declare(strict_types=1); namespace Symplify\MonorepoBuilder\Release\Process; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; final class ProcessRunner { /** * Reasonable timeout to report hang off: 10 minutes * @var float */ private const TIMEOUT = 10 * 60.0; /** * @var SymfonyStyle */ private $symfonyStyle; public function __construct(SymfonyStyle $symfonyStyle) { $this->symfonyStyle = $symfonyStyle; } /** * @param string|string[] $commandLine */ public function run($commandLine, bool $shouldDisplayOutput = false): string { if ($this->symfonyStyle->isVerbose()) { $this->symfonyStyle->note('Running process: ' . $this->normalizeToString($commandLine)); } $process = $this->createProcess($commandLine); $process->run(); $this->reportResult($shouldDisplayOutput, $process); return $process->getOutput(); } /** * @param string|string[] $content */ private function normalizeToString($content): string { if (is_array($content)) { return implode(' ', $content); } return $content; } /** * @param string|string[] $commandLine */ private function createProcess($commandLine): Process { // @since Symfony 4.2: https://github.com/symfony/symfony/pull/27821 if (is_string($commandLine) && method_exists(Process::class, 'fromShellCommandline')) { return Process::fromShellCommandline($commandLine, null, null, null, self::TIMEOUT); } return new Process($commandLine, null, null, null, self::TIMEOUT); } private function reportResult(bool $shouldDisplayOutput, Process $process): void { if ($process->isSuccessful()) { if ($shouldDisplayOutput) { $this->symfonyStyle->writeln(trim($process->getOutput())); } return; } throw new ProcessFailedException($process); } }
Symplify/Symplify
packages/MonorepoBuilder/packages/Release/src/Process/ProcessRunner.php
PHP
mit
2,156
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_05) on Fri Dec 23 12:54:36 EST 2005 --> <TITLE> TemplateEmailListener (ATG Java API) </TITLE> <META NAME="keywords" CONTENT="atg.userprofiling.email.TemplateEmailListener interface"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="TemplateEmailListener (ATG Java API)"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TemplateEmailListener.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> atg.userprofiling.email</FONT> <BR> Interface TemplateEmailListener</H2> <DL> <DT><B>All Superinterfaces:</B> <DD>java.util.EventListener</DD> </DL> <HR> <DL> <DT>public interface <B>TemplateEmailListener</B><DT>extends java.util.EventListener</DL> <P> <p>A listener that is notified of TemplateEmailEvents. <P> <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../atg/userprofiling/email/TemplateEmailEvent.html" title="class in atg.userprofiling.email"><CODE>TemplateEmailEvent</CODE></A></DL> <HR> <P> <!-- ======== NESTED CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Field Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../atg/userprofiling/email/TemplateEmailListener.html#CLASS_VERSION">CLASS_VERSION</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../atg/userprofiling/email/TemplateEmailListener.html#emailNotification(atg.userprofiling.email.TemplateEmailEvent)">emailNotification</A></B>(<A HREF="../../../atg/userprofiling/email/TemplateEmailEvent.html" title="class in atg.userprofiling.email">TemplateEmailEvent</A>&nbsp;pEvent)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Called when a TemplateEmailEvent occurs.</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Field Detail</B></FONT></TD> </TR> </TABLE> <A NAME="CLASS_VERSION"><!-- --></A><H3> CLASS_VERSION</H3> <PRE> public static final java.lang.String <B>CLASS_VERSION</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#atg.userprofiling.email.TemplateEmailListener.CLASS_VERSION">Constant Field Values</A></DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="emailNotification(atg.userprofiling.email.TemplateEmailEvent)"><!-- --></A><H3> emailNotification</H3> <PRE> public void <B>emailNotification</B>(<A HREF="../../../atg/userprofiling/email/TemplateEmailEvent.html" title="class in atg.userprofiling.email">TemplateEmailEvent</A>&nbsp;pEvent)</PRE> <DL> <DD>Called when a TemplateEmailEvent occurs. <P> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TemplateEmailListener.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
Smolations/more-dash-docsets
docsets/ATG 2007.1.docset/Contents/Resources/Documents/atg/userprofiling/email/TemplateEmailListener.html
HTML
mit
9,455
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("jcasm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("jcasm")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("af9adb39-2257-47d1-98c5-71f256fb5b15")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
jncronin/jca
jcasm/jcasm/Properties/AssemblyInfo.cs
C#
mit
1,422
'use strict'; exports.command = function( ) { const SauceLabs = require( 'saucelabs' ); const saucelabs = new SauceLabs({ username: process.env.SAUCE_USERNAME, password: process.env.SAUCE_ACCESS_KEY }); const sessionid = this.capabilities[ 'webdriver.remote.sessionid' ]; saucelabs.updateJob( sessionid, { passed: this.currentTest.results.failed === 0 }, () => {}); return this; };
LaxarJS/shop-demo
nightwatch-tests/lib/custom_commands/reportToSauce.js
JavaScript
mit
425
using System.Web.Http; using System.Web.Mvc; namespace Windays.Web.Api.Areas.HelpPage { public class HelpPageAreaRegistration : AreaRegistration { public override string AreaName { get { return "HelpPage"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "HelpPage_Default", "Help/{action}/{apiId}", new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); HelpPageConfig.Register(GlobalConfiguration.Configuration); } } }
rjovic/Windays2015
Windays.Web.Api/Areas/HelpPage/HelpPageAreaRegistration.cs
C#
mit
673
package buyer; /** * This class is a re-work of the given Buyer interface within the original BuyerImpl class. * ============================================================================================ * The goal of the rework is to represent a generic type of Buyer. * ============================================================================================ * However, subclasses may define more specific types of Buyers. * ============================================================================================ * @param name - The name of the new Buyer * ============================================================================================ * @param type - The 'type' of new Buyer (normally 'cash' or normally 'credit') * ============================================================================================ * @author Original: Laureate Development Team * ============================================================================================ * @author Subsequent annotations and changes rwebaz http://about.me/rwebaz */ import java.util.ArrayList; import java.util.List; import product.Product; public class BuyerImplements extends Buyer implements BuyerInterface { // This class implements the BuyerInterface /* Declare the 'instance' variables that are accessible to the class. * The BuyerImplements class (instance) variables are: */ protected String null_buyer; protected String name; protected int buyerLimit; protected String pay; protected String categoryName; protected String itemProduct; // Create the primary constructor for all future instances of the 'BuyerImplements' class public BuyerImplements(String b_name, String b_id, int b_limit) { // Choose one... super(buyerName, buyerType); // super(categoryName, itemProduct); /* Rename the class variables to accommodate constructor 'this' and to... instantiate the variables as 'local' variables of the constructor method Buyer */ buyerName = b_name; buyerId = b_id; buyerLimit = b_limit; } // Other methods public static void addBuyer(Buyer buyer) { buyers.add(buyer); } // The shopping cart that contains all the items this Buyer has purchased. private List<Product> shoppingCart = new ArrayList<Product>(); // Methods that point to the contract interface w the 'BuyerInterface' class @Override // per contract w interface 'BuyerInterface' @Override public String getBuyerName() { return buyerName; } @Override // per contract w interface 'BuyerInterface' public String getBuyerType() { return buyerType; } // per contract w interface 'BuyerInterface' public String buyerPayForItem1() { pay = "The buyer " + getBuyerName() + " is now paying by " + getBuyerType() + "..."; System.out.println("A.) " + pay); return pay; } // per contract w interface 'BuyerInterface' @Override // Display this Buyer and some of its information as a String. public String toString() { String str = getBuyerName() + " wants to buy "; for (String productName : shoppingList) { str += productName + " "; } str += " has purchased "; for (Product product : shoppingCart) { str += product.getCategoryName() + " "; } return str; } // Pay for the item that the Buyer is purchasing // @param item - the Product that is being purchased public void payForItem1(Product item) { System.out.println(getBuyerName() + " is paying for item " + item.getCategoryName()); addItemToCart(item); } // Add an item to the shopping list // @param itemName - the name of the item to add to the shopping list public void addItemToShoppingList1(String itemName) { shoppingList.add(itemName); } // Add a Product to the shopping cart. // @param item the Product to add to the shopping cart public void addItemToCart1(Product item) { shoppingCart.add(item); } @Override public String buyerPayForItem() { // TODO Auto-generated method stub return null; } @Override public void payForItem(Product item) { // TODO Auto-generated method stub } @Override public void addItemToShoppingList(String itemName) { // TODO Auto-generated method stub } @Override public void addItemToCart(Product item) { // TODO Auto-generated method stub } // The list of registered Buyers. public static List<Buyer> buyers = new ArrayList<Buyer>(); // Get the shopping list of items that the Buyer wants to purchase. // @return the list of items in the shopping list @Override public List<String> getShoppingList() { return shoppingList; } /* Attempt to locate the Products that the Buyers are looking for. * When the Product is located, the Broker arranges for the Seller * to sell the Product, and for the Buyer to pay for it. */ // Locate a Seller who can provide the desired Product. // @param itemName - the name of the Product // @return - the Product, if a Seller is located null, if no Seller provides this Product public Product findItem(String itemName) { Product item = null; // for (Seller seller : sellers) { // if (seller.provideProduct(itemName)) { // item = seller.sellProduct(); // break; } } return item; } // The shopping list array that contains all the items this Buyer wants to purchase private List<String> shoppingList = new ArrayList<String>(); public void findItemsForBuyers() { for (Buyer buyer : buyers) { for (String productName : this.getShoppingList()) { String itemName = productName; Product theProduct = findItem(itemName); // Nest If loop in 1st For loop if (theProduct != null) { buyer.payForItem(theProduct); } // Close 2nd For loop } } } // Display the list of registered Buyers public static void displayBuyers() { System.out.println(); System.out.println("The buyers:"); for (Buyer buyer : buyers) { System.out.println(buyer.toString()); } System.out.println(""); } }
rwebaz/Simple-Java
src/TestNewPackage/src/buyer/BuyerImplements.java
Java
mit
6,598
daily ===== a tiny little computer-time clock that counts down while your machine is in use
dxnn/daily
README.md
Markdown
mit
93
/* * This file is part of ClassGraph. * * Author: Luke Hutchison * * Hosted at: https://github.com/classgraph/classgraph * * -- * * The MIT License (MIT) * * Copyright (c) 2019 Luke Hutchison * * Permission is hereby granted, free of charge, to any person obtaining 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, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 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. */ package nonapi.io.github.classgraph.fastzipfilereader; import java.io.IOException; import java.util.Calendar; import java.util.TimeZone; import nonapi.io.github.classgraph.fileslice.Slice; import nonapi.io.github.classgraph.fileslice.reader.RandomAccessReader; import nonapi.io.github.classgraph.utils.VersionFinder; /** A zip entry within a {@link LogicalZipFile}. */ public class FastZipEntry implements Comparable<FastZipEntry> { /** The parent logical zipfile. */ final LogicalZipFile parentLogicalZipFile; /** The offset of the entry's local header, as an offset relative to the parent logical zipfile. */ private final long locHeaderPos; /** The zip entry path. */ public final String entryName; /** True if the zip entry is deflated; false if the zip entry is stored. */ final boolean isDeflated; /** The compressed size of the zip entry, in bytes. */ public final long compressedSize; /** The uncompressed size of the zip entry, in bytes. */ public final long uncompressedSize; /** The last modified millis since the epoch, or 0L if it is unknown */ private long lastModifiedTimeMillis; /** The last modified time in MSDOS format, if {@link FastZipEntry#lastModifiedTimeMillis} is 0L. */ private final int lastModifiedTimeMSDOS; /** The last modified date in MSDOS format, if {@link FastZipEntry#lastModifiedTimeMillis} is 0L. */ private final int lastModifiedDateMSDOS; /** The file attributes for this resource, or 0 if unknown */ public final int fileAttributes; /** The {@link Slice} for the zip entry's raw data (which can be either stored or deflated). */ private Slice slice; /** * The version code (&gt;= 9), or 8 for the base layer or a non-versioned jar (whether JDK 7 or 8 compatible). */ final int version; /** * The unversioned entry name (i.e. entryName with "META_INF/versions/{versionInt}/" stripped) */ public final String entryNameUnversioned; // ------------------------------------------------------------------------------------------------------------- /** * Constructor. * * @param parentLogicalZipFile * The parent logical zipfile containing this entry. * @param locHeaderPos * The offset of the LOC header for this entry within the parent logical zipfile. * @param entryName * The name of the entry. * @param isDeflated * True if the entry is deflated; false if the entry is stored. * @param compressedSize * The compressed size of the entry. * @param uncompressedSize * The uncompressed size of the entry. * @param lastModifiedTimeMillis * The last modified date/time in millis since the epoch, or 0L if unknown (in which case, the MSDOS * time and date fields will be provided). * @param lastModifiedTimeMSDOS * The last modified date, in MSDOS format, if lastModifiedMillis is 0L. * @param lastModifiedDateMSDOS * The last modified date, in MSDOS format, if lastModifiedMillis is 0L. * @param fileAttributes * The POSIX file attribute bits from the zip entry. */ FastZipEntry(final LogicalZipFile parentLogicalZipFile, final long locHeaderPos, final String entryName, final boolean isDeflated, final long compressedSize, final long uncompressedSize, final long lastModifiedTimeMillis, final int lastModifiedTimeMSDOS, final int lastModifiedDateMSDOS, final int fileAttributes) { this.parentLogicalZipFile = parentLogicalZipFile; this.locHeaderPos = locHeaderPos; this.entryName = entryName; this.isDeflated = isDeflated; this.compressedSize = compressedSize; this.uncompressedSize = !isDeflated && uncompressedSize < 0 ? compressedSize : uncompressedSize; this.lastModifiedTimeMillis = lastModifiedTimeMillis; this.lastModifiedTimeMSDOS = lastModifiedTimeMSDOS; this.lastModifiedDateMSDOS = lastModifiedDateMSDOS; this.fileAttributes = fileAttributes; // Get multi-release jar version number, and strip any version prefix int entryVersion = 8; String entryNameWithoutVersionPrefix = entryName; if (entryName.startsWith(LogicalZipFile.MULTI_RELEASE_PATH_PREFIX) && entryName.length() > LogicalZipFile.MULTI_RELEASE_PATH_PREFIX.length() + 1) { // This is a multi-release jar path final int nextSlashIdx = entryName.indexOf('/', LogicalZipFile.MULTI_RELEASE_PATH_PREFIX.length()); if (nextSlashIdx > 0) { // Get path after version number, i.e. strip "META-INF/versions/{versionInt}/" prefix final String versionStr = entryName.substring(LogicalZipFile.MULTI_RELEASE_PATH_PREFIX.length(), nextSlashIdx); // For multi-release jars, the version number has to be an int >= 9 // Integer.parseInt() is slow, so this is a custom implementation (this is called many times // for large classpaths, and Integer.parseInt() was a bit of a bottleneck, surprisingly) int versionInt = 0; if (versionStr.length() < 6 && !versionStr.isEmpty()) { for (int i = 0; i < versionStr.length(); i++) { final char c = versionStr.charAt(i); if (c < '0' || c > '9') { versionInt = 0; break; } if (versionInt == 0) { versionInt = c - '0'; } else { versionInt = versionInt * 10 + c - '0'; } } } if (versionInt != 0) { entryVersion = versionInt; } // Set version to 8 for out-of-range version numbers or invalid paths if (entryVersion < 9 || entryVersion > VersionFinder.JAVA_MAJOR_VERSION) { entryVersion = 8; } if (entryVersion > 8) { // Strip version path prefix entryNameWithoutVersionPrefix = entryName.substring(nextSlashIdx + 1); // For META-INF/versions/{versionInt}/META-INF/*, don't strip version prefix: // "The intention is that the META-INF directory cannot be versioned." // http://mail.openjdk.java.net/pipermail/jigsaw-dev/2018-October/013954.html if (entryNameWithoutVersionPrefix.startsWith(LogicalZipFile.META_INF_PATH_PREFIX)) { entryVersion = 8; entryNameWithoutVersionPrefix = entryName; } } } } this.version = entryVersion; this.entryNameUnversioned = entryNameWithoutVersionPrefix; } // ------------------------------------------------------------------------------------------------------------- /** * Lazily get zip entry slice -- this is deferred until zip entry data needs to be read, in order to avoid * randomly seeking within zipfile for every entry as the central directory is read. * * @return the offset within the physical zip file of the entry's start offset. * @throws IOException * If an I/O exception occurs. */ public Slice getSlice() throws IOException { if (slice == null) { final RandomAccessReader randomAccessReader = parentLogicalZipFile.slice.randomAccessReader(); // Check header magic if (randomAccessReader.readInt(locHeaderPos) != 0x04034b50) { throw new IOException("Zip entry has bad LOC header: " + entryName); } final long dataStartPos = locHeaderPos + 30 + randomAccessReader.readShort(locHeaderPos + 26) + randomAccessReader.readShort(locHeaderPos + 28); if (dataStartPos > parentLogicalZipFile.slice.sliceLength) { throw new IOException("Unexpected EOF when trying to read zip entry data: " + entryName); } // Create a new Slice that wraps just the data of the zip entry, and mark whether it is deflated slice = parentLogicalZipFile.slice.slice(dataStartPos, compressedSize, isDeflated, uncompressedSize); } return slice; } // ------------------------------------------------------------------------------------------------------------- /** * Get the path to this zip entry, using "!/" as a separator between the parent logical zipfile and the entry * name. * * @return the path of the entry */ public String getPath() { return parentLogicalZipFile.getPath() + "!/" + entryName; } /** * Get the last modified time in Epoch millis, or 0L if unknown. * * @return the last modified time in Epoch millis. */ public long getLastModifiedTimeMillis() { // If lastModifiedTimeMillis is zero, but there is an MSDOS date and time available if (lastModifiedTimeMillis == 0L && (lastModifiedDateMSDOS != 0 || lastModifiedTimeMSDOS != 0)) { // Convert from MS-DOS Date & Time Format to Epoch millis final int lastModifiedSecond = (lastModifiedTimeMSDOS & 0b11111) * 2; final int lastModifiedMinute = lastModifiedTimeMSDOS >> 5 & 0b111111; final int lastModifiedHour = lastModifiedTimeMSDOS >> 11; final int lastModifiedDay = lastModifiedDateMSDOS & 0b11111; final int lastModifiedMonth = (lastModifiedDateMSDOS >> 5 & 0b111) - 1; final int lastModifiedYear = (lastModifiedDateMSDOS >> 9) + 1980; final Calendar lastModifiedCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); lastModifiedCalendar.set(lastModifiedYear, lastModifiedMonth, lastModifiedDay, lastModifiedHour, lastModifiedMinute, lastModifiedSecond); lastModifiedCalendar.set(Calendar.MILLISECOND, 0); // Cache converted time by overwriting the zero lastModifiedTimeMillis field lastModifiedTimeMillis = lastModifiedCalendar.getTimeInMillis(); } // Return the last modified time, or 0L if it is totally unknown. return lastModifiedTimeMillis; } /** * Sort in decreasing order of version number, then lexicographically increasing order of unversioned entry * path. * * @param o * the object to compare to * @return the result of comparison */ @Override public int compareTo(final FastZipEntry o) { final int diff0 = o.version - this.version; if (diff0 != 0) { return diff0; } final int diff1 = entryNameUnversioned.compareTo(o.entryNameUnversioned); if (diff1 != 0) { return diff1; } final int diff2 = entryName.compareTo(o.entryName); if (diff2 != 0) { return diff2; } // In case of multiple entries with the same entry name, return them in consecutive order of location, // so that the earliest entry overrides later entries (this is an arbitrary decision for consistency) final long diff3 = locHeaderPos - o.locHeaderPos; return diff3 < 0L ? -1 : diff3 > 0L ? 1 : 0; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return parentLogicalZipFile.hashCode() ^ version ^ entryName.hashCode() ^ (int) locHeaderPos; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } else if (!(obj instanceof FastZipEntry)) { return false; } final FastZipEntry other = (FastZipEntry) obj; return this.parentLogicalZipFile.equals(other.parentLogicalZipFile) && this.compareTo(other) == 0; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "jar:file:" + getPath(); } }
lukehutch/fast-classpath-scanner
src/main/java/nonapi/io/github/classgraph/fastzipfilereader/FastZipEntry.java
Java
mit
13,768
<div class="commune_descr limited"> <p> Fraissinet-de-Lozère est un village géographiquement positionné dans le département de Lozère en Languedoc-Roussillon. Elle totalisait 216 habitants en 2008.</p> <p>À coté de Fraissinet-de-Lozère sont situées les villes de <a href="{{VLROOT}}/immobilier/salle-prunet_48186/">La&nbsp;Salle-Prunet</a> localisée à 9&nbsp;km, 137 habitants, <a href="{{VLROOT}}/immobilier/bleymard_48027/">Le&nbsp;Bleymard</a> à 12&nbsp;km, 367 habitants, <a href="{{VLROOT}}/immobilier/bedoues_48022/">Bédouès</a> localisée à 8&nbsp;km, 314 habitants, <a href="{{VLROOT}}/immobilier/cocures_48050/">Cocurès</a> située à 6&nbsp;km, 194 habitants, <a href="{{VLROOT}}/immobilier/mas-dorcieres_48093/">Mas-d'Orcières</a> localisée à 11&nbsp;km, 139 habitants, <a href="{{VLROOT}}/immobilier/saint-maurice-de-ventalon_48172/">Saint-Maurice-de-Ventalon</a> localisée à 11&nbsp;km, 68 habitants, entre autres. De plus, Fraissinet-de-Lozère est située à seulement 22&nbsp;km de <a href="{{VLROOT}}/immobilier/mende_48095/">Mende</a>.</p> <p>Si vous envisagez de demenager à Fraissinet-de-Lozère, vous pourrez aisément trouver une maison à acheter. </p> <p>Le parc de logements, à Fraissinet-de-Lozère, était réparti en 2011 en treize appartements et 228 maisons soit un marché plutôt équilibré.</p> <p>La ville compte quelques équipements sportifs, elle dispose, entre autres, de une boucle de randonnée.</p> </div>
donaldinou/frontend
src/Viteloge/CoreBundle/Resources/descriptions/48066.html
HTML
mit
1,490
class ScopedTagsMigration < ActiveRecord::Migration def self.up create_table :tags do |t| t.string :name t.string :context end create_table :taggings do |t| t.references :tag t.references :taggable, :polymorphic => true end add_index "tags", ['context', 'name'] add_index "taggings", ['taggable_id', 'taggable_type'] end def self.down drop_table :taggings drop_table :tags end end
joshk/scoped-tags
generators/scoped_tags_migration/templates/migration.rb
Ruby
mit
450
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <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.8"/> <title>Faeris: 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/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.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">Faeris &#160;<span id="projectnumber">v3.2</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.8 --> <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 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="inherits.html"><span>Class&#160;Hierarchy</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)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">ProgramSourceMgr Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>add</b>(const char *name, Resource *res) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>addCache</b>(FsString *name, Resource *res) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>addRef</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>addSearchPath</b>(const char *path) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>autoDestroy</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>className</b>() (defined in <a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a>)</td><td class="entry"><a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>clearCache</b>() (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>create</b>() (defined in <a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a>)</td><td class="entry"><a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>createFile</b>(const char *filename) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>decRef</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>destroy</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>dropScriptData</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>dump</b>() (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>equal</b>(FsObject *ob) (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>existSearchPath</b>(const char *path) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>finalize</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>findFromCache</b>(FsString *name) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>FS_CLASS_DECLARE</b>(FsObject) (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>FsObject</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>getAttribute</b>(const char *name) (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getCacheResourceNu</b>() (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>getHashCode</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getObjectNu</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>getRefDelete</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>getUserData</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>load</b>(const char *name) (defined in <a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a>)</td><td class="entry"><a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>loadPreDefineShader</b>() (defined in <a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a>)</td><td class="entry"><a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>m_caches</b> (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>m_func</b> (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>m_scriptData</b> (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>m_searchPaths</b> (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>onFinalize</b> (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>pathPos</b>(const char *path) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>preloadResource</b>(const char *path) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ProgramSourceMgr</b>() (defined in <a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a>)</td><td class="entry"><a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>refCnt</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>remove</b>(Resource *res) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>removeCache</b>(FsString *key) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>removeSearchPath</b>(const char *path) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ResourceCreateFunc</b> typedef (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ResourceMgr</b>(ResourceCreateFunc func) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>setAttribute</b>(const char *name, const FsVariant &amp;v) (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>setAttributes</b>(FsDict *dict) (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>setRefDelete</b>(bool value) (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>setUserData</b>(void *data) (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>unload</b>(const char *path, bool force=false) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>unloadAll</b>(bool force=false) (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~FsObject</b>() (defined in <a class="el" href="class_fs_object.html">FsObject</a>)</td><td class="entry"><a class="el" href="class_fs_object.html">FsObject</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>~ProgramSourceMgr</b>() (defined in <a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a>)</td><td class="entry"><a class="el" href="class_program_source_mgr.html">ProgramSourceMgr</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~ResourceMgr</b>() (defined in <a class="el" href="class_resource_mgr.html">ResourceMgr</a>)</td><td class="entry"><a class="el" href="class_resource_mgr.html">ResourceMgr</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Jan 23 2015 17:58:37 for Faeris by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.8 </small></address> </body> </html>
FSource/FDesign-Document
doxygen/html/class_program_source_mgr-members.html
HTML
mit
18,517
/* * Clearest Framework * Provided under MIT License. * Copyright (c) 2012-2015 Illya Kokshenev <sou@illya.com.br> */ /** * Created by M0nZDeRR on 30/10/2015. */ var chai = require("chai"), expect = chai.expect, commons = require("../../core/commons"), inside = commons.inside, Serializer = require("../../tool/serializer.js"); describe("tool / serializer", function(){ it("should serialize simple elements",function(){ var ser = new Serializer(); expect(ser.serialize(undefined)).to.be.equal("undefined"); expect(ser.serialize(null)).to.be.equal("null"); expect(ser.serialize(42)).to.be.equal('42'); expect(ser.serialize('foo')).to.be.equal('"foo"'); }); it("should serialize objects, functions and call custom serializers",function(){ var ser = new Serializer(); var f = function (a,b,c){return a+b+c}; expect(ser.serialize(f)).to.be.equal(f.toString()); expect(ser.serialize({})).to.be.equal('{}'); expect(ser.serialize({foo:42})).to.be.equal('{foo:42}'); expect(ser.serialize({foo:"42"})).to.be.equal('{foo:"42"}'); var o={}; inside(o).serialize = function(ser){return ser.serialize('custom!');} expect(ser.serialize(o)).to.be.equal('"custom!"'); }); //it("should serialize recursive references ") });
m0nzderr/clearest
test/tool/serializer.js
JavaScript
mit
1,355
angular.module('checkoutModule') .controller('checkoutAccordionController', [ '$scope', '$location', '$q', '$timeout', '_', 'checkoutApiService', 'visitorLoginService', 'cartService', 'commonUtilService', 'checkoutService', 'giftcardsApiService', function ( $scope, $location, $q, $timeout, _, checkoutApiService, visitorLoginService, cartService, commonUtilService, checkoutService, giftcardsApiService ) { var isValidSteps = { 'billingAddress': false, 'shippingAddress': false, 'shippingMethod': false, 'paymentMethod': false, 'discounts': true }; // General $scope.checkoutService = checkoutService; $scope.cart = cartService; $scope.checkout = {}; $scope.isGuestCheckout = false; $scope.getOptionLabel = commonUtilService.getOptionLabel; // Accordion navigation $scope.back = back; $scope.next = next; $scope.save = save; // Addresses $scope.addressSettings = { useShippingAsBilling: true }; $scope.newBilling = newBilling; $scope.newShipping = newShipping; $scope.choiceBilling = choiceBilling; $scope.choiceShipping = choiceShipping; // Shipping method $scope.shippingMethod = { selected: false }; $scope.shippingMethods = []; // REFACTOR: nest under shippingMethod as options // Billing Method $scope.paymentMethod = { selected: false }; $scope.paymentMethods = []; // REFACTOR: nest under paymentMethod as options // Discounts and Giftcards $scope.discounts = { apply: applyDiscount, remove: removeDiscount, code: '', isVisible: false, message: false, isApplying: false, }; $scope.canRemoveDiscount = canRemoveDiscount; activate(); ///////////////////// function activate() { // Load checkout, and refresh cart info(); // Load the user visitorLoginService.isLoggedIn().then(function(isLoggedIn){ // Show the first step if (isLoggedIn) { $('#shippingAddress .panel-body').show(); } // Guest checkout isn't enabled, and they aren't logged in, bounce 'em if (!isGuestCheckoutEnabled() && !isLoggedIn) { commonUtilService.addFlashMessage('Please log in or register to enter checkout.', 'info'); return $location.path('/registration'); } $scope.isGuestCheckout = (isLoggedIn === false); // They are logged in, check if we have any addresses on file getAddresses(); }); checkoutService.loadSavedCC().then(function( res ){ if (res !== null){ var result = _.uniq(res, 'ID'); $scope.paymentMethods = $scope.paymentMethods.concat(result); } }); // Load payment methods checkoutService.loadPaymentMethods().then(function(methods){ //merge payment methods and tokens; $scope.paymentMethods = methods.concat($scope.paymentMethods); }); $scope.$emit('add-breadcrumbs', {'label': 'Checkout', 'url': '/checkout'}); } /** * Gets checkout information, makes sure the cart is up to date * @return {promise} */ function info() { return checkoutService.update().then(function (checkout) { $scope.checkout = checkout; initAddressesData(); return cartService.reload().then(function(){ // If they don't have any items in cart redirect to the empty cart page if (cartService.getCountItems() === 0) { return $location.path('/cart'); } }); }); function initAddressesData() { if ($scope.checkout.shipping_address === null) { $scope.checkout.shipping_address = getDefaultAddress(); } if ($scope.checkout.billing_address === null) { $scope.checkout.billing_address = getDefaultAddress(); } } } function getDefaultAddress() { return { 'street': '', 'city': '', 'state': '', 'phone': '', 'zip_code': '', 'company': '', 'first_name': '', 'last_name': '', 'address_line1': '', 'address_line2': '', 'country': 'US' }; } function isGuestCheckoutEnabled() { return angular.appConfig.hasGuestCheckout; } /** * Gets visitor addresses */ function getAddresses() { return checkoutApiService.getAddresses().$promise .then(function (response) { var result = response.result || []; $scope.addresses = result; }); } // REFACTOR: we should just be able to use the $scope.paymentMethod.selected object function getPaymentInfo() { var info = { 'method': null, 'form': null }; info.method = $scope.paymentMethod.selected; info.form = $scope.paymentMethod.selected.form; return info; } function newBilling() { // Sets a flag of form is not valid isValidSteps.billingAddress = false; // Initialise address by default $scope.checkout.billing_address = getDefaultAddress(); $scope.addressSettings.useShippingAsBilling = false; for (var field in $scope.checkout.billing_address) { if ($scope.billingAddress.hasOwnProperty(field)) { $scope.billingAddress[field].$pristine = true; $scope.billingAddress[field].$invalid = false; } } } function newShipping() { // Sets a flag of form is not valid isValidSteps.shippingAddress = false; // Initialise address by default $scope.checkout.shipping_address = getDefaultAddress(); for (var field in $scope.checkout.shipping_address) { if ($scope.shippingAddress.hasOwnProperty(field)) { $scope.shippingAddress[field].$pristine = true; $scope.shippingAddress[field].$invalid = false; } } } // REFACTOR: This is currently only used for saved addresses, and probably isn't needed function choiceBilling(billingId) { // TODO: [aknox] these top level conditions can't be right, // why would we look at the shippingAddress form validity if ($scope.isGuestCheckout && $scope.shippingAddress.$valid) { checkoutService.saveBillingAddress($scope.checkout.shipping_address).then( function (response) { if (response.error === null) { isValidSteps.billingAddress = true; } } ); } else if ($scope.checkout.billing_address !== null && $scope.checkout.billing_address._id !== billingId && typeof billingId === 'string' && billingId !== '') { // Sets existing address as billing checkoutService.saveBillingAddress({'id': billingId}).then( function (response) { if (response.error === null) { isValidSteps.billingAddress = true; } } ); } else { if ($scope.shippingAddress.$valid) { checkoutService.saveBillingAddress($scope.checkout.shipping_address).then( function (response) { if (response.error === null) { isValidSteps.billingAddress = true; } } ); } } } // REFACTOR: This is currently only used for saved addresses, and probably isn't needed function choiceShipping (shippingId) { if ($scope.isGuestCheckout) { checkoutService.saveShippingAddress($scope.checkout.shipping_address).then( function (response) { // update checkout info().then(function () { // if all ok, must update allowed shipping methods list // and must set billing address if set appropriate checkbox if (response.error === null) { checkoutService.loadShippingMethods().then(function (methods) { $scope.shippingMethods = methods; $scope.shippingMethod.selected = $scope.shippingMethods[0]; // select first option }); // sets billing address if ($scope.addressSettings.useShippingAsBilling) { $scope.choiceBilling(response.result); } } }); } ); } else if (($scope.checkout.shipping_address !== null && $scope.checkout.shipping_address._id !== shippingId) || Boolean(shippingId)) { // Sets existing address as shipping checkoutService.saveShippingAddress({'id': shippingId}).then( function (response) { // update checkout info().then(function () { // if all ok, must update allowed shipping methods list // and must set billing address if set appropriate checkbox if (response.error === null) { isValidSteps.shippingAddress = true; checkoutService.loadShippingMethods().then(function (methods) { $scope.shippingMethods = methods; $scope.shippingMethod.selected = $scope.shippingMethods[0]; // select first option }); // sets billing address if ($scope.addressSettings.useShippingAsBilling) { $scope.choiceBilling(response.result._id); } } else { isValidSteps.billingAddress = false; } }); } ); } } var _scrollTo = function($step){ $('html, body').animate({ scrollTop: $step.offset().top }, 100); }; function back(step) { var $thisStep = $('#' + step); var $lastStep = $thisStep.prev('.panel'); // We can start scrolling to the panel before animations finish because the // distance from the top won't change _scrollTo($lastStep); $thisStep.find('.panel-body').slideUp(500); $lastStep.find('.panel-body').slideDown(500); } function next(step) { var _accordionAnimation = function(step, skipOneStep) { var $thisStep = $('#' + step); var $nextStep = $thisStep.next('.panel'); if (skipOneStep) { $nextStep = $thisStep.next('.panel').next('.panel'); } $thisStep.find('.panel-body').slideUp(600, function(){ _scrollTo($nextStep); }); $nextStep.find('.panel-body').slideDown(500); }; var actionBillingAddress = function () { if ($scope.billingAddress.$valid) { isValidSteps.billingAddress = true; // REFACTOR: this condition could be worded better if ( ( !Boolean($scope.checkout.billing_address._id) && !$scope.isGuestCheckout ) || $scope.isGuestCheckout ) { checkoutService.saveBillingAddress($scope.checkout.billing_address) .then(function () { getAddresses(); //TODO: not sure this is necessary // update checkout info(); _accordionAnimation(step); }); } else { //TODO: Confirm that this is expected _accordionAnimation(step); } } }; var actionShippingAddress = function () { if ($scope.shippingAddress.$valid) { isValidSteps.shippingAddress = true; //always persist shipping address in case there are shipping notes checkoutService.saveShippingAddress($scope.checkout.shipping_address) .then(function () { getAddresses(); //TODO: not sure this is necessary checkoutService.loadShippingMethods().then(function (methods) { $scope.shippingMethods = methods; // select first option $scope.shippingMethod.selected = $scope.shippingMethods[0]; }); if ($scope.addressSettings.useShippingAsBilling) { checkoutService.saveBillingAddress($scope.checkout.shipping_address) .then(function (response) { if (response.error === null) { isValidSteps.billingAddress = true; } // update checkout info(); // skip billing address step var skipOneStep = true; _accordionAnimation(step, skipOneStep); }); } else { // update checkout info(); // open billing address _accordionAnimation(step); } }); } }; var actionShippingMethod = function() { checkoutService.saveShippingMethod({ 'method': $scope.shippingMethod.selected.Method, 'rate': $scope.shippingMethod.selected.Rate }).then(function (response) { if (response.result === 'ok') { // update checkout info(); isValidSteps.shippingMethod = true; _accordionAnimation(step); } }); }; var actionPaymentMethod = function () { isValidSteps.paymentMethod = false; // Zero dollar, proceed if ($scope.checkout.grandtotal <= 0) { isValidSteps.paymentMethod = true; info(); _accordionAnimation(step); } if ($scope.paymentMethod.selected) { if ($scope.paymentMethod.selected.isCreditCard) { var payment = getPaymentInfo(); payment.method.form.$submitted = true; if (payment.method.form.$valid) { // Save off the method name checkoutService.savePaymentMethod({ method: $scope.paymentMethod.selected.Code }); // Save off the cc form checkoutService.saveAdditionalInfo({'cc': payment.method.cc}) .then(function(resp){ if (resp.result === 'ok') { // Update the checkout object and proceed isValidSteps.paymentMethod = true; info(); _accordionAnimation(step); } }); } } else if ($scope.paymentMethod.selected.ID){ //if method is saved token var payment = getPaymentInfo(); // Save off the method name checkoutService.savePaymentMethod({ method: $scope.paymentMethod.selected.Desc }); // Save off the cc form checkoutService.saveAdditionalInfo({ 'cc': { 'id': $scope.paymentMethod.selected.ID } }).then(function(resp){ if (resp.result === 'ok') { // Update the checkout object and proceed isValidSteps.paymentMethod = true; info(); _accordionAnimation(step); } }); } else { // not a cc just continue checkoutService.savePaymentMethod({ method: $scope.paymentMethod.selected.Code }) .then(function(resp){ // update the checkout object and proceed if (resp.result === 'ok') { isValidSteps.paymentMethod = true; info(); _accordionAnimation(step); } }); } } }; var actionCustomerAdditionalInfo = function () { // isValidSteps isn't used for this step if ($scope.isGuestCheckout && $scope.customerInfo.$valid) { checkoutService.saveAdditionalInfo({ 'customer_email': $scope.checkout.info.customer_email, 'customer_name': $scope.checkout.info.customer_name }).then(function () { info(); _accordionAnimation(step); }); } }; var actionDefault = function () { if (isValidSteps[step]) { _accordionAnimation(step); } }; switch (step) { case 'billingAddress': actionBillingAddress(); break; case 'shippingAddress': actionShippingAddress(); break; case 'shippingMethod': actionShippingMethod(); break; case 'paymentMethod': actionPaymentMethod(); break; case 'customerInfo': actionCustomerAdditionalInfo(); break; default: actionDefault(); } }// jshint ignore:line /** * Saves checkout */ function save() { $scope.isProcessingOrder = true; var payment, isValid, sendPostForm; $scope.message = ''; isValid = function () { var result, message, getErrorMsg; message = ''; result = { status: true, message: '', }; getErrorMsg = function (step) { /*jshint maxcomplexity:6 */ var msg = 'Please fill all required fields'; switch (step) { case 'billingAddress': msg = 'Please fill all required fields in billing section <br />'; break; case 'shippingAddress': msg = 'Please fill all required fields in shipping section <br />'; break; case 'shippingMethod': msg = 'Please choose shipping method <br />'; break; case 'paymentMethod': msg = 'Please choose payment method <br />'; break; case 'additionalInfo': msg = 'Please fill all required fields in additional section <br />'; break; } return msg; }; for (var step in isValidSteps) { if (isValidSteps.hasOwnProperty(step) && !isValidSteps[step]) { message += getErrorMsg(step); result = { status: false, message: message }; } } return result; }; sendPostForm = function (method, response) { var form; form = "<div class='hidden' id='auth_net_form'>" + response.result + '</div>'; form = form.replace('$CC_NUM', method.cc.number); form = form.replace('$CC_MONTH', method.cc.expire_month); form = form.replace('$CC_YEAR', method.cc.expire_year); $('body').append(form); $('#auth_net_form').find('form').submit(); $('#auth_net_form').remove(); }; payment = getPaymentInfo(); if (payment.form !== null && typeof payment.form !== 'undefined') { payment.form.submited = true; } info().then(function () { var checkoutValid = isValid(); if (checkoutValid.status) { $(this).parents('.confirm').css('display', 'none'); $('#processing').modal('show'); checkoutApiService.save().$promise .then(function(response) { if (response.error === null) { var isRemote = (null !== payment.method && payment.method.Type === 'remote' && response.result === 'redirect'); var isPostCC = (null !== payment.method && payment.method.Type === 'post_cc'); if (isRemote) { // PayPal Express window.location.replace(response.redirect); $scope.isProcessingOrder = false; } else if (isPostCC) { // Auth.net sendPostForm(payment.method, response); $scope.isProcessingOrder = false; } else { // All Others; Zero Dollar, PayFlow Pro info().then(function() { var purchase = response.result || {}; //TODO: clean this up with angular modals and promises $('#processing').modal('hide'); $timeout(function() { $scope.isProcessingOrder = false; $location.path('/checkout/success/' + purchase._id); }, 600); }); } } else { // Errors from server $(this).parents('.confirm').css('display', 'block'); $('#processing').modal('hide'); $scope.message = commonUtilService.getMessage(response); $scope.isProcessingOrder = false; } }); } else { $(this).parents('.confirm').css('display', 'block'); $('#processing').modal('hide'); $scope.message = commonUtilService.getMessage(null, 'danger', checkoutValid.message); } }); } function applyDiscount() { var errorMessage = 'The coupon code or giftcard code entered is not valid at this time.'; var validationMessage = 'Please enter a coupon code or a giftcard code.'; var code = $scope.discounts.code; var promises = []; // Clear old messaging $scope.discounts.message = false; if (!code) { $scope.discounts.message = commonUtilService.getMessage(null, 'danger', validationMessage); return; } // Prevent double submission if ($scope.discounts.isApplying) { return; } $scope.discounts.isApplying = true; // Apply this as a giftcard and a coupon promises.push(giftcardsApiService.apply({'giftcode': code})); promises.push(checkoutService.discountApply({'code': code})); allResolved(promises).then(function(responses){ $scope.discounts.isApplying = false; var respSuccess = _.filter(responses, {'error': null}); if (respSuccess.length) { $scope.discounts.code = ''; info(); } else { $scope.discounts.message = commonUtilService.getMessage(null, 'danger', errorMessage); } }); // NOTE: $q.all will reject if one of the promises is bad, so we can't use it here // and have instead replicateed $Q.allResolved function allResolved(promises) { var deferred = $q.defer(), counter = 0, results = []; angular.forEach(promises, function(promise, key) { counter++; $q.when(promise).then(function(value) { if (results.hasOwnProperty(key)) { return; } results[key] = value; if (!(--counter)) { deferred.resolve(results); } }, function(reason) { if (results.hasOwnProperty(key)) { return; } results[key] = reason.data; if (!(--counter)) { deferred.resolve(results); } }); }); if (counter === 0) { deferred.resolve(results); } return deferred.promise; } } function canRemoveDiscount(discount) { if (!discount || !discount.Labels || !discount.Labels[0]) return false; var removableDiscountTypes = { 'D': true, 'GC': true }; return discount.Labels[0] in removableDiscountTypes; } function removeDiscount(discount){ if (!discount.Labels || !discount.Labels[0]) return; var discountType = discount.Labels[0]; var errorMessage = 'Removing of coupon code or giftcard code is not avalable at this time.'; var giftcardMessage = 'Your giftcard was removed successfully!'; var couponMessage = 'Your coupon code was removed successfully!'; switch(discountType) { // type Discount case 'D': checkoutApiService.removeDiscount({'code': discount.Code}).$promise .then(function(response) { if (response.error === null) { info(); $scope.discounts.code = ''; $scope.discounts.message = commonUtilService.getMessage(null, 'success', couponMessage); } else { $scope.discounts.message = commonUtilService.getMessage(null, 'danger', errorMessage); } }); break; // type gift-card case 'GC': giftcardsApiService.remove({'giftcode': discount.Code}).$promise .then(function(response) { if (response.error === null) { info(); $scope.discounts.code = ''; $scope.discounts.message = commonUtilService.getMessage(null, 'success', giftcardMessage); } else { $scope.discounts.message = commonUtilService.getMessage(null, 'danger', errorMessage); } }); break; } } } ]);
ottemo/ultimo
src/app/checkout/accordion.controller.js
JavaScript
mit
31,464
__author__ = 'Akshay' """ File contains code to Mine reviews and stars from a state reviews. This is just an additional POC that we had done on YELP for visualising number of 5 star reviews per state on a map. For each business per state, 5 reviews are taken and the count of the review is kept in the dictionary for each state. Use the resulting json to plot it onto the map. For the actual map visualisation, please refer State Review Nightlife POC. Since only 5 business reviews were taken per state, this still needs work. """ ############################################## from __future__ import division import sys reload(sys) import json import datetime sys.setdefaultencoding('utf8') state_5_star_dict = {} state_4_star_dict = {} state_3_star_dict = {} state_2_star_dict = {} state_1_star_dict = {} state_business = {} def create_set_for_business_with_cat(category): business_count = 0 with open('Data\yelp_academic_dataset_business.json') as fp: for line in fp.readlines(): temp = json.loads(line, encoding='utf-8') categories = str(temp["categories"]) state = str(temp["state"]) if state == "ON" or state == "ELN" or state == "EDH" or state == "MLN" or state == "NTH" or state == "FIF": continue if state not in state_business: state_business[state] = 0 if len(state_business.keys()) == 50: break if category in categories: print state business_id = str(temp["business_id"]) city = str(temp["city"]) name = str(temp["name"]) create_yelp_set(business_id, state, city, name) print "set prepared." def create_yelp_set(business_id, state, city, name): file_write = open('Data\state_stars_date_business.txt', mode='a') if state_business[state] == 5: print state, " is already completed." return with open('Data\yelp_academic_dataset_review.json') as fp: for line in fp.readlines(): temp = json.loads(line, encoding='utf-8') if str(temp["business_id"]) == business_id: state_business[state] += 1 star = str(temp["stars"]) date = str(temp["date"]) date_tm = datetime.datetime.strptime(date, "%Y-%m-%d").date() file_write.write(business_id) file_write.write('\t') file_write.write(state) file_write.write('\t') file_write.write(star) file_write.write('\t') file_write.write(city) file_write.write('\t') file_write.write(name) file_write.write('\t') file_write.write(str(date_tm)) file_write.write('\n') if state_business[state] == 5: break for key, value in state_5_star_dict.iteritems(): print key, value file_write.close() print "Done." def state_review_trends(): count = 0 with open('Data\state_stars_date_business.txt') as fp: for line in fp.readlines(): count += 1 tup = (line.split("\t")[0], line.split("\t")[1], line.split("\t")[2], line.split("\t")[3], line.split("\t")[4], line.split("\t")[5]) state = tup[1] star_rating = int(tup[2]) if int(star_rating) != 5: continue if state not in state_5_star_dict: state_5_star_dict[state] = 0 if state not in state_4_star_dict: state_4_star_dict[state] = 0 if state not in state_3_star_dict: state_3_star_dict[state] = 0 if state not in state_2_star_dict: state_2_star_dict[state] = 0 if state not in state_1_star_dict: state_1_star_dict[state] = 0 if star_rating == 5: state_5_star_dict[state] += 1 if star_rating == 4: state_4_star_dict[state] += 1 if star_rating == 3: state_3_star_dict[state] += 1 if star_rating == 2: state_2_star_dict[state] += 1 if star_rating == 1: state_1_star_dict[state] += 1 response = [] print "Number of 5 star reviews per state." for key, value in state_5_star_dict.iteritems(): response.append({'id': key, 'value': value}) print key, value json_data = json.dumps(response) print json_data print "Done." print count def main(): # Uncomment the line to run mining data. # create_set_for_business_with_cat("Nightlife") state_review_trends() if __name__ == "__main__": print "Execute Script!!" main()
akshaykamath/StateReviewTrendAnalysisYelp
StateReviewTrendsPOC.py
Python
mit
4,899
package org.codehaus.xfire.xmlbeans; import java.util.HashMap; import java.util.Map; import net.webservicex.WeatherData; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.aegis.stax.ElementReader; import org.codehaus.xfire.aegis.type.DefaultTypeCreator; import org.codehaus.xfire.soap.SoapConstants; import org.codehaus.xfire.soap.handler.ReadHeadersHandler; import org.codehaus.xfire.test.AbstractXFireTest; public class XmlTypeTest extends AbstractXFireTest { public void testNamespaces() throws Exception { XmlBeansType type = new XmlBeansType(WeatherData.class); Map nsmap = new HashMap(); nsmap.put("xsd", SoapConstants.XSD); MessageContext context = new MessageContext(); context.setProperty(ReadHeadersHandler.DECLARED_NAMESPACES, nsmap); type.readObject(new ElementReader(getResourceAsStream("/org/codehaus/xfire/xmlbeans/undeclaredns.xml")), context); } public void testTypeCreator() throws Exception { XmlBeansTypeCreator typeCreator = new XmlBeansTypeCreator(new DefaultTypeCreator()); XmlBeansType type = (XmlBeansType) typeCreator.createType(WeatherData.class); assertNotNull(type); assertTrue(type.isAbstract()); } }
eduardodaluz/xfire
xfire-xmlbeans/src/test/org/codehaus/xfire/xmlbeans/XmlTypeTest.java
Java
mit
1,337
const router = require("express").Router(); const Category = require("../model/Category"); const { categoryValidation } = require("../validation"); const verify = require("./verifyToken"); router.post("/", verify, async (req, res) => { const { error } = categoryValidation(req.body); if (error) return res.status(400).send(error.details[0].message); const category = new Category({ name: req.body.name, icon: req.body.icon, color: req.body.color, owner: req.user._id }); try { const savedCategory = await category.save(); res.send(savedCategory); } catch (err) { res.status(400).send(err); } }); router.get("/", verify, async (req, res) => { let query = {}; if (req.user.role !== "admin") { query.owner = req.user._id; } try { const allCategories = await Category.find(query); res.send(allCategories); } catch (err) { res.status(400).send(err); } }); router.get("/:id", verify, async (req, res) => { let query = {}; if (req.user.role !== "admin") { query.owner = req.user._id; } try { const categoryDetails = await Category.findById( req.params.id, (err, detail) => { var opts = [{ path: "category", match: { owner: req.user._id } }]; Category.populate(detail, opts, function(err, details) { console.log(details); }); } ); res.send(categoryDetails); } catch (err) { res.status(400).send(err); } }); router.put("/:id", async (req, res) => { try { Category.findOneAndUpdate( { _id: req.params.id }, { name: req.body.name, icon: req.body.icon }, err => { if (err) { return res.send(err); } return res.send("Successfully updated!"); } ); } catch (err) { res.status(400).send(err); } }); router.delete("/:id", async (req, res) => { try { const data = await Category.deleteOne({ _id: req.params.id }); if (data.ok === 1) { return res.send("Successfully deleted!"); } } catch (err) { res.status(400).send(err); } }); module.exports = router;
sivadass/react-expense-manager
backend/routes/category.js
JavaScript
mit
2,135
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>RUNTIME_OUTPUT_DIRECTORY &mdash; CMake 3.7.2 Documentation</title> <link rel="stylesheet" href="../_static/cmake.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '3.7.2', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/> <link rel="top" title="CMake 3.7.2 Documentation" href="../index.html" /> <link rel="up" title="cmake-properties(7)" href="../manual/cmake-properties.7.html" /> <link rel="next" title="RUNTIME_OUTPUT_NAME_&lt;CONFIG&gt;" href="RUNTIME_OUTPUT_NAME_CONFIG.html" /> <link rel="prev" title="RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;" href="RUNTIME_OUTPUT_DIRECTORY_CONFIG.html" /> </head> <body role="document"> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="RUNTIME_OUTPUT_NAME_CONFIG.html" title="RUNTIME_OUTPUT_NAME_&lt;CONFIG&gt;" accesskey="N">next</a> |</li> <li class="right" > <a href="RUNTIME_OUTPUT_DIRECTORY_CONFIG.html" title="RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;" accesskey="P">previous</a> |</li> <li> <img src="../_static/cmake-logo-16.png" alt="" style="vertical-align: middle; margin-top: -2px" /> </li> <li> <a href="https://cmake.org/">CMake</a> &raquo; </li> <li> <a href="../index.html">3.7.2 Documentation</a> &raquo; </li> <li class="nav-item nav-item-1"><a href="../manual/cmake-properties.7.html" accesskey="U">cmake-properties(7)</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="runtime-output-directory"> <span id="prop_tgt:RUNTIME_OUTPUT_DIRECTORY"></span><h1>RUNTIME_OUTPUT_DIRECTORY<a class="headerlink" href="#runtime-output-directory" title="Permalink to this headline">¶</a></h1> <p>Output directory in which to build <a class="reference internal" href="../manual/cmake-buildsystem.7.html#runtime-output-artifacts"><span>RUNTIME</span></a> target files.</p> <p>This property specifies the directory into which runtime target files should be built. The property value may use <span class="target" id="index-0-manual:cmake-generator-expressions(7)"></span><a class="reference internal" href="../manual/cmake-generator-expressions.7.html#manual:cmake-generator-expressions(7)" title="cmake-generator-expressions(7)"><code class="xref cmake cmake-manual docutils literal"><span class="pre">generator</span> <span class="pre">expressions</span></code></a>. Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory unless a generator expression is used.</p> <p>This property is initialized by the value of the variable CMAKE_RUNTIME_OUTPUT_DIRECTORY if it is set when a target is created.</p> <p>See also the <span class="target" id="index-0-prop_tgt:RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;"></span><a class="reference internal" href="RUNTIME_OUTPUT_DIRECTORY_CONFIG.html#prop_tgt:RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;" title="RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;"><code class="xref cmake cmake-prop_tgt docutils literal"><span class="pre">RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;</span></code></a> target property.</p> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="RUNTIME_OUTPUT_DIRECTORY_CONFIG.html" title="previous chapter">RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;</a></p> <h4>Next topic</h4> <p class="topless"><a href="RUNTIME_OUTPUT_NAME_CONFIG.html" title="next chapter">RUNTIME_OUTPUT_NAME_&lt;CONFIG&gt;</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/prop_tgt/RUNTIME_OUTPUT_DIRECTORY.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="RUNTIME_OUTPUT_NAME_CONFIG.html" title="RUNTIME_OUTPUT_NAME_&lt;CONFIG&gt;" >next</a> |</li> <li class="right" > <a href="RUNTIME_OUTPUT_DIRECTORY_CONFIG.html" title="RUNTIME_OUTPUT_DIRECTORY_&lt;CONFIG&gt;" >previous</a> |</li> <li> <img src="../_static/cmake-logo-16.png" alt="" style="vertical-align: middle; margin-top: -2px" /> </li> <li> <a href="https://cmake.org/">CMake</a> &raquo; </li> <li> <a href="../index.html">3.7.2 Documentation</a> &raquo; </li> <li class="nav-item nav-item-1"><a href="../manual/cmake-properties.7.html" >cmake-properties(7)</a> &raquo;</li> </ul> </div> <div class="footer" role="contentinfo"> &copy; Copyright 2000-2016 Kitware, Inc. and Contributors. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.4a0+. </div> </body> </html>
ontouchstart/emcc
base/cmake-3.7.2-Linux-x86_64/doc/cmake/html/prop_tgt/RUNTIME_OUTPUT_DIRECTORY.html
HTML
mit
6,881
//Wrapped in an outer function to preserve global this (function (root) { var amdExports; define(['bootstrap/bootstrap-transition','bootstrap/bootstrap-tooltip'], function () { (function () { /* =========================================================== * bootstrap-popover.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#popovers * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================================================== */ !function ($) { "use strict"; // jshint ;_; /* POPOVER PUBLIC CLASS DEFINITION * =============================== */ var Popover = function (element, options) { this.init('popover', element, options) } /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js ========================================== */ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, { constructor: Popover , setContent: function () { var $tip = this.tip() , title = this.getTitle() , content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') } , hasContent: function () { return this.getTitle() || this.getContent() } , getContent: function () { var content , $e = this.$element , o = this.options content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) || $e.attr('data-content') return content } , tip: function () { if (!this.$tip) { this.$tip = $(this.options.template) } return this.$tip } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } }) /* POPOVER PLUGIN DEFINITION * ======================= */ var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('popover') , options = typeof option == 'object' && option if (!data) $this.data('popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, { placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) /* POPOVER NO CONFLICT * =================== */ $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(window.jQuery); }.call(root)); return amdExports; }); }(this));
bcool/Coder4Hire
lib/bootstrap/js/bootstrap-popover.js
JavaScript
mit
3,363
import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from '../../actions/itemActions'; import FilterList from '../../components/FilterList/FilterList'; export const Filters = (props) => { return ( <FilterList changeShop={props.actions.changeShop} shop={props.shop} /> ); }; Filters.propTypes = { actions: PropTypes.object.isRequired, shop: PropTypes.oneOf([ 'side', 'secret', 'basics', 'upgrades' ]) }; function mapStateToProps(state) { return { shop: state.layout.shop }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(Filters);
akrigline/dota2items
src/containers/Filters/Filters.js
JavaScript
mit
802
python -m venv flask flask/bin/pip install -r requirements.txt
miguelgrinberg/REST-tutorial
setup.sh
Shell
mit
63
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace IppDotNetSdkQuickBooksApiV3SampleWebFormsApp.Account { public partial class Login : Page { protected void Page_Load(object sender, EventArgs e) { RegisterHyperLink.NavigateUrl = "Register"; var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]); if (!String.IsNullOrEmpty(returnUrl)) { RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl; } } } }
IntuitDeveloperRelations/QuickbooksV3API-DotNet
IppDotNetSdkQuickBooksApiV3SampleWebFormsApp/Account/Login.aspx.cs
C#
mit
636
var priceCount; var priceCountS; window.onload = function(){ initContentList(1); //$("#addContentBtn").bind("click",function(){ // window.location = "csicrmmgr.do?page=11"; //}); $("#query").bind("click",function(){initContentList(1);}); }; $(".colors a").live({ mouseover: (function(){ $(this).css("color","blue"); }), mouseout:(function(){ $(this).css("color","red"); }) }); function initContentList(currPage){ var pageSize =15; var data = {}; var form = ((currPage=currPage==0?1:currPage)-1)*pageSize; data.from = form; data.pageSize = pageSize; data.memberId = $("#memberId").val(); data.orderId = $("#orderId").val(); data.state = $("#state option:selected").val(); data.sdate = $("#sdate").val(); data.edate = $("#edate").val(); if(data.edate!=null&&data.sdate!=null){ var totalMonth = getMct(data.sdate,data.edate,'-'); if(totalMonth>=6){ jAlert("查询日期范围不能大于半年","提示"); return; } } var jsonData = JSON.stringify(data); $.post("Orderstatis.do?method=getsalesList",{data:jsonData},function(json){ if(json!=null && json.returnState == true){ var data=json.data[0]; var context=$("#dataList"); context.html(''); if (data != null && data.length > 0) { priceCount = json.data[1]; priceCountS = json.data[2]; $("#dataTips").hide(); var h=new Array(); for(var i=0;i<data.length;i++){ var bean=data[i]; h.push("<tr>"); h.push("<td>"+bean.recordId+"</td>"); h.push("<td class='colors'>"+bean.orderId+"</td>"); h.push("<td>"+bean.name+"</td>"); h.push("<td>"+bean.orderNum+"</td>"); h.push("<td>"+bean.unitPrice+"</td>"); h.push("<td>"+stateInfo(bean.state)+"</td>"); h.push("<td>"+bean.createTime+"</td>"); h.push("</tr>"); } h.push("<tr class='tb td1'><td style='text-align: left;' colspan='6'>总订单金额:"+priceCount+"元&nbsp;&nbsp;&nbsp;成功订单金额:"+priceCountS+"元&nbsp;&nbsp;&nbsp;成效率:"+toDecimal(priceCountS/priceCount*100)+"%</td></tr>"); context.append(h.join('')); }else{ $("#dataTips").show(); } } page(json.total,pageSize,currPage,"pageInfo","initContentList"); },"json"); } //获取两个日期之间的月份差距 function getMct(beginTime,endTime,sign){ var beginDate = beginTime.split(sign);// 拆分开始日期的年月日 var endDate = endTime.split(sign);// 拆分开始日期的年月日 var bMonth = parseInt(beginDate[0]) * 12 + parseInt(beginDate[1]);// 得到开 始日期的月数 var eMonth = parseInt(endDate[0]) * 12 + parseInt(endDate[1]);// 得到结束日 期的月数 var totalMonth = Math.abs(eMonth - bMonth);// 获取月数 return totalMonth; } /**查看订单详情**/ function showTxt(memberId){ window.location ="Membermanage.do?page=12&memberId="+memberId; } /**设置操作栏按钮**/ function stateBut(bean){ if('1'==bean.state){ return "<input type='button' id='topay' value='已支付' class='bt_1' onclick=topay('"+bean.memberId+"','"+bean.currency+"','"+bean.totalAmount+"','"+bean.orderId+"');>"; }else if('2'==bean.state){ return "<input type='button' id='backpay' value='已发货' class='bt_1'>"; } } /**设置状态**/ function stateInfo(state){ if('1'==state){ return '待支付'; } if('2'==state){ return '已支付'; } if('3'==state){ return '已发货'; } if('4'==state){ return '已接收'; } if('5'==state){ return '已结案'; } if('6'==state){ return '异常'; } if('7'==state){ return '退货'; } } /**确认支付**/ function topay(memberId,currency,totalAmount,orderId){ jConfirm("您确认用户已经付款?", "提示", function (r) { if (r) { var data={}; data.memberId=memberId; data.orderId=orderId; data.currency=currency; data.totalAmount=totalAmount; var jsonData=JSON.stringify(data); $.post("Ordermanage.do?method=toPayforOrder",{data:jsonData},function(json){ if(json!=null && json.returnState == true){ var message=json.message; //提示信息:0,币种不同 1,操作成功 2,余额不足 3,系统错误 if('0'==message){ jAlert("币种不同,无法支付!!","提示"); }else if('1'==message){ jAlert("操作成功!!","提示",function(){ initContentList(1); }); }else if('2'==message){ jAlert("用户账户余额不足,不能执行'已支付'动作!!","提示"); }else if('3'==message){ jAlert("操作失败,请重试!!","提示"); } }else{ jAlert("操作失败,请重试!!","提示"); } },"json"); } }); } function toDecimal(x) { var f = parseFloat(x); if (isNaN(f)) { return; } f = Math.round(x*100)/100; return f; }
linfongi/gloso
glosob2c/gadmin/membermgr/js/saleslist.js
JavaScript
mit
5,020
// @flow /** * CommonFashionista: provides utilities to help manage Fashions * (which are * object-representations of CSS styles). * * @module internal/fashionistas/common */ import Debug from 'debug' import chroma from 'chroma-js' import type { CalcFashion, ColorFashion, CompositeFashion, Fashion, NumberFashion, StaticFashion, UnitFashion, } from '../flow-types' import { ALL_COMMAS_REGEX, NUMBER_REGEX, NON_NUMER_REGEX, makeError, } from '../utils' import { BOX_SHADOW, TRANSFORM, TRANSFORM_DELIMITER, } from '../constants' const EMPTY_UNIT: string = '0px'; const debug = Debug('react-animatronics:fashionistas:common'); const isCommaString = (str: string): boolean => { return ( typeof str === 'string' && str.includes(',') && !str.includes('rgb') && !str.includes('hsl') ); } export const isColorString = (str: string): boolean => { let color; try { color = chroma(str); } catch (e) { color = false; } return !!color; } // NOTE: replace decimals and negative signs otherwise it'll get caught by the // NON_NUMBER_REGEX // TODO: why is the NON_NUMBER_REGEX check in here? export const isNumberString = (str: string): boolean => ( !isNaN(parseFloat(str)) && !NON_NUMER_REGEX.test(str.replace('.', '').replace('-', '')) ); // FIXME: can have false positives export const isUnitString = (str: string): boolean => ( NUMBER_REGEX.test(str) ); export const createColorFashion = (raw: string): ColorFashion => ({ isBasicType: true, isColorType: true, value: chroma(raw).hex(), }); export const createStaticFashion = (raw: string): StaticFashion => ({ isBasicType: true, isStaticType: true, value: raw, }); export const createNumberFashion = (raw: string|number): NumberFashion => ({ isBasicType: true, isNumberType: true, value: parseFloat(raw), }); // EXPERIMENT: Perhaps departing from implicit returns since they make // debugging more difficult. export const createUnitFashion = (raw: string): UnitFashion => { debug('creating unit fashion for "%s"', raw); return { isBasicType: true, isUnitType: true, value: parseFloat(NUMBER_REGEX.exec(raw)[0]), unit: raw.slice(NUMBER_REGEX.exec(raw)[0].length), }; }; export const createCalcFashion = (raw: string): CalcFashion => { debug('creating calc fashion fro "%s"', raw); return { isBasicType: true, isCalcType: true, value: raw, }; }; export const parseTransformName = (transform: string): string => { return transform.slice(0, transform.indexOf('(')); }; // TODO: Better function names const removeLastChar = (str: string) => { return str.substr(0, str.length - 1); }; const butLast = (array: any[]) => { return array.slice(0, array.length - 1); } const last = (array: any[]) => { return array[array.length - 1]; } // FIXME: Lots of imperative code here, there must be a better way. To goal is // to correctly split any valid CSS transforms, which can have nested parens // e.g. "translateX(100px) translateY(calc((100% - 40px) * -1))" export const splitTransforms = (transforms: string) => { let openParenCount = 0; const startingCharIndexes = []; const chars = transforms.split(''); const splits = []; for (let i = 0; i < chars.length; ++i) { const c = chars[i]; if (c === ' ') { continue; } else if (startingCharIndexes.length === 0) { startingCharIndexes.push(i); } else if (c === '(') { openParenCount += 1; } else if (c === ')') { if (openParenCount === 1) { splits.push( chars .slice(startingCharIndexes.pop(), i + 1) .join('') ); openParenCount -= 1; } else if (openParenCount > 1) { openParenCount -= 1; } } } return splits; } /** * @param string value e.g. "translateX(100x)", "translateY(calc(100% - 40px))" * @returns string e.g. "100px", "calc(100% - 40px)" */ export const parseInnerTransformValue = (value: string): string => { const [_, ...inner] = value.split('('); return butLast(inner) .concat(removeLastChar(last(inner))) .join('('); } const parseTransformStyle = (transform: string): Fashion => { return parseStyle(parseInnerTransformValue(transform)); } export const createTransformFashion = (raw: string): CompositeFashion => ({ isCompositeType: true, names: splitTransforms(raw).map(parseTransformName), styles: splitTransforms(raw).map(parseTransformStyle), }); /** * @param raw - e.g. "6px 12px" (margin/padding shorthand) * @returns CompositeFashion */ export const createSpacingFashion = (raw: string, name: string): CompositeFashion => { const segments = raw.split(' '); const numSegments = segments.filter(s => !!s).length; if (numSegments < 1 || numSegments > 4) { throw makeError( `Received an invalid style for ${ name || "margin/padding" }: "${ raw }".`, `Margins/paddings should have between 1 to 4 values (no less than 1 and`, `no more than 4).` ); } const parsed = segments.map(createUnitFashion); return { isCompositeType: true, styles: numSegments === 1 ? [parsed[0], parsed[0], parsed[0], parsed[0]] : numSegments === 2 ? [parsed[0], parsed[1], parsed[0], parsed[1]] : numSegments === 3 ? [parsed[0], parsed[1], parsed[2], parsed[1]] : // numSegments === 4 [parsed[0], parsed[1], parsed[2], parsed[3]] }; }; export const createCommaFashion = (raw: string, name: ?string): CompositeFashion => ({ isCompositeType: true, isCommaType: true, styles: raw .split(',') .map(s => s.trim()) .map(style => parseStyle(style, name)), }); export const createBoxShadowFashion = (raw: string): CompositeFashion => { const segments = raw.split(' '); const numSegments = segments.filter(s => !!s).length; if (numSegments < 3 || numSegments > 5) { throw makeError( `Received an invalid style for box-shadow: "${ raw }".`, `Box-shadows should have between 3 to 5 values:`, `https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow` ); } // Possible formats: // offset-x | offset-y | color // offset-x | offset-y | blur-radius | color // offset-x | offset-y | blur-radius | spread-radius | color // inset | offset-x | offset-y | color // Target format: // offset-x | offset-y | blur-radius | spread-radius | color return { isCompositeType: true, styles: numSegments === 3 ? [ createUnitFashion(segments[0]), createUnitFashion(segments[1]), createUnitFashion(EMPTY_UNIT), createUnitFashion(EMPTY_UNIT), createColorFashion(segments[2]) ] : (numSegments === 4 && segments[0] === 'inset') ? [ createStaticFashion(segments[0]), createUnitFashion(segments[1]), createUnitFashion(segments[2]), createColorFashion(segments[3]) ] : (numSegments === 4) ? [ createUnitFashion(segments[0]), createUnitFashion(segments[1]), createUnitFashion(segments[2]), createUnitFashion(EMPTY_UNIT), createColorFashion(segments[3]) ] : // numSegments === 5 [ createUnitFashion(segments[0]), createUnitFashion(segments[1]), createUnitFashion(segments[2]), createUnitFashion(segments[3]), createColorFashion(segments[4]) ] }; } export const parseStyle = (raw: string|number, name: ?string): Fashion => { return typeof raw === 'number' ? createNumberFashion(raw) : isNumberString(raw) ? createNumberFashion(raw) : typeof raw === 'string' && name === TRANSFORM ? createTransformFashion(raw) : typeof raw === 'string' && (raw.includes('calc') || raw.includes('matrix')) ? createCalcFashion(raw) : typeof name === 'string' && (name.includes('margin') || name.includes('padding')) ? createSpacingFashion(raw, name) : isCommaString(raw) ? createCommaFashion(raw, name) : name === BOX_SHADOW ? createBoxShadowFashion(raw) : isColorString(raw) ? createColorFashion(raw) : isUnitString(raw) ? createUnitFashion(raw) : createStaticFashion(raw) }; export const stringifyCalc = (calc: CalcFashion) => calc.value; export const stringifyColor = (color: ColorFashion) => `${ chroma(color.value).hex() }`; export const stringifyNumber = (number: NumberFashion) => `${ number.value }`; export const stringifyUnit = (style: UnitFashion) => `${ style.value }${ style.unit }`; export const stringifyComposite = (composite: CompositeFashion) => composite.styles .reduce((arr: string[], style: Fashion, index: number) => { const name: ?string = composite.names && composite.names[index]; return arr.concat( name ? `${ name }(${ stringifyFashion(style) })` : stringifyFashion(style) ); }, []) .join(composite.isCommaType ? ', ' : ' '); const stringifyBasic = (fashion: Fashion): string => { debug('stringifying basic fashion %o', fashion); return fashion.isColorType ? stringifyColor(fashion) : fashion.isNumberType ? stringifyNumber(fashion) : fashion.isUnitType ? stringifyUnit(fashion) : fashion.isCalcType ? stringifyCalc(fashion) : '' }; export const stringifyFashion = (style: Fashion): string => ( style.isCompositeType ? stringifyComposite(style) : // default: unknown style stringifyBasic(style) ); // IMPROVE: By default, all "transforms" will be converted, even if they have // the same units. We can be more efficient about this, but it's unclear if // that's worth it right now. export const haveConvertibleUnits = ( rawA: string, rawB: string, styleName: string ): boolean => { if (styleName === TRANSFORM) return true; const fashionA = parseStyle(rawA, styleName); const fashionB = parseStyle(rawB, styleName); return (fashionA.isCalcType || fashionB.isCalcType) ? true : (fashionA.unit && fashionB.unit) ? fashionA.unit !== fashionB.unit : false }; const lastChar = (s: string) => s[s.length - 1]; export const separateTransformNames = (transform: string) => { const separated = splitTransforms(transform) .map(parseTransformName); return separated; } export const parseTransformsSeparately = (transforms: string) => { return splitTransforms(transforms) .sort() .reduce((result, transform) => { const name = parseTransformName(transform); result[name] = transform; return result; }, {}) }; export const pluckTransforms = ( styles: Object, transformations: string[] ) => { return Object.keys(styles) .map(transformName => { return transformations.includes(transformName) ? styles[transformName] : ''; }) .filter(t => !!t) .join(' '); }
andrewkshim/react-animatronics
src/internal/fashionistas/common.js
JavaScript
mit
10,749
/* ** syscall.c for ftrace in /home/kureuil/Work/PSU_2015_ftrace ** ** Made by Arch Kureuil ** Login <kureuil@epitech.net> ** ** Started on Tue Apr 12 11:47:22 2016 Arch Kureuil ** Last update Sun Apr 17 11:19:06 2016 Arch Kureuil */ #include <sys/ptrace.h> #include <sys/time.h> #include <sys/wait.h> #include <assert.h> #include <stdlib.h> #include <time.h> #include "ftrace.h" #include "ftrace-syscall.h" static const t_printer g_printers[] = { &ftrace_print_hexa, &ftrace_print_integer, &ftrace_print_pointer, &ftrace_print_string, &ftrace_print_long, &ftrace_print_ulong, &ftrace_print_size_t, &ftrace_print_ssize_t, NULL }; static int ftrace_syscall_get_by_id(unsigned long long id, struct s_syscall *scallp) { size_t i; i = 0; while (g_syscalls[i].name != NULL) { if (g_syscalls[i].id == id) { *scallp = g_syscalls[i]; return (0); } i++; } return (-1); } static int ftrace_syscall_print_call(const struct s_syscall *scall, const struct user_regs_struct *regs, const struct s_ftrace_opts *opts) { size_t i; unsigned long long int value; ftrace_event_trigger("ftrace:printline-begin", NULL); fprintf(stderr, "%s(", scall->name); i = 0; while (i < scall->argc) { if (i != 0) fprintf(stderr, ", "); value = ftrace_registers_get_by_idx(regs, i); if (g_ftrace_syscall_prettify) { if (scall->args[i].custom) scall->args[i].printer.callback(value, opts->pid, regs, opts); else g_printers[scall->args[i].printer.type](value, opts->pid, regs, opts); } else ftrace_print_hexa(value, opts->pid, regs, opts); i++; } return (0); } static int ftrace_syscall_print_return(const struct s_syscall *scall, const struct user_regs_struct *regs, const struct s_ftrace_opts *opts) { long long filtered; if (!scall->noreturn) { fprintf(stderr, ") = "); if (g_ftrace_syscall_prettify) { filtered = ((long long) regs->rax < 0) ? (unsigned long long) -1 : regs->rax; g_printers[scall->retval](filtered, opts->pid, regs, opts); ftrace_print_errno(regs->rax, opts->pid, regs, opts); } else ftrace_print_hexa(regs->rax, opts->pid, regs, opts); fprintf(stderr, "\n"); } else { fprintf(stderr, ") = ?\n"); } return (0); } int ftrace_syscall_handler(unsigned long long int instruction, const struct user_regs_struct *regs, const struct s_ftrace_opts *opts) { int status; struct user_regs_struct registers; struct s_syscall scall; assert(regs != NULL); assert(opts != NULL); (void) instruction; if (ftrace_syscall_get_by_id(regs->rax, &scall)) return (0); ftrace_syscall_print_call(&scall, regs, opts); if (ptrace(PTRACE_SINGLESTEP, opts->pid, 0, 0) == -1) return (-1); wait(&status); if (!scall.noreturn) { if (ftrace_peek_registers(opts->pid, &registers)) return (-1); } ftrace_syscall_print_return(&scall, &registers, opts); if (!WIFSTOPPED(status)) { fprintf(stderr, "+++ exited with %d +++\n", WEXITSTATUS(status)); return (1); } return (0); } static const struct s_ftrace_handler g_ftrace_syscall_handler = { .bitmask = FTRACE_SYSCALL_BITMASK, .instruction = FTRACE_SYSCALL_INSTRUCTION, .callback = &ftrace_syscall_handler, }; void ftrace_syscall_register_handlers(const char *name, void *data) { (void) name; (void) data; ftrace_handlers_register(&g_ftrace_syscall_handler); }
kureuil/ftrace
vendor/ftrace-syscall/src/handler.c
C
mit
3,512
require 'spec_helper' describe Receipt do pending "add some examples to (or delete) #{__FILE__}" end
abanoubadel/rails_project
spec/models/receipt_spec.rb
Ruby
mit
104
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="twitter:card" content="summary"/> <meta name="twitter:image" content="http://opendatask.ca/images/cover.jpg"/> <meta name="twitter:title" content="Tags"/> <meta name="twitter:description" content="Data transparency for the flatlands"/> <meta name="twitter:site" content="@opendatask"/> <meta property="og:title" content="Tags &middot; Saskatchewan Open Data" /> <meta property="og:site_name" content="Saskatchewan Open Data" /> <meta property="og:url" content="http://opendatask.ca/tags/" /> <meta property="og:image" content="http://opendatask.ca/images/cover.jpg"/> <meta property="og:type" content="website" /> <meta property="og:description" content="Data transparency for the flatlands" /> <title>Tags &middot; Saskatchewan Open Data</title> <meta name="description" content="Data transparency for the flatlands" /> <meta name="HandheldFriendly" content="True" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="http://opendatask.ca/images/favicon.ico"> <link rel="apple-touch-icon" href="http://opendatask.ca/images/apple-touch-icon.png" /> <link rel="stylesheet" type="text/css" href="http://opendatask.ca/css/screen.css" /> <link rel="stylesheet" type="text/css" href="http://opendatask.ca/css/nav.css" /> <link rel="stylesheet" type="text/css" href="http://opendatask.ca/css/mailchimp.css" /> <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400|Inconsolata" /> <link href="http://opendatask.ca/index.xml" rel="alternate" type="application/rss+xml" title="Saskatchewan Open Data" /> <link href="http://opendatask.ca/tags/index.xml" rel="alternate" type="application/rss+xml" title="Tags &middot; Saskatchewan Open Data" /> <meta name="generator" content="Hugo 0.54.0" /> <link rel="canonical" href="http://opendatask.ca/tags/" /> <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "Website", "publisher": { "@type": "Person", "name": , "image": { "@type": "ImageObject", "url": http://opendatask.ca/images/logo.png, "width": 250, "height": 250 }, "url": http://andrewdyck.com, "sameAs": [ ], "description": Andrew loves data. When he&#39;s not moving bytes around for analysis or visualization, he&#39;s writing about open data. }, "url": http://opendatask.ca/, "mainEntityOfPage": { "@type": "WebPage", "@id": http://opendatask.ca/ }, "description": Data transparency for the flatlands } </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-26754725-1', 'auto'); ga('send', 'pageview'); </script> <script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","https://chimpstatic.com/mcjs-connected/js/users/4194d641d0e422e7e016b09ba/873f99eed6d758d0bf4375c35.js");</script> </head> <body class="nav-closed"> <div class="nav"> <h3 class="nav-title">Menu</h3> <a href="#" class="nav-close"> <span class="hidden">Close</span> </a> <ul> <li class="nav-opened" role="presentation"> <a href="http://opendatask.ca/">Home</a> </li> <li class="nav-opened" role="presentation"> <a href="http://opendatask.ca/about">About</a> </li> <li class="nav-opened" role="presentation"> <a href="http://opendatask.ca/data">Data Sources</a> </li> <li class="nav-opened" role="presentation"> <a href="http://opendatask.ca/newsletter">Newsletter</a> </li> <li class="nav-opened" role="presentation"> <a href="http://opendatask.ca/contact">Contact</a> </li> </ul> <a class="subscribe-button icon-feed" href="http://opendatask.ca/tags/index.xml">Subscribe</a> </div> <span class="nav-cover"></span> <div class="site-wrapper"> <header class="main-header tag-head" style="background-image: url(http://opendatask.ca/images/cover.jpg)"> <nav class="main-nav overlay clearfix"> <a class="blog-logo" href="http://opendatask.ca/"><img src="http://opendatask.ca/images/logo.png" alt="Home" /></a> <a class="menu-button" href="#"><span class="burger">&#9776;</span><span class="word">Menu</span></a> </nav> <div class="vertical"> <div class="main-header-content inner"> <h1 class="page-title">Tags</h1> <h2 class="page-description"> Data transparency for the flatlands </h2> </div> </div> </header> <main class="content" role="main"> <div class="extra-pagination inner"> <nav class="pagination" role="navigation"> <span class="page-number">Page 1 of 2</span> <a class="older-posts" href="http://opendatask.ca/tags/page/2/">Older Posts &rarr;</a> </nav> </div> <article class="post tags"> <header class="post-header"> <h2 class="post-title"><a href="http://opendatask.ca/tags/democracy/">Democracy</a></h2> </header> <section class="post-excerpt"> <p> <a class="read-more" href="http://opendatask.ca/tags/democracy/">&raquo;</a></p> </section> <footer class="post-meta"> <img class="author-thumb" src="http://opendatask.ca/images/logo.png" alt="Author image" nopin="nopin" /> Andrew Dyck <time class="post-date" datetime="2020-10-20T00:00:00Z"> 20 Oct 2020 </time> </footer> </article> <article class="post tags"> <header class="post-header"> <h2 class="post-title"><a href="http://opendatask.ca/tags/election/">Election</a></h2> </header> <section class="post-excerpt"> <p> <a class="read-more" href="http://opendatask.ca/tags/election/">&raquo;</a></p> </section> <footer class="post-meta"> <img class="author-thumb" src="http://opendatask.ca/images/logo.png" alt="Author image" nopin="nopin" /> Andrew Dyck <time class="post-date" datetime="2020-10-20T00:00:00Z"> 20 Oct 2020 </time> </footer> </article> <article class="post tags"> <header class="post-header"> <h2 class="post-title"><a href="http://opendatask.ca/tags/hackathon/">Hackathon</a></h2> </header> <section class="post-excerpt"> <p> <a class="read-more" href="http://opendatask.ca/tags/hackathon/">&raquo;</a></p> </section> <footer class="post-meta"> <img class="author-thumb" src="http://opendatask.ca/images/logo.png" alt="Author image" nopin="nopin" /> Andrew Dyck <time class="post-date" datetime="2011-12-03T00:00:00Z"> 3 Dec 2011 </time> </footer> </article> <article class="post tags"> <header class="post-header"> <h2 class="post-title"><a href="http://opendatask.ca/tags/model/">Model</a></h2> </header> <section class="post-excerpt"> <p> <a class="read-more" href="http://opendatask.ca/tags/model/">&raquo;</a></p> </section> <footer class="post-meta"> <img class="author-thumb" src="http://opendatask.ca/images/logo.png" alt="Author image" nopin="nopin" /> Andrew Dyck <time class="post-date" datetime="2020-10-20T00:00:00Z"> 20 Oct 2020 </time> </footer> </article> <article class="post tags"> <header class="post-header"> <h2 class="post-title"><a href="http://opendatask.ca/tags/open-data-day/">Open Data Day</a></h2> </header> <section class="post-excerpt"> <p> <a class="read-more" href="http://opendatask.ca/tags/open-data-day/">&raquo;</a></p> </section> <footer class="post-meta"> <img class="author-thumb" src="http://opendatask.ca/images/logo.png" alt="Author image" nopin="nopin" /> Andrew Dyck <time class="post-date" datetime="2017-03-11T00:00:00Z"> 11 Mar 2017 </time> </footer> </article> <nav class="pagination" role="navigation"> <span class="page-number">Page 1 of 2</span> <a class="older-posts" href="http://opendatask.ca/tags/page/2/">Older Posts &rarr;</a> </nav> </main> <footer class="site-footer clearfix"> <section class="copyright"><a href="">Saskatchewan Open Data</a> All rights reserved - 2020</section> <section class="poweredby">Proudly generated by <a class="icon-hugo" href="http://gohugo.io">HUGO</a>, with <a class="icon-theme" href="https://github.com/vjeantet/hugo-theme-casper">Casper</a> theme</section> </footer> </div> <script type="text/javascript" src="http://opendatask.ca/js/jquery.js"></script> <script type="text/javascript" src="http://opendatask.ca/js/jquery.fitvids.js"></script> <script type="text/javascript" src="http://opendatask.ca/js/index.js"></script> </body> </html>
SaskOpenData/SaskOpenData.github.io
tags/index.html
HTML
mit
10,624
<style> .highlight { padding: 9px 14px; background-color: #b7b7b8; border: 1px solid #e1e1e8; border-radius: 4px; } img { margin-bottom: 10px; } </style> <div class="highlight" style="display: inline-block" > <div> <img ng-src="{{image.dataUrl}}" width="100" height="100" /> </div> <div class="form-group"> <input class="form-control headerText" type="text" ng-model="image.title" placeholder="Title ..." /> </div> <div class="form-group"> <input class="form-control headerText" type="text" ng-model="image.description" placeholder="Title ..." /> </div> </div>
BLTuckerDev/GroupedImages
detailedimagebox.html
HTML
mit
764
<style type="text/css" media="screen"> span#live-signal { color: red; animation: blinker 3s linear infinite; font-size: 15px; } @keyframes blinker { 50% { opacity: 0; } } </style> <div> <h4> <span id="live-signal">LIVE</span> <small>last updated <span id="last-updated">{{lastUpdated}}</span></small> </h4> </div>
khairihafsham/wikisual
wikiweb/jsapp/app/live-display.component.html
HTML
mit
336
<?php namespace App\Security\ACL; interface IBrokerPermissions { public function canViewStats(): bool; public function canFreeze(): bool; public function canUnfreeze(): bool; }
ReCodEx/api
app/V1Module/security/ACL/IBrokerPermissions.php
PHP
mit
193
--- id: 842 title: 投资新政13条齐出 保险资管急欲打通奇经八脉 date: 2012-06-14T09:05:00+00:00 author: 偶尔陶醉 layout: post guid: http://www.stutostu.com/842.html permalink: /?p=842 categories: - 股票 tags: - 保险 - 投资 --- 【偶尔点评:这么搞法,以后银行并保险就难了,牌照要升值了我擦~~目前有保险牌照的股份制好像就招行持有50%的招商信诺】  来源:21世纪经济报道   保险资产管理的实质性利好即将到来。   近日,中国保监会频频召集各家保险机构投资人士,组织培训及研讨,核心正是保监会拟发布的13项险资投资新政的征求意见稿,被业界称为保险资金新政“13条”。 **6月13日,多位保险公司投资人士在接受本报记者采访时表示,保监会这次动作确实比较大,此次“13条”涉及保险资产管理范围和保险投资渠道两大方向,并就拓宽保险资产管理范围和险资委托投资征求意见,保险公司将可以参与投资银行、证券和信托等发行的投资品种,以及委托其他投资管理机构管理保险资金**。 **这意味着保险资金的投资范围将打破以往体内循环的封闭现状,实现与银行、证券、信托的对接。此外,保险资产管理公司也将借机逐步淡化保险资管的行业局限,参与到泛资产管理行业之中**。 **  打破银、证、信、保边界**   一位与会的保险资产管理公司高管透露,根据“13条”的规定,保险机构将可以参与投资境内商业银行发起的信贷资产支持证券、保证收益型理财产品,但应符合相关金融监管部门规定,且基础资产清晰,信用评级在AAA或相当于AAA的信用级别,并在指定金融资产交易机构发行、等级和交易流通。   此外,保险机构还将可以投资境内信托公司发起设立的集合资金信托计划和券商或券商资产管理公司发起的有担保的集合资产管理计划。   “这是一个大的行业趋势。”一位中型保险公司的高管称,以前保险资金是自己圈起来,只是保险系统内循环。现在中间一些壁垒要拆除掉,一方面保险资管可以参与外部竞争,另一方面券商、基金等也可以参与保险资金的竞争,从而更加市场化。 **目前的行业大背景是保费收入增长放缓,信托、证券、理财都对保险业务增长带来较大冲击。考虑到整个行业竞争,保险作为财富管理中的环节之一,投资必须进一步解放,一保险公司投资负责人亦称**。   该人士透露,根据“13条”的规定,符合资质的信托公司和证券公司净资产不低于20亿元人民币,信托公司信用评级A级以上,证券公司或证券资管公司则需满足上一年度证监会A或A以上评级的要求。   前述高管表示,目前,保险资管的专业水准跟基金、券商相比各有侧重,在固定收益投资方面比较领先,在权益类投资方面优势略小,合作可以加强保险资管在权益类投资领域的能力。 **值得一提的是,根据“13条”的规定,除受托管理保险资金外,保险资管公司还将允许受托管理养老金、企业年金、住房公积金和其他企业委托的资金;保险资管公司可根据受托资金需求,制定投资策略,开发资产管理产品,并以投资组合名义开设相关账户**。   此外,据前述保险资管人士透露,在经有关金融监管部门批准后,保险资产管理公司有望开展公募资产管理业务。接近保监会人士表示,保监会还将根据市场情况适时地发布有关业务的规则。 **  委托投资酝酿放行**   除了保险资金投资范围的相应拓宽,根据“13条”的规定,保险公司将被允许向保险资产管理公司以外的资产管理机构委托投资,包括证券公司、证券资产管理公司,基金管理公司等专业投资管理机构。   保监会也对险资受托机构的资质做了明确规定,保险公司选择证券公司或证券资产管理公司开展委托投资,需取得客户资产管理业务资格   三年以上,且受托机构需满足客户资产管理业务管理资产余额不低于200亿元,其中,集合资产管理业务余额不得低于100亿元。   “这个门槛还是蛮高的。”一位券商资产管理公司的高管表示,**从截至2011年底的数据来看,满足如上管理资产余额200亿元的券商资管只有中金和中信两家,若同时满足集合资产管理余额100亿条件,就只剩下中信一家**。“去年,全券商资管行业满足客户资产管理业务管理余额100亿元的也只仅有5家而已。”   而对于基金公司受托保险资金,保监会规定则需要符合获得特定客户资产管理业务资格满三年,且特定客户资产管理资产余额不低于200亿元,其中非关联方机构资产余额占比不超过50%。   前述保险公司投资负责人表示,“行业内的资产管理公司水平良莠不齐,引入基金公司和证券公司等于多了一个很大的选择。”此外,保险公司还可以授权投资管理人运用远期、掉期、齐全、期货等金融衍生品,管理和对冲风险,不得用于投资和放大交易。   不过,业内人士亦有担忧,保监会一次性推出13条拓宽险资运用范围和渠道的征求意见稿,未免有些激进。   前述投资负责人称,保险公司要有风险识别和风险管理的能力,例如允许利用股指期货和国债期货进行对冲,如果有的人拿它来做套利和投机,那就引入了极大的风险。“监管不好的话,很难控制和识别。”   前述保险公司高管亦指出,“保险资管的范围和渠道一旦放开,虽然投资选择面更大,但配套的风险管控要求也会更高。”   他认为,政策推出是一个导向,在保险公司实施层面,不可能政策一放开就立刻去做,还需要一个过程,包括投资能力和风险控制能力的配备,这是循序渐进的过程。“在偿付能力的刚性约束下,保险公司不太可能冒然行事。”   据保监会统计,截至今年4月末,我国保险资产总额已达到6.3万亿元。
Barbery/blog.site
content/post/2012-06-14-投资新政13条齐出保险资管急欲打通奇经八脉.md
Markdown
mit
6,488
/******************************************************************************* * File Name: scps.c * * Version: 1.30 * * Description: * This file contains SCPS callback handler function. * * Hardware Dependency: * CY8CKIT-042 BLE * ******************************************************************************** * Copyright 2014-2015, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "common.h" #include "scps.h" uint16 requestScanRefresh = 0u; uint16 scanInterval = 0u; uint16 scanWindow = 0u; /******************************************************************************* * Function Name: ScpsCallBack() ******************************************************************************** * * Summary: * This is an event callback function to receive service specific events from * SCPS Service. * * Parameters: * event - the event code * *eventParam - the event parameters * * Return: * None. * ********************************************************************************/ void ScpsCallBack (uint32 event, void *eventParam) { switch(event) { case CYBLE_EVT_SCPSS_NOTIFICATION_ENABLED: requestScanRefresh = ENABLED; break; case CYBLE_EVT_SCPSS_NOTIFICATION_DISABLED: requestScanRefresh = DISABLED; break; case CYBLE_EVT_SCPSS_SCAN_INT_WIN_CHAR_WRITE: scanInterval = CyBle_Get16ByPtr(((CYBLE_SCPS_CHAR_VALUE_T *)eventParam)->value->val); scanWindow = CyBle_Get16ByPtr(((CYBLE_SCPS_CHAR_VALUE_T *)eventParam)->value->val + sizeof(scanInterval)); break; case CYBLE_EVT_SCPSC_NOTIFICATION: break; case CYBLE_EVT_SCPSC_READ_DESCR_RESPONSE: break; case CYBLE_EVT_SCPSC_WRITE_DESCR_RESPONSE: break; default: break; } } /******************************************************************************* * Function Name: ScpsInit() ******************************************************************************** * * Summary: * Initializes the SCPS Service. * *******************************************************************************/ void ScpsInit(void) { CYBLE_API_RESULT_T apiResult; uint16 cccdValue; /* Register service specific callback function */ CyBle_ScpsRegisterAttrCallback(ScpsCallBack); /* Read CCCD configurations from flash */ apiResult = CyBle_ScpssGetCharacteristicDescriptor(CYBLE_SCPS_SCAN_REFRESH, CYBLE_SCPS_SCAN_REFRESH_CCCD, CYBLE_CCCD_LEN, (uint8 *)&cccdValue); if((apiResult == CYBLE_ERROR_OK) && (cccdValue != 0u)) { requestScanRefresh |= ENABLED; } } /* [] END OF FILE */
perusworld/PSoC4OTAUpdate
HelloApp.cydsn/scps.c
C
mit
2,985
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ class Home extends CI_Controller { public function __construct() { parent::__construct(); } public function index() { echo "home page"; } }
leelanarasimha/codeignierproject
application/controllers/Home.php
PHP
mit
381
define(['app', 'model/candidate'], function(App, CandidateCollection){ App.commands.setHandler('votePageDisplay', function(voter){ require(['views/vote', 'backbone'], function(VoteView, Backbone){ var list = new CandidateCollection(); list.fetch(); //Display only those candidates which are from the voter's constituency App.Main.show(new VoteView({ collection: list })); }) ; }); });
SethiPawandeep/ElectionApp
Election-UI/www/js/events/showVotePage.js
JavaScript
mit
481
package work.samoje.colors; /** * Static methods to help with common concerns when working with colors. * * @author Jennie Sadler * */ public class ColorHelpers { public static final double MAX_COLOR_VAL = 255.0; /** * Returns the integer value nearest the given double that is in the set {0, * 255}. * * @param value * @return */ public static int getNearestAbsoluteValue(final double value) { return (value > (MAX_COLOR_VAL / 2)) ? (int) MAX_COLOR_VAL : 0; } /** * Returns the integer value nearest the given double value that is in the * range [0, 255]. * * @param value * Any double value * @return The integer value nearest to the provided in [0, 255]. May be * equal to the given value. */ public static int boundByColorRange(final double value) { return Math.max(0, (int)Math.round(Math.min(ColorHelpers.MAX_COLOR_VAL, value))); } }
jenlersadnie/color-array-series
src/work/samoje/colors/ColorHelpers.java
Java
mit
981
// Copyright (c) 2009-2013 The Storecoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypter.h" #include "script.h" #include <string> #include <vector> #include <boost/foreach.hpp> #include <openssl/aes.h> #include <openssl/evp.h> bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) { if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) return false; int i = 0; if (nDerivationMethod == 0) i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV); if (i != (int)WALLET_CRYPTO_KEY_SIZE) { OPENSSL_cleanse(chKey, sizeof(chKey)); OPENSSL_cleanse(chIV, sizeof(chIV)); return false; } fKeySet = true; return true; } bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV) { if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE) return false; memcpy(&chKey[0], &chNewKey[0], sizeof chKey); memcpy(&chIV[0], &chNewIV[0], sizeof chIV); fKeySet = true; return true; } bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) { if (!fKeySet) return false; // max ciphertext len for a n bytes of plaintext is // n + AES_BLOCK_SIZE - 1 bytes int nLen = vchPlaintext.size(); int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; vchCiphertext = std::vector<unsigned char> (nCLen); EVP_CIPHER_CTX ctx; bool fOk = true; EVP_CIPHER_CTX_init(&ctx); if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen); if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); if (!fOk) return false; vchCiphertext.resize(nCLen + nFLen); return true; } bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) { if (!fKeySet) return false; // plaintext will always be equal to or lesser than length of ciphertext int nLen = vchCiphertext.size(); int nPLen = nLen, nFLen = 0; vchPlaintext = CKeyingMaterial(nPLen); EVP_CIPHER_CTX ctx; bool fOk = true; EVP_CIPHER_CTX_init(&ctx); if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen); if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen); EVP_CIPHER_CTX_cleanup(&ctx); if (!fOk) return false; vchPlaintext.resize(nPLen + nFLen); return true; } bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext); } bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext) { CCrypter cKeyCrypter; std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE); memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); if(!cKeyCrypter.SetKey(vMasterKey, chIV)) return false; return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); } bool CCryptoKeyStore::SetCrypted() { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; CKey key; key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); if (key.GetPubKey() == vchPubKey) break; return false; } vMasterKey = vMasterKeyIn; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKeyPubKey(key, pubkey); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CKeyingMaterial vchSecret(key.begin(), key.end()); if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(pubkey, vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CKeyingMaterial vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed()); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys) { const CKey &key = mKey.second; CPubKey vchPubKey = key.GetPubKey(); CKeyingMaterial vchSecret(key.begin(), key.end()); std::vector<unsigned char> vchCryptedSecret; if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; }
storecoin/storecoin
src/crypter.cpp
C++
mit
8,248
require 'spec_helper' module Fooltip describe Association do it { should belong_to(:owner) } it { should belong_to(:container) } it { should validate_presence_of :owner_id } it { should validate_presence_of :owner_type } it { should validate_presence_of :container_id } it { should validate_uniqueness_of(:owner_id).scoped_to(:owner_type, :container_id) } context "an instance of an ActiveRecord class calling 'has_fooltips'" do let(:tf) { TestFooltip.new } it "should respond to :fooltips" do tf.should respond_to :fooltips end it "should not have any fooltips before any have been added" do tf.fooltips.should be_empty end end end end
intesys/fooltip
spec/models/fooltip/association_spec.rb
Ruby
mit
724
# Author: Samuel Genheden, samuel.genheden@gmail.com """ Program to build lipids from a template, similarly to MARTINI INSANE Is VERY experimental! """ import argparse import os import xml.etree.ElementTree as ET import numpy as np from sgenlib import pdb class BeadDefinition(object): def __init__(self): self.name = None self.xyz = None def parse(self, element): if "name" in element.attrib: self.name = element.attrib["name"] else: return if "xyz" in element.attrib: self.xyz = np.array(element.attrib["xyz"].split(), dtype=float) def __str__(self): return "%s (%s)"%(self.name,",".join("%.2f"%c for c in self.xyz)) class LipidTemplate(object): def __init__(self): self.name = None self.beads = [] self.headname = [] self.tailname = [] self.head = [] self.tail = [] def make(self, bd=3.0): struct = pdb.PDBFile() res = pdb.Residue() for i, bead in enumerate(self.beads): atom = pdb.Atom() atom.idx = i atom.serial = i + 1 atom.name = bead.name atom.resname = self.name atom.residue = 1 atom.set_xyz(bead.xyz*bd) res.atoms.append(atom) struct.atoms.append(atom) struct.residues.append(res) allcoord = np.asarray([a.xyz for a in struct.atoms]) offset = allcoord.mean(axis=0) + 50.0 for a in struct.atoms: a.set_xyz(a.xyz+offset) struct.box = np.asarray([100,100,100]) return struct def parse(self, element): if "name" in element.attrib: self.name = element.attrib["name"] else: return if "head" in element.attrib: self.headname = element.attrib["head"].split() if "tail" in element.attrib: self.tailname = element.attrib["tail"].split() for child in element: if child.tag != "bead": continue b = BeadDefinition() b.parse(child) if b.name is not None: self.beads.append(b) if b.name in self.headname : self.head.append(b) elif b.name in self.tailname : self.tail.append(b) def __str__(self): return self.name+"\n\t"+"\n\t".join(b.__str__() for b in self.beads) class LipidCollection(object): def __init__(self): self.lipids = {} def load(self, filename): tree = ET.parse(filename) # Parse lipids for child in tree.getroot(): if child.tag != "lipid": continue lipid = LipidTemplate() lipid.parse(child) if lipid.name is not None: self.lipids[lipid.name] = lipid if __name__ == '__main__' : parser = argparse.ArgumentParser(description="Building lipids from templates") parser.add_argument('-l','--lipid',help="the lipid to build") parser.add_argument('-x','--xml',help="the definition of templates") parser.add_argument('-o','--out',help="the output name",default="lipid.pdb") parser.add_argument('--bd',type=float,help="the spacing between beads",default=3.0) args = parser.parse_args() lipidbook = LipidCollection() if args.xml is None: thispath = os.path.dirname(os.path.abspath(__file__)) args.xml = os.path.join(thispath,"lipid_templates.xml") lipidbook.load(args.xml) if args.lipid in lipidbook.lipids: struct = lipidbook.lipids[args.lipid].make(bd=args.bd) struct.write(args.out) else: "%s not in the XML file"%args.lipid
SGenheden/Scripts
Membrane/build_lipid.py
Python
mit
3,765
"use strict"; var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic'); var app_module_1 = require('./app/app.module'); //enableProdMode(); //Uncomment for production document.addEventListener('WebComponentsReady', function () { platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule) .then(function (success) { return console.log('App bootstrapped'); }) .catch(function (err) { return console.error(err); }); }); /* var webComponentsFlag = false; document.addEventListener('WebComponentsReady',() =>{ if (!webComponentsFlag) platformBrowserDynamic().bootstrapModule(AppModule); webComponentsFlag = true; }); if (webComponentsFlag) platformBrowserDynamic().bootstrapModule(AppModule);*/
mockii/mockii_node
src/main.js
JavaScript
mit
784
--- layout: post microblog: true audio: date: 2018-10-30 07:06:05 -0600 guid: http://craigmcclellan.micro.blog/2018/10/30/happy-th-anniversary.html --- Happy 8th Anniversary @laura_mcclellan! Thanks for marrying me love. <img src="http://craigmcclellan.com/uploads/2018/41ec1ea48a.jpg" width="600" height="400" />
craigwmcclellan/craigwmcclellan.github.io
_posts/2018-10-30-happy-th-anniversary.md
Markdown
mit
316
Job-Offers ========== Offline Angular based Javascript / HTML / CSS app with localstorage for tracking Job offers, applications and interviews
digitalgravy/Job-Offers
README.md
Markdown
mit
144
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ShowCar : Car { private int stars; public ShowCar(string brand, string model, int yearOfProduction, int horsepower, int acceleration, int suspension, int durability) : base(brand, model, yearOfProduction, horsepower, acceleration, suspension, durability) { } public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.AppendLine($"{stars} *"); return sb.ToString(); } public override void Tune(int tuneIndex, string addOn) { base.Tune(tuneIndex, addOn); this.stars += tuneIndex; } }
Plotso/SoftUni
CSharpOOP Basics-Exams/NFS/NFS/Entities/Cars/ShowCar.cs
C#
mit
750
/** ****************************************************************************** * @file usb_conf.h * @author MCD Application Team * @version V4.0.0 * @date 21-January-2013 * @brief Virtual COM Port Demo configuration header ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2013 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_CONF_H #define __USB_CONF_H #include "platform_config.h" /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ /* External variables --------------------------------------------------------*/ /*-------------------------------------------------------------*/ /* EP_NUM */ /* defines how many endpoints are used by the device */ /*-------------------------------------------------------------*/ #define EP_NUM (4) /*-------------------------------------------------------------*/ /* -------------- Buffer Description Table -----------------*/ /*-------------------------------------------------------------*/ /* buffer table base address */ #define BTABLE_ADDRESS (0x00) /* EP0 */ /* rx/tx buffer base address */ #define ENDP0_RXADDR (0x20) #define ENDP0_TXADDR (0x60) #define ENDP0_SIZE (0x40) /* EP1 */ /* tx buffer base address */ #define ENDP1_TXADDR (0xA0) #define ENDP1_TXSIZE (0x8) /* EP2 */ /* tx buffer base address */ #define ENDP2_TXADDR (0x100) #define ENDP2_RXSIZE (0x40) /* EP3 */ /* rx buffer base address */ #define ENDP3_RXADDR (0x140) #define ENDP3_RXSIZE (0x40) /*-------------------------------------------------------------*/ /* ------------------- ISTR events -------------------------*/ /*-------------------------------------------------------------*/ /* IMR_MSK */ /* mask defining which events has to be handled */ /* by the device application software */ #define IMR_MSK (CNTR_CTRM | CNTR_RESETM | CNTR_SOFM /*| CNTR_WKUPM | CNTR_SUSPM | CNTR_ERRM | CNTR_ESOFM*/) //#define CTR_CALLBACK //#define DOVR_CALLBACK //#define ERR_CALLBACK //#define WKUP_CALLBACK //#define SUSP_CALLBACK //#define RESET_CALLBACK #define SOF_CALLBACK //#define ESOF_CALLBACK /* CTR service routines */ /* associated to defined endpoints */ //#define EP1_IN_Callback NOP_Process //#define EP2_IN_Callback NOP_Process #define EP3_IN_Callback NOP_Process #define EP4_IN_Callback NOP_Process #define EP5_IN_Callback NOP_Process #define EP6_IN_Callback NOP_Process #define EP7_IN_Callback NOP_Process #define EP1_OUT_Callback NOP_Process #define EP2_OUT_Callback NOP_Process //#define EP3_OUT_Callback NOP_Process #define EP4_OUT_Callback NOP_Process #define EP5_OUT_Callback NOP_Process #define EP6_OUT_Callback NOP_Process #define EP7_OUT_Callback NOP_Process #endif /*__USB_CONF_H*/ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
eleqian/WiDSO
MCU/VirtualCOMPort/usb/usb_conf.h
C
mit
4,073
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; 7875cd80-14cf-464e-8cda-e04cc534d262 </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#Deedle.RProvider.Plugin">Deedle.RProvider.Plugin</a></strong></td> <td class="text-center">98.74 %</td> <td class="text-center">98.74 %</td> <td class="text-center">100.00 %</td> <td class="text-center">98.74 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="Deedle.RProvider.Plugin"><h3>Deedle.RProvider.Plugin</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Array</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>create a new System.Collections.ObjectModel.ReadOnlyCollection&lt;T&gt; using the Array as arguments</td> </tr> <tr> <td style="padding-left:2em">AsReadOnly``1(``0[])</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td>create a new System.Collections.ObjectModel.ReadOnlyCollection&lt;T&gt; using the Array as arguments</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.ComponentModel.Composition.ExportAttribute</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">#ctor(System.Type)</td> <td class="IconErrorEncoded"></td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconErrorEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
kuhlenh/port-to-core
Reports/de/deedle.rplugin.1.2.0/Deedle.RProvider.Plugin-net40.html
HTML
mit
13,096
//==================================================================================== // // Purpose: Provide basic touch detection of controller to interactable objects // // This script must be attached to a Controller within the [CameraRig] Prefab // //==================================================================================== namespace VRTK { using UnityEngine; using System.Collections; public struct ObjectInteractEventArgs { public uint controllerIndex; public GameObject target; } public delegate void ObjectInteractEventHandler(object sender, ObjectInteractEventArgs e); [RequireComponent(typeof(VRTK_ControllerActions))] public class VRTK_InteractTouch : MonoBehaviour { public bool hideControllerOnTouch = false; public float hideControllerDelay = 0f; public Color globalTouchHighlightColor = Color.clear; public GameObject customRigidbodyObject; public event ObjectInteractEventHandler ControllerTouchInteractableObject; public event ObjectInteractEventHandler ControllerUntouchInteractableObject; private GameObject touchedObject = null; private GameObject lastTouchedObject = null; private SteamVR_TrackedObject trackedController; private VRTK_ControllerActions controllerActions; private GameObject controllerRigidBodyObject; private bool triggerRumble; public virtual void OnControllerTouchInteractableObject(ObjectInteractEventArgs e) { if (ControllerTouchInteractableObject != null) ControllerTouchInteractableObject(this, e); } public virtual void OnControllerUntouchInteractableObject(ObjectInteractEventArgs e) { if (ControllerUntouchInteractableObject != null) ControllerUntouchInteractableObject(this, e); } public ObjectInteractEventArgs SetControllerInteractEvent(GameObject target) { ObjectInteractEventArgs e; e.controllerIndex = (uint)trackedController.index; e.target = target; return e; } public void ForceTouch(GameObject obj) { if (obj.GetComponent<Collider>()) { OnTriggerStay(obj.GetComponent<Collider>()); } else if (obj.GetComponentInChildren<Collider>()) { OnTriggerStay(obj.GetComponentInChildren<Collider>()); } } public GameObject GetTouchedObject() { return touchedObject; } public bool IsObjectInteractable(GameObject obj) { return (obj && (obj.GetComponent<VRTK_InteractableObject>() || obj.GetComponentInParent<VRTK_InteractableObject>())); } public void ToggleControllerRigidBody(bool state) { if (controllerRigidBodyObject && controllerRigidBodyObject.GetComponent<Rigidbody>()) { controllerRigidBodyObject.GetComponent<Rigidbody>().detectCollisions = state; } } public void ForceStopTouching() { if (touchedObject != null) { StopTouching(touchedObject); } } private void Awake() { trackedController = GetComponent<SteamVR_TrackedObject>(); controllerActions = GetComponent<VRTK_ControllerActions>(); } private void Start() { if (GetComponent<VRTK_ControllerActions>() == null) { Debug.LogError("VRTK_InteractTouch is required to be attached to a SteamVR Controller that has the VRTK_ControllerActions script attached to it"); return; } Utilities.SetPlayerObject(this.gameObject, VRTK_PlayerObject.ObjectTypes.Controller); CreateTouchCollider(this.gameObject); CreateControllerRigidBody(); triggerRumble = false; } private void OnTriggerEnter(Collider collider) { if (IsObjectInteractable(collider.gameObject) && (touchedObject == null || !touchedObject.GetComponent<VRTK_InteractableObject>().IsGrabbed())) { lastTouchedObject = collider.gameObject; } } private void OnTriggerStay(Collider collider) { if (touchedObject != null && touchedObject != lastTouchedObject && !touchedObject.GetComponent<VRTK_InteractableObject>().IsGrabbed()) { ForceStopTouching(); } if (touchedObject == null && IsObjectInteractable(collider.gameObject)) { if (collider.gameObject.GetComponent<VRTK_InteractableObject>()) { touchedObject = collider.gameObject; } else { touchedObject = collider.gameObject.GetComponentInParent<VRTK_InteractableObject>().gameObject; } var touchedObjectScript = touchedObject.GetComponent<VRTK_InteractableObject>(); if (!touchedObjectScript.IsValidInteractableController(this.gameObject, touchedObjectScript.allowedTouchControllers)) { touchedObject = null; return; } OnControllerTouchInteractableObject(SetControllerInteractEvent(touchedObject)); touchedObjectScript.ToggleHighlight(true, globalTouchHighlightColor); touchedObjectScript.StartTouching(this.gameObject); if (controllerActions.IsControllerVisible() && hideControllerOnTouch) { Invoke("HideController", hideControllerDelay); } var rumbleAmount = touchedObjectScript.rumbleOnTouch; if (!rumbleAmount.Equals(Vector2.zero) && !triggerRumble) { triggerRumble = true; controllerActions.TriggerHapticPulse((ushort)rumbleAmount.y, rumbleAmount.x, 0.05f); Invoke("ResetTriggerRumble", rumbleAmount.x); } } } private void ResetTriggerRumble() { triggerRumble = false; } private bool IsColliderChildOfTouchedObject(GameObject collider) { if (touchedObject != null && collider.GetComponentInParent<VRTK_InteractableObject>() && collider.GetComponentInParent<VRTK_InteractableObject>().gameObject == touchedObject) { return true; } return false; } private void OnTriggerExit(Collider collider) { if (touchedObject != null && (touchedObject == collider.gameObject || IsColliderChildOfTouchedObject(collider.gameObject))) { StopTouching(collider.gameObject); } } private void StopTouching(GameObject obj) { if (IsObjectInteractable(obj)) { GameObject untouched; if (obj.GetComponent<VRTK_InteractableObject>()) { untouched = obj; } else { untouched = obj.GetComponentInParent<VRTK_InteractableObject>().gameObject; } OnControllerUntouchInteractableObject(SetControllerInteractEvent(untouched.gameObject)); untouched.GetComponent<VRTK_InteractableObject>().ToggleHighlight(false); untouched.GetComponent<VRTK_InteractableObject>().StopTouching(this.gameObject); } if (hideControllerOnTouch) { controllerActions.ToggleControllerModel(true, touchedObject); } touchedObject = null; } private void CreateTouchCollider(GameObject obj) { var collider = this.GetComponent<Collider>(); if(collider == null) { var genCollider = obj.AddComponent<SphereCollider>(); genCollider.radius = 0.06f; genCollider.center = new Vector3(0f, -0.04f, 0f); collider = genCollider; } collider.isTrigger = true; } private void CreateBoxCollider(GameObject obj, Vector3 center, Vector3 size) { BoxCollider bc = obj.AddComponent<BoxCollider>(); bc.size = size; bc.center = center; } private void HideController() { if (touchedObject != null) { controllerActions.ToggleControllerModel(false, touchedObject); } } private void CreateControllerRigidBody() { if (customRigidbodyObject != null) { controllerRigidBodyObject = customRigidbodyObject; } else { controllerRigidBodyObject = new GameObject(); CreateBoxCollider(controllerRigidBodyObject, new Vector3(0f, -0.01f, -0.098f), new Vector3(0.04f, 0.025f, 0.15f)); CreateBoxCollider(controllerRigidBodyObject, new Vector3(0f, -0.009f, -0.002f), new Vector3(0.05f, 0.025f, 0.04f)); CreateBoxCollider(controllerRigidBodyObject, new Vector3(0f, -0.024f, 0.01f), new Vector3(0.07f, 0.02f, 0.02f)); CreateBoxCollider(controllerRigidBodyObject, new Vector3(0f, -0.045f, 0.022f), new Vector3(0.07f, 0.02f, 0.022f)); CreateBoxCollider(controllerRigidBodyObject, new Vector3(0f, -0.0625f, 0.03f), new Vector3(0.065f, 0.015f, 0.025f)); CreateBoxCollider(controllerRigidBodyObject, new Vector3(0.045f, -0.035f, 0.005f), new Vector3(0.02f, 0.025f, 0.025f)); CreateBoxCollider(controllerRigidBodyObject, new Vector3(-0.045f, -0.035f, 0.005f), new Vector3(0.02f, 0.025f, 0.025f)); var createRB = controllerRigidBodyObject.AddComponent<Rigidbody>(); createRB.mass = 100f; } var controllerRB = controllerRigidBodyObject.GetComponent<Rigidbody>(); controllerRigidBodyObject.name = string.Format("[{0}]_RigidBody_Holder", this.gameObject.name); controllerRigidBodyObject.transform.parent = this.transform; controllerRigidBodyObject.transform.localPosition = Vector3.zero; controllerRB.useGravity = false; controllerRB.isKinematic = false; controllerRB.collisionDetectionMode = CollisionDetectionMode.Continuous; controllerRB.constraints = RigidbodyConstraints.FreezeAll; ToggleControllerRigidBody(false); } } }
morgan3d/misc
tachyonVR/Assets/SteamVR_Unity_Toolkit/Scripts/VRTK_InteractTouch.cs
C#
mit
10,886
// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "04954704af281700db0de173a257396b39fbe48fd357edaa8d57a2c00d137782b50bf9885d34d3b4c6a20164714693e80e5447423ea27f539de384b3fed3f336c2"; static const char* pszTestKey = "0484e4e040707affc5d90b9d06108a96c173a4665fd483f91e31cc97431ad5782abfeaead8df64764b99533f22866a6e763a425e89da4eb5c7e33c3075825b8005"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return Hash(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CPubKey key(ParseHex(fTestNet ? pszTestKey : pszMainKey)); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; }
b-desconocido/bdc-project
src/alert.cpp
C++
mit
7,387
// // NSAttributedString+MUSExtraMethods.h // MuseApp // // Created by Leo Kwan on 9/18/15. // Copyright © 2015 Leo Kwan. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface NSAttributedString (MUSExtraMethods) +(NSAttributedString *)returnMarkDownStringFromString:(NSString *)string; +(NSAttributedString *)returnAttrTagWithTitle:(NSString *)title color:(UIColor *)color undelineColor:(UIColor *)lineColor; +(NSAttributedString *)returnStringWithTitle:(NSString *)title color:(UIColor *)color undelineColor:(UIColor *)lineColor fontSize:(CGFloat)size; @end
leojkwan/MuseApp
MuseJournal/NSAttributedString+MUSExtraMethods.h
C
mit
607
/** * Copyright (c) 2013 Andre Ricardo Schaffer * * Permission is hereby granted, free of charge, to any person obtaining 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, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE 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. */ package com.github.wiselenium.testng; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import com.github.wiselenium.WiseContext; import com.github.wiselenium.Wiselenium; import com.github.wiselenium.factory.WisePageFactory; import com.github.wiselenium.testng.annotation.Page; import com.github.wiselenium.testng.exception.PageInjectionException; import com.github.wiselenium.testng.exception.ScreenShotException; /** * All wiselenium TestNG tests should extend this class. * * @param <T> The type of the test. * @author Andre Ricardo Schaffer * @since 0.3.0 */ @Listeners(WiseTestListener.class) public class WiseTest implements WiseQuery, WiseWait, WiseScreenShoot { private WebDriver driver; @BeforeClass public void setUpWiseTest() { this.driver = this.initDriver(); WiseContext.setDriver(this.driver); this.injectPageFieldsIntoTest(this); } @AfterClass(alwaysRun = true) public void tearDownWiseTest() { if (this.driver != null) this.driver.quit(); } /** * Inits the driver instance for the test. <br/> * May be overridden. By default, inits a FirefoxDriver. * * @return The instance of the driver for the test. * @since 0.3.0 */ public WebDriver initDriver() { return new FirefoxDriver(); } private void injectPageFieldsIntoTest(WiseTest testInstance) { for (Class<?> clazz = testInstance.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { for (Field field : clazz.getDeclaredFields()) { this.injectPageFieldIntoTest(field, testInstance); } } } private void injectPageFieldIntoTest(Field field, WiseTest testInstance) { if (!field.isAnnotationPresent(Page.class)) return; field.setAccessible(true); Object page = testInstance.initElements(field.getType()); try { field.set(testInstance, page); } catch (Exception e) { throw new PageInjectionException(field.getType(), this.getClass(), e); } } /** * Returns the driver of the test. * * @return The driver of the test. * @since 0.3.0 */ public WebDriver getDriver() { return this.driver; } @Override public <E> E findElement(Class<E> clazz, By by) { return Wiselenium.findElement(clazz, by, this.driver); } @Override public <E> List<E> findElements(Class<E> clazz, By by) { return Wiselenium.findElements(clazz, by, this.driver); } /** * Loads a new web page in the current browser window using a HTTP GET operation. * * @param url The URL to load. It is best to use a fully qualified URL. * @return This page object. * @since 0.3.0 */ public void get(String url) { if (url != null) this.driver.get(url); } /** * Instantiates an instance of the given class, and set a lazy proxy for each of its element * fields. <br/> * * @param <E> The class type that will be initialized. * @param clazz The class to be initialized. * @return An instance of the class with its element fields proxied. * @since 0.3.0 * @see WisePageFactory#initElements(WebDriver, Class) */ public <E> E initElements(Class<E> clazz) { return WisePageFactory.initElements(this.driver, clazz); } /** * As initElements(Class) but will only replace the element fields of an already instantiated * Object. * * @param <E> The type of the instance. * @param instance The instance whose fields should be proxied. * @return The instance with its element fields proxied. * @since 0.3.0 */ public <E> E initElements(E instance) { return WisePageFactory.initElements(this.driver, instance); } @Override public WebDriverWait waitFor(long timeOutInSeconds) { return new WebDriverWait(this.driver, timeOutInSeconds); } @Override public WebDriverWait waitFor(long timeOutInSeconds, long sleepInMillis) { return new WebDriverWait(this.driver, timeOutInSeconds, sleepInMillis); } @Override public void takeScreenShot(String fileName) { File scrFile = ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE); try { File destFile = new File(fileName); FileUtils.copyFile(scrFile, destFile); } catch (IOException e) { throw new ScreenShotException(e); } } /** * Returns the dir where the test failure screenshots will be saved. <br/> * May be overridden. By default, returns "target/test-failure-screenshots/" . * * @return The dir where the test failure screenshots will be saved. * @since 0.3.0 */ public String getTestFailureScreenShotPath() { return "target/test-failure-screenshots/"; } }
wiselenium/wiselenium
wiselenium-testng/src/main/java/com/github/wiselenium/testng/WiseTest.java
Java
mit
6,098
using System.Collections.Generic; using mongoDB4.net.HelloMongo.Models; namespace mongoDB4.net.HelloMongo.Repositories { public interface ICommentsRepository { Comment Save(Comment comment); IEnumerable<Comment> GetAll(); } }
MatthewNichols/mongo4.NET
src/HelloMongo/mongoDB4.net.HelloMongo/Repositories/ICommentsRepository.cs
C#
mit
257
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2016, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ #include "UnitTestPCH.h" #include "../../include/assimp/postprocess.h" #include "../../include/assimp/scene.h" #include <assimp/Importer.hpp> #include <BaseImporter.h> #include "TestIOSystem.h" #include <assimp/DefaultIOSystem.h> using namespace ::std; using namespace ::Assimp; class ImporterTest : public ::testing::Test { public: virtual void SetUp() { pImp = new Importer(); } virtual void TearDown() { delete pImp; } protected: Importer* pImp; }; #define InputData_BLOCK_SIZE 1310 // test data for Importer::ReadFileFromMemory() - ./test/3DS/CameraRollAnim.3ds static unsigned char InputData_abRawBlock[1310] = { 77,77,30,5,0,0,2,0,10,0,0,0,3,0,0,0,61,61,91,3,0,0,62,61,10,0,0,0,3,0,0,0, 0,1,10,0,0,0,0,0,128,63,0,64,254,2,0,0,66,111,120,48,49,0,0,65,242,2,0,0,16,65,64,1, 0,0,26,0,102,74,198,193,102,74,198,193,0,0,0,0,205,121,55,66,102,74,198,193,0,0,0,0,102,74,198,193, 138,157,184,65,0,0,0,0,205,121,55,66,138,157,184,65,0,0,0,0,102,74,198,193,102,74,198,193,90,252,26,66, 205,121,55,66,102,74,198,193,90,252,26,66,102,74,198,193,138,157,184,65,90,252,26,66,205,121,55,66,138,157,184,65, 90,252,26,66,102,74,198,193,102,74,198,193,0,0,0,0,205,121,55,66,102,74,198,193,0,0,0,0,205,121,55,66, 102,74,198,193,90,252,26,66,205,121,55,66,102,74,198,193,90,252,26,66,102,74,198,193,102,74,198,193,90,252,26,66, 102,74,198,193,102,74,198,193,0,0,0,0,205,121,55,66,138,157,184,65,0,0,0,0,205,121,55,66,102,74,198,193, 90,252,26,66,205,121,55,66,138,157,184,65,0,0,0,0,102,74,198,193,138,157,184,65,0,0,0,0,102,74,198,193, 138,157,184,65,90,252,26,66,102,74,198,193,138,157,184,65,90,252,26,66,205,121,55,66,138,157,184,65,90,252,26,66, 205,121,55,66,138,157,184,65,0,0,0,0,102,74,198,193,138,157,184,65,0,0,0,0,102,74,198,193,102,74,198,193, 90,252,26,66,102,74,198,193,102,74,198,193,90,252,26,66,102,74,198,193,138,157,184,65,0,0,0,0,64,65,216,0, 0,0,26,0,0,0,128,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,63,0,0,128,63,0,0,0,0, 0,0,128,63,0,0,0,0,0,0,0,0,0,0,128,63,0,0,0,0,0,0,0,0,0,0,128,63,0,0,128,63, 0,0,128,63,0,0,0,0,0,0,0,0,0,0,128,63,0,0,0,0,0,0,128,63,0,0,128,63,0,0,128,63, 0,0,128,63,0,0,0,0,0,0,128,63,0,0,0,0,0,0,0,0,0,0,128,63,0,0,0,0,0,0,0,0, 0,0,128,63,0,0,0,0,0,0,0,0,0,0,128,63,0,0,0,0,0,0,128,63,0,0,128,63,0,0,128,63, 0,0,128,63,0,0,0,0,0,0,128,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,63, 0,0,128,63,0,0,128,63,0,0,128,63,0,0,0,0,0,0,0,0,96,65,54,0,0,0,0,0,128,63,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,128,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,63,53,169, 40,65,176,205,90,191,0,0,0,0,32,65,158,0,0,0,12,0,0,0,2,0,3,0,6,0,3,0,1,0,0,0, 6,0,4,0,5,0,7,0,6,0,7,0,6,0,4,0,6,0,8,0,9,0,10,0,6,0,11,0,12,0,13,0, 6,0,1,0,14,0,7,0,6,0,7,0,15,0,1,0,6,0,16,0,17,0,18,0,6,0,19,0,20,0,21,0, 6,0,22,0,0,0,23,0,6,0,24,0,6,0,25,0,6,0,80,65,54,0,0,0,2,0,0,0,2,0,0,0, 4,0,0,0,4,0,0,0,8,0,0,0,8,0,0,0,16,0,0,0,16,0,0,0,32,0,0,0,32,0,0,0, 64,0,0,0,64,0,0,0,0,64,67,0,0,0,67,97,109,101,114,97,48,49,0,0,71,52,0,0,0,189,19,25, 195,136,104,81,64,147,56,182,65,96,233,20,194,67,196,97,190,147,56,182,65,0,0,0,0,85,85,85,66,32,71,14, 0,0,0,0,0,0,0,0,0,122,68,0,176,179,1,0,0,10,176,21,0,0,0,5,0,77,65,88,83,67,69,78, 69,0,44,1,0,0,8,176,14,0,0,0,0,0,0,0,44,1,0,0,9,176,10,0,0,0,128,2,0,0,2,176, 168,0,0,0,48,176,8,0,0,0,0,0,16,176,18,0,0,0,66,111,120,48,49,0,0,64,0,0,255,255,19,176, 18,0,0,0,0,0,0,128,0,0,0,128,0,0,0,128,32,176,38,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,53,169,40,65,176,205,90,191,0,0,0,0,33,176,42,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 34,176,38,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,128,63,0,0, 128,63,0,0,128,63,3,176,143,0,0,0,48,176,8,0,0,0,1,0,16,176,21,0,0,0,67,97,109,101,114,97, 48,49,0,0,64,0,0,255,255,32,176,38,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,0,0,189,19,25,195,136,104,81,64,147,56,182,65,35,176,30,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,52,66,36,176,40,0,0,0,0,0,0,0,0,0,120,0,0,0,2,0,0, 0,0,0,0,0,0,0,120,13,90,189,120,0,0,0,0,0,99,156,154,194,4,176,73,0,0,0,48,176,8,0,0, 0,2,0,16,176,21,0,0,0,67,97,109,101,114,97,48,49,0,0,64,0,0,255,255,32,176,38,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,96,233,20,194,67,196,97,190,147,56,182,65, }; #define AIUT_DEF_ERROR_TEXT "sorry, this is a test" static const aiImporterDesc desc = { "UNIT TEST - IMPORTER", "", "", "", 0, 0, 0, 0, 0, "apple mac linux windows" }; class TestPlugin : public BaseImporter { public: virtual bool CanRead( const std::string& pFile, IOSystem* /*pIOHandler*/, bool /*test*/) const { std::string::size_type pos = pFile.find_last_of('.'); // no file extension - can't read if( pos == std::string::npos) return false; std::string extension = pFile.substr( pos); // todo ... make case-insensitive return (extension == ".apple" || extension == ".mac" || extension == ".linux" || extension == ".windows" ); } virtual const aiImporterDesc* GetInfo () const { return & desc; } virtual void InternReadFile( const std::string& /*pFile*/, aiScene* /*pScene*/, IOSystem* /*pIOHandler*/) { throw DeadlyImportError(AIUT_DEF_ERROR_TEXT); } }; // ------------------------------------------------------------------------------------------------ TEST_F(ImporterTest, testMemoryRead) { const aiScene* sc = pImp->ReadFileFromMemory(InputData_abRawBlock,InputData_BLOCK_SIZE, aiProcessPreset_TargetRealtime_Quality,"3ds"); ASSERT_TRUE(sc != NULL); EXPECT_EQ(aiString("<3DSRoot>"), sc->mRootNode->mName); EXPECT_EQ(1U, sc->mNumMeshes); EXPECT_EQ(24U, sc->mMeshes[0]->mNumVertices); EXPECT_EQ(12U, sc->mMeshes[0]->mNumFaces); } // ------------------------------------------------------------------------------------------------ TEST_F(ImporterTest, testIntProperty) { bool b = pImp->SetPropertyInteger("quakquak",1503); EXPECT_FALSE(b); EXPECT_EQ(1503, pImp->GetPropertyInteger("quakquak",0)); EXPECT_EQ(314159, pImp->GetPropertyInteger("not_there",314159)); b = pImp->SetPropertyInteger("quakquak",1504); EXPECT_TRUE(b); } // ------------------------------------------------------------------------------------------------ TEST_F(ImporterTest, testFloatProperty) { bool b = pImp->SetPropertyFloat("quakquak",1503.f); EXPECT_TRUE(!b); EXPECT_EQ(1503.f, pImp->GetPropertyFloat("quakquak",0.f)); EXPECT_EQ(314159.f, pImp->GetPropertyFloat("not_there",314159.f)); } // ------------------------------------------------------------------------------------------------ TEST_F(ImporterTest, testStringProperty) { bool b = pImp->SetPropertyString("quakquak","test"); EXPECT_TRUE(!b); EXPECT_EQ("test", pImp->GetPropertyString("quakquak","weghwekg")); EXPECT_EQ("ILoveYou", pImp->GetPropertyString("not_there","ILoveYou")); } // ------------------------------------------------------------------------------------------------ TEST_F(ImporterTest, testPluginInterface) { pImp->RegisterLoader(new TestPlugin()); EXPECT_TRUE(pImp->IsExtensionSupported(".apple")); EXPECT_TRUE(pImp->IsExtensionSupported(".mac")); EXPECT_TRUE(pImp->IsExtensionSupported("*.linux")); EXPECT_TRUE(pImp->IsExtensionSupported("windows")); EXPECT_TRUE(pImp->IsExtensionSupported(".x")); /* x and 3ds must be available in this Assimp build, of course! */ EXPECT_TRUE(pImp->IsExtensionSupported(".3ds")); EXPECT_FALSE(pImp->IsExtensionSupported(".")); TestPlugin* p = (TestPlugin*) pImp->GetImporter(".windows"); ASSERT_TRUE(NULL != p); try { p->InternReadFile("",0,NULL); } catch ( const DeadlyImportError& dead) { EXPECT_TRUE(!strcmp(dead.what(),AIUT_DEF_ERROR_TEXT)); // unregister the plugin and delete it pImp->UnregisterLoader(p); delete p; return; } EXPECT_TRUE(false); // control shouldn't reach this point } // ------------------------------------------------------------------------------------------------ TEST_F(ImporterTest, testExtensionCheck) { std::string s; pImp->GetExtensionList(s); // TODO } // ------------------------------------------------------------------------------------------------ TEST_F(ImporterTest, testMultipleReads) { // see http://sourceforge.net/projects/assimp/forums/forum/817654/topic/3591099 // Check whether reading and post-processing multiple times using // the same objects is *generally* fine. This test doesn't target // importers. Testing post-processing stability is the main point. const unsigned int flags = aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_GenSmoothNormals | aiProcess_ValidateDataStructure | aiProcess_RemoveRedundantMaterials | aiProcess_SortByPType | aiProcess_FindDegenerates | aiProcess_FindInvalidData | aiProcess_GenUVCoords | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph; EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/test.x",flags)); //EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/dwarf.x",flags)); # is in nonbsd EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/Testwuson.X",flags)); EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/anim_test.x",flags)); //EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/dwarf.x",flags)); # is in nonbsd EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/anim_test.x",flags)); EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/BCN_Epileptic.X",flags)); //EXPECT_TRUE(pImp->ReadFile(ASSIMP_TEST_MODELS_DIR "/X/dwarf.x",flags)); # is in nonbsd } TEST_F( ImporterTest, SearchFileHeaderForTokenTest ) { //DefaultIOSystem ioSystem; // BaseImporter::SearchFileHeaderForToken( &ioSystem, assetPath, Token, 2 ) }
forifelse/fispTools
assimp/test/unit/utImporter.cpp
C++
mit
11,856
'use strict'; var util = require('util'), errors = module.exports = {}; errors.BaseError = function() { var tmp = Error.apply(this, arguments); tmp.name = this.name = 'QMFError'; this.message = tmp.message; if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); }; util.inherits(errors.BaseError, Error); errors.AgentExceptionError = function(values) { var errorText = (values.error_text instanceof Buffer) ? values.error_text.toString() : values.error_text; errors.BaseError.call(this, errorText); this.name = 'QMFAgentExceptionError'; this.errorCode = values.error_code; this.errorText = errorText; }; util.inherits(errors.AgentExceptionError, errors.BaseError); errors.InvalidResponseError = function(opcode) { errors.BaseError.call(this, opcode); this.name = 'QMFInvalidResponseError'; this.opcode = opcode; }; util.inherits(errors.InvalidResponseError, errors.BaseError); errors.TimeoutError = function() { errors.BaseError.call(this, 'request timed out'); this.name = 'QMFTimeoutError'; }; util.inherits(errors.TimeoutError, errors.BaseError);
mbroadst/node-qmf2
lib/errors.js
JavaScript
mit
1,120
# testifix [![npm version][npm-image]][npm-url] > Simple, promise-based unit testing. ## Installation $ npm install testifix ## License MIT [npm-image]: https://img.shields.io/npm/v/testifix.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/testifix
ebednarz/testifix
README.markdown
Markdown
mit
273
import React from "react" type Props = { condition: boolean children: React.ReactElement wrap: (children: React.ReactNode) => JSX.Element } export const Conditional = ({ condition, children, wrap }: Props) => condition ? React.cloneElement(wrap(children)) : children
UgnisSoftware/ugnis
src/components/Conditional/src/Conditional.tsx
TypeScript
mit
277
Slipmat.Views.LabelShow = Backbone.ModularView.extend({ tagName: "main", className: "group", template: JST["labels/show"], initialize: function (options) { this.router = options.router; this.listenTo(this.model, "sync change", this.render); }, events: { "submit": "addComment" }, render: function () { var content = this.template({ label: this.model }); this.$el.html(content); if (Slipmat.currentUser.isSignedIn()) { $textarea = $('<textarea class="form comment-form">'); this.$("#new-comment").prepend($textarea); } this.listContributors(); this.renderComments(); this.renderRecords(); return this; }, renderRecords: function () { var records = this.model.records(), template = JST["records/_record"], header = JST["layouts/_paginationHeader"]({ collection: records }), footer = JST["layouts/_paginationFooter"]({ collection: records }), $el = this.$(".content-records"); this.$(".pagination-header").html(header); this.$(".pagination-footer").html(footer); records.forEach(record => { var subview = template({ model: record }); $el.append(subview); }); } });
cribbles/Slipmat
app/assets/javascripts/views/labels/show.js
JavaScript
mit
1,215
Meteor.startup(function () { // Notification email Router.route('/email/notification/:id?', { name: 'notification', where: 'server', action: function() { var notification = Herald.collection.findOne(this.params.id); var notificationContents = buildEmailNotification(notification); this.response.write(notificationContents.html); this.response.end(); } }); });
haribabuthilakar/fh
packages/telescope-notifications/lib/server/routes.js
JavaScript
mit
425
<!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="keywords" content=" "> <title>Event Structure | LivePerson Technical Documentation</title> <link rel="stylesheet" href="css/syntax.css"> <link rel="stylesheet" type="text/css" href="css/font-awesome-4.7.0/css/font-awesome.min.css"> <!--<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">--> <link rel="stylesheet" href="css/modern-business.css"> <link rel="stylesheet" href="css/lavish-bootstrap.css"> <link rel="stylesheet" href="css/customstyles.css"> <link rel="stylesheet" href="css/theme-blue.css"> <!-- <script src="assets/js/jsoneditor.js"></script> --> <script src="assets/js/jquery-3.1.0.min.js"></script> <!-- <link rel='stylesheet' id='theme_stylesheet' href='//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css'> --> <!-- <link rel='stylesheet' id='theme_stylesheet' href='//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css'> --> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> --> <script src="assets/js/jquery.cookie-1.4.1.min.js"></script> <script src="js/jquery.navgoco.min.js"></script> <script src="assets/js/bootstrap-3.3.4.min.js"></script> <script src="assets/js/anchor-2.0.0.min.js"></script> <script src="js/toc.js"></script> <script src="js/customscripts.js"></script> <link rel="shortcut icon" href="images/favicon.ico"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <link rel="alternate" type="application/rss+xml" title="" href="http://0.0.0.0:4005feed.xml"> <script> $(document).ready(function() { // Initialize navgoco with default options $("#mysidebar").navgoco({ caretHtml: '', accordion: true, openClass: 'active', // open save: false, // leave false or nav highlighting doesn't work right cookie: { name: 'navgoco', expires: false, path: '/' }, slide: { duration: 400, easing: 'swing' } }); $("#collapseAll").click(function(e) { e.preventDefault(); $("#mysidebar").navgoco('toggle', false); }); $("#expandAll").click(function(e) { e.preventDefault(); $("#mysidebar").navgoco('toggle', true); }); }); </script> <script> $(function () { $('[data-toggle="tooltip"]').tooltip() }) </script> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container topnavlinks"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <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="fa fa-home fa-lg navbar-brand" href="index.html">&nbsp;<span class="projectTitle"> LivePerson Technical Documentation</span></a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <!-- entries without drop-downs appear here --> <!-- entries with drop-downs appear here --> <!-- conditional logic to control which topnav appears for the audience defined in the configuration file.--> <li><a class="email" title="Submit feedback" href="https://github.com/LivePersonInc/dev-hub/issues" ><i class="fa fa-github"></i> Issues</a><li> <!--comment out this block if you want to hide search--> <li> <!--start search--> <div id="search-demo-container"> <input type="text" id="search-input" placeholder="search..."> <ul id="results-container"></ul> </div> <script src="js/jekyll-search.js" type="text/javascript"></script> <script type="text/javascript"> SimpleJekyllSearch.init({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), dataSource: 'search.json', searchResultTemplate: '<li><a href="{url}" title="Event Structure">{title}</a></li>', noResultsText: 'No results found.', limit: 10, fuzzy: true, }) </script> <!--end search--> </li> </ul> </div> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <div class="col-lg-12">&nbsp;</div> <!-- Content Row --> <div class="row"> <!-- Sidebar Column --> <div class="col-md-3"> <ul id="mysidebar" class="nav"> <li class="sidebarTitle"> </li> <li> <a href="#">Common Guidelines</a> <ul> <li class="subfolders"> <a href="#">Introduction</a> <ul> <li class="thirdlevel"><a href="index.html">Home</a></li> <li class="thirdlevel"><a href="getting-started.html">Getting Started with LiveEngage APIs</a></li> </ul> </li> <li class="subfolders"> <a href="#">Guides</a> <ul> <li class="thirdlevel"><a href="guides-customizedchat.html">Customized Chat Windows</a></li> </ul> </li> </ul> <li> <a href="#">Account Configuration</a> <ul> <li class="subfolders"> <a href="#">Predefined Content API</a> <ul> <li class="thirdlevel"><a href="account-configuration-predefined-content-overview.html">Overview</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-methods.html">Methods</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-get-items.html">Get Predefined Content Items</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-get-by-id.html">Get Predefined Content by ID</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-query-delta.html">Predefined Content Query Delta</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-create-content.html">Create Predefined Content</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-update-content.html">Update Predefined Content</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-update-content-items.html">Update Predefined Content Items</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-delete-content.html">Delete Predefined Content</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-delete-content-items.html">Delete Predefined Content Items</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-get-default-items.html">Get Default Predefined Content Items</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-get-default-items-by-id.html">Get Default Predefined Content by ID</a></li> <li class="thirdlevel"><a href="account-configuration-predefined-content-appendix.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Automatic Messages API</a> <ul> <li class="thirdlevel"><a href="account-configuration-automatic-messages-overview.html">Overview</a></li> <li class="thirdlevel"><a href="account-configuration-automatic-messages-methods.html">Methods</a></li> <li class="thirdlevel"><a href="account-configuration-automatic-messages-get-automatic-messages.html">Get Automatic Messages</a></li> <li class="thirdlevel"><a href="account-configuration-automatic-messages-get-automatic-message-by-id.html">Get Automatic Message by ID</a></li> <li class="thirdlevel"><a href="account-configuration-automatic-messages-update-an-automatic-message.html">Update an Automatic Message</a></li> <li class="thirdlevel"><a href="account-configuration-automatic-messages-appendix.html">Appendix</a></li> </ul> </li> </ul> <li> <a href="#">Administration</a> <ul> <li class="subfolders"> <a href="#">Users API</a> <ul> <li class="thirdlevel"><a href="administration-users-overview.html">Overview</a></li> <li class="thirdlevel"><a href="administration-users-methods.html">Methods</a></li> <li class="thirdlevel"><a href="administration-get-all-users.html">Get all users</a></li> <li class="thirdlevel"><a href="administration-get-user-by-id.html">Get user by ID</a></li> <li class="thirdlevel"><a href="administration-create-users.html">Create users</a></li> <li class="thirdlevel"><a href="administration-update-users.html">Update users</a></li> <li class="thirdlevel"><a href="administration-update-user.html">Update user</a></li> <li class="thirdlevel"><a href="administration-delete-users.html">Delete users</a></li> <li class="thirdlevel"><a href="administration-delete-user.html">Delete user</a></li> <li class="thirdlevel"><a href="administration-change-users-password.html">Change user's password</a></li> <li class="thirdlevel"><a href="administration-reset-users-password.html">Reset user's password</a></li> <li class="thirdlevel"><a href="administration-user-query-delta.html">User query delta</a></li> <li class="thirdlevel"><a href="administration-users-appendix.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Skills API</a> <ul> <li class="thirdlevel"><a href="administration-skills-overview.html">Overview</a></li> <li class="thirdlevel"><a href="administration-skills-methods.html">Methods</a></li> <li class="thirdlevel"><a href="administration-get-all-skills.html">Get all skills</a></li> <li class="thirdlevel"><a href="administration-get-skill-by-id.html">Get skill by ID</a></li> <li class="thirdlevel"><a href="administration-create-skills.html">Create skills</a></li> <li class="thirdlevel"><a href="administration.update-skills.html">Update skills</a></li> <li class="thirdlevel"><a href="administration-update-skill.html">Update skill</a></li> <li class="thirdlevel"><a href="administration-delete-skills.html">Delete skills</a></li> <li class="thirdlevel"><a href="administration-delete-skill.html">Delete skill</a></li> <li class="thirdlevel"><a href="administration-skills-query-delta.html">Skills Query Delta</a></li> <li class="thirdlevel"><a href="administration-skills-appendix.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Agent Groups API</a> <ul> <li class="thirdlevel"><a href="administration-agent-groups-overview.html">Overview</a></li> <li class="thirdlevel"><a href="administration-agent-groups-methods.html">Methods</a></li> <li class="thirdlevel"><a href="administration-get-all-agent-groups.html">Get all agent groups</a></li> <li class="thirdlevel"><a href="administration-get-agent-groups-by-id.html">Get agent group by ID</a></li> <li class="thirdlevel"><a href="administration-create-agent-groups.html">Create agent groups</a></li> <li class="thirdlevel"><a href="administration-update-agent-groups.html">Update agent groups</a></li> <li class="thirdlevel"><a href="administration-update-agent-group.html">Update agent group</a></li> <li class="thirdlevel"><a href="administration-delete-agent-groups.html">Delete agent groups</a></li> <li class="thirdlevel"><a href="administration-delete-agent-group.html">Delete agent group</a></li> <li class="thirdlevel"><a href="administration-get-subgroups-and-members.html">Get subgroups and members of an agent group</a></li> <li class="thirdlevel"><a href="administration-agent-groups-query-delta.html">Agent Groups Query Delta</a></li> </ul> </li> </ul> <li> <a href="#">Consumer Experience</a> <ul> <li class="subfolders"> <a href="#">JavaScript Chat SDK</a> <ul> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getting-started.html">Getting Started</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-chat-states.html">Chat States</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-surveys.html">Surveys</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-creating-an-instance.html">Creating an Instance</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-methods.html">Methods</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getestimatedwaittime.html">getEstimatedWaitTime</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getprechatsurvey.html">getPreChatSurvey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getengagement.html">getEngagement</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-requestchat.html">requestChat</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-addline.html">addLine</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-setvisitortyping.html">setVisitorTyping</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-setvisitorname.html">setVisitorName</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-endchat.html">endChat</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-requesttranscript.html">requestTranscript</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getexitsurvey.html">getExitSurvey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-submitexitsurvey.html">submitExitSurvey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getofflinesurvey.html">getOfflineSurvey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-submitofflinesurvey.html">submitOfflineSurvey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getstate.html">getState</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getagentloginname.html">getAgentLoginName</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getvisitorname.html">getVisitorName</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getagentid.html">getAgentId</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getrtsessionid.html">getRtSessionId</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getsessionkey.html">getSessionKey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-getagenttyping.html">getAgentTyping</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-events.html">Events</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onload.html">onLoad</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-oninit.html">onInit</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onestimatedwaittime.html">onEstimatedWaitTime</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onengagement.html">onEngagement</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onprechatsurvey.html">onPreChatSurvey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onstart.html">onStart</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onstop.html">onStop</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onrequestchat.html">onRequestChat</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-ontranscript.html">onTranscript</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-online.html">onLine</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onstate.html">onState</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-oninfo.html">onInfo</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onagenttyping.html">onAgentTyping</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onexitsurvey.html">onExitSurvey</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-onaccounttoaccounttransfer.html">onAccountToAccountTransfer</a></li> <li class="thirdlevel"><a href="rt-interactions-example.html">Engagement Attributes Body Example</a></li> <li class="thirdlevel"><a href="consumer-experience-javascript-chat-demo.html">Demo App</a></li> </ul> </li> <li class="subfolders"> <a href="#">Server Chat API</a> <ul> <li class="thirdlevel"><a href="consumer-experience-server-chat-getting-started.html">Getting Started</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-methods.html">Methods</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-availability.html">Retrieve Availability</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-available-slots.html">Retrieve Available Slots</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-estimated-wait-time.html">Retrieve Estimated Wait Time</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-offline-survey.html">Retrieve an Offline Survey</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-start-chat.html">Start a Chat</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-chat-resources.html">Retrieve Chat Resources, Events and Information</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-chat-events.html">Retrieve Chat Events</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-add-lines.html">Add Lines / End Chat</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-chat-information.html">Retrieve Chat Information</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-visitor-name.html">Retrieve the Visitor's Name</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-set-visitor-name.html">Set the Visitor's Name</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-agent-typing-status.html">Retrieve the Agent's Typing Status</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-visitor-typing-status.html">Retrieve the Visitor's Typing Status</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-set-visitor-typing-status.html">Set the Visitor's Typing Status</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-retrieve-exit-survey-structure.html">Retrieve Exit Survey Structure</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-submit-survey-data.html">Submit Survey Data</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-send-transcript.html">Send a Transcript</a></li> <li class="thirdlevel"><a href="consumer-experience-server-chat-sample.html">Sample Postman Collection</a></li> </ul> </li> <li class="subfolders"> <a href="#">Push Service API</a> <ul> <li class="thirdlevel"><a href="push-service-overview.html">Overview</a></li> <li class="thirdlevel"><a href="push-service-tls-html">TLS Authentication</a></li> <li class="thirdlevel"><a href="push-service-codes-html">HTTP Response Codes</a></li> <li class="thirdlevel"><a href="push-service-configuration-html">Configuration of Push Proxy</a></li> </ul> </li> <li class="subfolders"> <a href="#">In-App Messaging SDK iOS (2.0)</a> <ul> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-quick-start.html">Quick Start</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-advanced-configurations.html">Advanced Configurations</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-methods.html">Methods</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-initialize.html">initialize</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-showconversation.html">showConversation</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-removeconversation.html">removeConversation</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-reconnect.html">reconnect</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-togglechatactions.html">toggleChatActions</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-checkactiveconversation.html">checkActiveConversation</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-markasurgent.html">markAsUrgent</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-isurgent.html">isUrgent</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-dismissurgent.html">dismissUrgent</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-resolveconversation.html">resolveConversation</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-clearhistory.html">clearHistory</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-logout.html">logout</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-destruct.html">destruct</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-handlepush.html">handlePush</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-registerpushnotifications.html">registerPushNotifications</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-setuserprofile.html">setUserProfile</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-getassignedagent.html">getAssignedAgent</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-subscribelogevents.html">subscribeLogEvents</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-getsdkversion.html">getSDKVersion</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-printalllocalizedkeys.html">printAllLocalizedKeys</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-printsupportedlanguages.html">printSupportedLanguages</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-getallsupportedlanguages.html">getAllSupportedLanguages</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-interfacedefinitions.html">Interface and Class Definitions</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-callbacks-index.html">Callbacks index</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-configuring-the-sdk.html">Configuring the SDK</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-attributes.html">Attributes</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-deprecated-attributes.html">Deprecated Attributes</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-stringlocalization.html">String localization in SDK</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-localizationkeys.html">Localization Keys</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-timestamps.html">Timestamps Formatting</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-createcertificate.html">OS Certificate Creation</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-advanced-csat.html">CSAT UI Content</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-photosharing.html">Photo Sharing (Beta)</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-pushnotifications.html">Configuring Push Notifications</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-opensource.html">Open Source List</a></li> <li class="thirdlevel"><a href="consumer-experience-ios-sdk-security.html">Security</a></li> </ul> </li> <li class="subfolders"> <a href="#">In-App Messaging SDK Android (2.0)</a> <ul> <li class="thirdlevel"><a href="android-overview.html">Overview</a></li> <li class="thirdlevel"><a href="android-prerequisites.html">Prerequisites</a></li> <li class="thirdlevel"><a href="android-download-and-unzip.html">Step 1: Download and Unzip the SDK</a></li> <li class="thirdlevel"><a href="android-configure-project-settings.html">Step 2: Configure project settings to connect LiveEngage SDK</a></li> <li class="thirdlevel"><a href="android-code-integration.html">Step 3: Code integration for basic deployment</a></li> <li class="thirdlevel"><a href="android-initialization.html">SDK Initialization and Lifecycle</a></li> <li class="thirdlevel"><a href="android-authentication.html">Authentication</a></li> <li class="thirdlevel"><a href="android-conversations-lifecycle.html">Conversations Lifecycle</a></li> <li class="thirdlevel"><a href="android-callbacks-interface.html">LivePerson Callbacks Interface</a></li> <li class="thirdlevel"><a href="android-notifications.html">Notifications</a></li> <li class="thirdlevel"><a href="android-user-data.html">User Data</a></li> <li class="thirdlevel"><a href="android-logs.html">Logs and Info</a></li> <li class="thirdlevel"><a href="android-methods.html">Methods</a></li> <li class="thirdlevel"><a href="android-initializedeprecated.html">initialize (Deprecated)</a></li> <li class="thirdlevel"><a href="android-initializeproperties.html">initialize (with SDK properties object)</a></li> <li class="thirdlevel"><a href="android-showconversation.html">showConversation</a></li> <li class="thirdlevel"><a href="android-showconversationauth.html">showConversation (with authentication support)</a></li> <li class="thirdlevel"><a href="android-hideconversation.html">hideConversation</a></li> <li class="thirdlevel"><a href="android-getconversationfrag.html">getConversationFragment</a></li> <li class="thirdlevel"><a href="android-getconversationfragauth.html">getConversationFragment with authentication support</a></li> <li class="thirdlevel"><a href="android-reconnect.html">reconnect</a></li> <li class="thirdlevel"><a href="android-setuserprofile.html">setUserProfile</a></li> <li class="thirdlevel"><a href="android-setuserprofiledeprecated.html">setUserProfile (Deprecated)</a></li> <li class="thirdlevel"><a href="android-registerlppusher.html">registerLPPusher</a></li> <li class="thirdlevel"><a href="android-unregisterlppusher.html">unregisterLPPusher</a></li> <li class="thirdlevel"><a href="android-handlepush.html">handlePush</a></li> <li class="thirdlevel"><a href="android-getsdkversion.html">getSDKVersion</a></li> <li class="thirdlevel"><a href="android-setcallback.html">setCallback</a></li> <li class="thirdlevel"><a href="android-removecallback.html">removeCallBack</a></li> <li class="thirdlevel"><a href="android-checkactiveconversation.html">checkActiveConversation</a></li> <li class="thirdlevel"><a href="android-checkagentid.html">checkAgentID</a></li> <li class="thirdlevel"><a href="android-markurgent.html">markConversationAsUrgent</a></li> <li class="thirdlevel"><a href="android-marknormal.html">markConversationAsNormal</a></li> <li class="thirdlevel"><a href="android-checkurgent.html">checkConversationIsMarkedAsUrgent</a></li> <li class="thirdlevel"><a href="android-resolveconversation.html">resolveConversation</a></li> <li class="thirdlevel"><a href="android-shutdown.html">shutDown</a></li> <li class="thirdlevel"><a href="android-shutdowndeprecated.html">shutDown (Deprecated)</a></li> <li class="thirdlevel"><a href="android-clearhistory.html">clearHistory</a></li> <li class="thirdlevel"><a href="android-logout.html">logOut</a></li> <li class="thirdlevel"><a href="android-callbacks-index.html">Callbacks Index</a></li> <li class="thirdlevel"><a href="android-configuring-sdk.html">Configuring the SDK</a></li> <li class="thirdlevel"><a href="android-attributes.html">Attributes</a></li> <li class="thirdlevel"><a href="android-configuring-edittext.html">Configuring the message’s EditText</a></li> <li class="thirdlevel"><a href="android-proguard.html">Proguard Configuration</a></li> <li class="thirdlevel"><a href="android-modifying-string.html">Modifying Strings</a></li> <li class="thirdlevel"><a href="android-modifying-resources.html">Modifying Resources</a></li> <li class="thirdlevel"><a href="android-plural-string.html">Plural String Resource Example</a></li> <li class="thirdlevel"><a href="android-timestamps.html">Timestamps Formatting</a></li> <li class="thirdlevel"><a href="android-off-hours.html">Date and Time</a></li> <li class="thirdlevel"><a href="android-bubble.html">Bubble Timestamp</a></li> <li class="thirdlevel"><a href="android-separator.html">Separator Timestamp</a></li> <li class="thirdlevel"><a href="android-resolve.html">Resolve Message</a></li> <li class="thirdlevel"><a href="android-csat.html">CSAT Behavior</a></li> <li class="thirdlevel"><a href="android-photo-sharing.html">Photo Sharing - Beta</a></li> <li class="thirdlevel"><a href="android-push-notifications.html">Enable Push Notifications</a></li> <li class="thirdlevel"><a href="android-appendix.html">Appendix</a></li> </ul> </li> </ul> <li> <a href="#">Real-time Interactions</a> <ul> <li class="subfolders"> <a href="#">Visit Information API</a> <ul> <li class="thirdlevel"><a href="rt-interactions-visit-information-overview.html">Overview</a></li> <li class="thirdlevel"><a href="rt-interactions-visit-information-visit-information.html">Visit Information</a></li> </ul> </li> <li class="subfolders"> <a href="#">App Engagement API</a> <ul> <li class="thirdlevel"><a href="rt-interactions-app-engagement-overview.html">Overview</a></li> <li class="thirdlevel"><a href="rt-interactions-app-engagement-methods.html">Methods</a></li> <li class="thirdlevel"><a href="rt-interactions-create-session.html">Create Session</a></li> <li class="thirdlevel"><a href="rt-interactions-update-session.html">Update Session</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement Attributes</a> <ul> <li class="thirdlevel"><a href="rt-interactions-engagement-attributes-overview.html">Overview</a></li> <li class="thirdlevel"><a href="rt-interactions-engagement-attributes-engagement-attributes.html">Engagement Attributes</a></li> </ul> </li> <li class="subfolders"> <a href="#">IVR Engagement API</a> <ul> <li class="thirdlevel"><a href="rt-interactions-ivr-engagement-overview.html">Overview</a></li> <li class="thirdlevel"><a href="rt-interactions-ivr-engagement-methods.html">Methods</a></li> <li class="thirdlevel"><a href="rt-interactions-ivr-engagement-external engagement.html">External Engagement</a></li> </ul> </li> <li class="subfolders"> <a href="#">Validate Engagement</a> <ul> <li class="thirdlevel"><a href="rt-interactions-validate-engagement-overview.html">Overview</a></li> <li class="thirdlevel"><a href="rt-interactions-validate-engagement-validate-engagement.html">Validate Engagement API</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement Trigger API</a> <ul> <li class="thirdlevel"><a href="trigger-overview.html">Overview</a></li> <li class="thirdlevel"><a href="trigger-methods.html">Methods</a></li> <li class="thirdlevel"><a href="trigger-click.html">Click</a></li> <li class="thirdlevel"><a href="trigger-getinfo.html">getEngagementInfo</a></li> <li class="thirdlevel"><a href="trigger-getstate.html">getEngagementState</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement Window Widget SDK</a> <ul> <li class="thirdlevel"><a href="rt-interactions-window-sdk-overview.html">Overview</a></li> <li class="thirdlevel"><a href="rt-interactions-window-sdk-getting-started.html">Getting Started</a></li> <li class="thirdlevel"><a href="rt-interactions-window-sdk-limitations.html">Limitations</a></li> <li class="thirdlevel"><a href="rt-interactions-window-sdk-configuration.html">Configuration</a></li> <li class="thirdlevel"><a href="rt-interactions-window-sdk-how-to-use.html">How to use the SDK</a></li> <li class="thirdlevel"><a href="rt-interactions-window-sdk-code-examples.html">Code Examples</a></li> <li class="active thirdlevel"><a href="rt-interactions-window-sdk-event-structure.html">Event Structure</a></li> </ul> </li> </ul> <li> <a href="#">Agent</a> <ul> <li class="subfolders"> <a href="#">Agent Workspace Widget SDK</a> <ul> <li class="thirdlevel"><a href="agent-workspace-sdk-overview.html">Overview</a></li> <li class="thirdlevel"><a href="agent-workspace-sdk-getting-started.html">Getting Started</a></li> <li class="thirdlevel"><a href="agent-workspace-sdk-limitations.html">Limitations</a></li> <li class="thirdlevel"><a href="agent-workspace-sdk-how-to-use.html">How to use the SDK</a></li> <li class="thirdlevel"><a href="agent-workspace-sdk-methods.html">Methods</a></li> <li class="thirdlevel"><a href="agent-workspace-sdk-public-model.html">Public Model Structure</a></li> <li class="thirdlevel"><a href="agent-workspace-sdk-public-properties.html">Public Properties</a></li> <li class="thirdlevel"><a href="agent-workspace-sdk-code-examples.html">Code Examples</a></li> </ul> </li> <li class="subfolders"> <a href="#">LivePerson Domain API</a> <ul> <li class="thirdlevel"><a href="agent-domain-domain-api.html">Domain API</a></li> </ul> </li> <li class="subfolders"> <a href="#">Login Service API</a> <ul> <li class="thirdlevel"><a href="login-getting-started.html">Getting Started</a></li> <li class="thirdlevel"><a href="agent-login-methods.html">Methods</a></li> <li class="thirdlevel"><a href="agent-login.html">Login</a></li> <li class="thirdlevel"><a href="agent-refresh.html">Refresh</a></li> <li class="thirdlevel"><a href="agent-refresh.html">Logout</a></li> </ul> </li> <li class="subfolders"> <a href="#">Chat Agent API</a> <ul> <li class="thirdlevel"><a href="chat-agent-getting-started.html">Getting Started</a></li> <li class="thirdlevel"><a href="agent-chat-agent-methods.html">Methods</a></li> <li class="thirdlevel"><a href="agent-start-agent-session.html">Start Agent Session</a></li> <li class="thirdlevel"><a href="agent-retrieve-current-availability.html">Retrieve Current Availability</a></li> <li class="thirdlevel"><a href="agent-set-agent-availability.html">Set Agent Availability</a></li> <li class="thirdlevel"><a href="agent-retrieve-available-agents.html">Retrieve Available Agents</a></li> <li class="thirdlevel"><a href="agent-retrieve-available-slots.html">Retrieve Available Slots</a></li> <li class="thirdlevel"><a href="agent-retrieve-agent-information.html">Retrieve Agent Information</a></li> <li class="thirdlevel"><a href="agent-determine-incoming.html">Determine Incoming Chat Requests</a></li> <li class="thirdlevel"><a href="agent-accept-chat.html">Accept a Chat</a></li> <li class="thirdlevel"><a href="agent-retrieve-chat-sessions.html">Retrieve Chat Sessions</a></li> <li class="thirdlevel"><a href="agent-retrieve-chat-resources.html">Retrieve Chat Resources, Events and Information</a></li> <li class="thirdlevel"><a href="agent-retrieve-data.html">Retrieve Data for Multiple Chats</a></li> <li class="thirdlevel"><a href="agent-retrieve-chat-events.html">Retrieve Chat Events</a></li> <li class="thirdlevel"><a href="agent-add-lines.html">Add Lines</a></li> <li class="thirdlevel"><a href="agent-end-chat.html">End Chat</a></li> <li class="thirdlevel"><a href="agent-retrieve-chat-info.html">Retrieve Chat Information</a></li> <li class="thirdlevel"><a href="">Retrieve Visitor’s Name</a></li> <li class="thirdlevel"><a href="agent-retrieve-agent-typing.html">Retrieve Agent's Typing Status</a></li> <li class="thirdlevel"><a href="agent-set-agent-typing.html">Set Agent’s Typing Status</a></li> <li class="thirdlevel"><a href="agent-retrieve-visitor-typing.html">Retrieve Visitor's Typing Status</a></li> <li class="thirdlevel"><a href="agent-chat-agent-retrieve-skills.html">Retrieve Available Skills</a></li> <li class="thirdlevel"><a href="agent-transfer-chat.html">Transfer a Chat</a></li> <li class="thirdlevel"><a href="agent-retrieve-survey-structure.html">Retrieve Agent Survey Structure</a></li> </ul> </li> <li class="subfolders"> <a href="#">Messaging Agent SDK</a> <ul> <li class="thirdlevel"><a href="messaging-agent-sdk-overview.html">Overview</a></li> </ul> </li> </ul> <li> <a href="#">Data</a> <ul> <li class="subfolders"> <a href="#">Data Access API (Beta)</a> <ul> <li class="thirdlevel"><a href="data-data-access-overview.html">Overview</a></li> <li class="thirdlevel"><a href="data-data-access-architecture.html">Architecture</a></li> <li class="thirdlevel"><a href="data-data-access-methods.html">Methods</a></li> <li class="thirdlevel"><a href="data-data-access-base-resource.html">Base Resource</a></li> <li class="thirdlevel"><a href="data-data-access-agent-activity.html">Agent Activity</a></li> <li class="thirdlevel"><a href="data-data-access-web-session.html">Web Session</a></li> <li class="thirdlevel"><a href="data-data-access-engagement.html">Engagement</a></li> <li class="thirdlevel"><a href="data-data-access-survey.html">Survey</a></li> <li class="thirdlevel"><a href="data-data-access-schema.html">Schema</a></li> <li class="thirdlevel"><a href="data-data-access-appendix.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Messaging Operations API</a> <ul> <li class="thirdlevel"><a href="data-messaging-operations-overview.html">Overview</a></li> <li class="thirdlevel"><a href="data-messaging-operations-methods.html">Methods</a></li> <li class="thirdlevel"><a href="data-messaging-operations-messaging-conversation.html">Messaging Conversation</a></li> <li class="thirdlevel"><a href="data-messaging-operations-messaging-csat-distribution.html">Messaging CSAT Distribution</a></li> <li class="thirdlevel"><a href="data-messaging-operations-appendix.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Messaging Interactions API (Beta)</a> <ul> <li class="thirdlevel"><a href="data-messaging-interactions-overview.html">Overview</a></li> <li class="thirdlevel"><a href="data-messaging-interactions-methods.html">Methods</a></li> <li class="thirdlevel"><a href="data-messaging-interactions-conversations.html">Conversations</a></li> <li class="thirdlevel"><a href="data-messaging-interactions-get-conversation-by-conversation-id.html">Get conversation by conversation ID</a></li> <li class="thirdlevel"><a href="data-messaging-interactions-get-conversations-by-consumer-id.html">Get Conversations by Consumer ID</a></li> <li class="thirdlevel"><a href="data-messaging-interactions-sample-code.html">Sample Code</a></li> <li class="thirdlevel"><a href="data-messaging-interactions-appendix.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Engagement History API</a> <ul> <li class="thirdlevel"><a href="data-engagement-history-overview.html">Overview</a></li> <li class="thirdlevel"><a href="data-engagement-history-methods.html">Methods</a></li> <li class="thirdlevel"><a href="data-engagement-history-retrieve-engagement-list-by-criteria.html">Retrieve Engagement List by Criteria</a></li> <li class="thirdlevel"><a href="data-engagement-history-sample-code.html">Sample Code</a></li> <li class="thirdlevel"><a href="data-engagement-history-appendix.html">Appendix</a></li> </ul> </li> <li class="subfolders"> <a href="#">Operational Real-time API</a> <ul> <li class="thirdlevel"><a href="data-operational-realtime-overview.html">Overview</a></li> <li class="thirdlevel"><a href="data-operational-realtime-methods.html">Methods</a></li> <li class="thirdlevel"><a href="data-operational-realtime-queue-health.html">Queue Health</a></li> <li class="thirdlevel"><a href="data-operational-realtime-engagement-activity.html">Engagement Activity</a></li> <li class="thirdlevel"><a href="data-operational-realtime-agent-activity.html">Agent Activity</a></li> <li class="thirdlevel"><a href="data-operational-realtime-current-queue-state.html">Current Queue State</a></li> <li class="thirdlevel"><a href="data-operational-realtime-sla-histogram.html">SLA Histogram</a></li> <li class="thirdlevel"><a href="data-operational-realtime-sample-code.html">Sample Code</a></li> </ul> </li> </ul> <li> <a href="#">LiveEngage Tag</a> <ul> <li class="subfolders"> <a href="#">LE Tag Events</a> <ul> <li class="thirdlevel"><a href="lp-tag-tag-events-overview.html">Overview</a></li> <li class="thirdlevel"><a href="lp-tag-tag-events-how.html">How to use these Events</a></li> <li class="thirdlevel"><a href="lp-tag-tag-events-events.html">Events</a></li> <li class="thirdlevel"><a href="lp-tag-visitor-flow.html">Visitor Flow Events</a></li> <li class="thirdlevel"><a href="lp-tag-engagement.html">Engagement Events</a></li> <li class="thirdlevel"><a href="lp-tag-engagement-window.html">Engagement Window Events</a></li> </ul> </li> </ul> <li> <a href="#">Messaging Window API</a> <ul> <li class="subfolders"> <a href="#">Introduction</a> <ul> <li class="thirdlevel"><a href="consumer-interation-index.html">Home</a></li> <li class="thirdlevel"><a href="consumer-int-protocol-overview.html">Protocol Overview</a></li> <li class="thirdlevel"><a href="consumer-int-getting-started.html">Getting Started</a></li> </ul> </li> <li class="subfolders"> <a href="#">Tutorials</a> <ul> <li class="thirdlevel"><a href="consumer-int-get-msg.html">Get Messages</a></li> <li class="thirdlevel"><a href="consumer-int-conversation-md.html">Conversation Metadata</a></li> <li class="thirdlevel"><a href="consumer-int-readaccept-events.html">Read/Accept events</a></li> <li class="thirdlevel"><a href="consumer-int-authentication.html">Authentication</a></li> <li class="thirdlevel"><a href="consumer-int-agent-profile.html">Agent Profile</a></li> <li class="thirdlevel"><a href="consumer-int-post-survey.html">Post Conversation Survey</a></li> <li class="thirdlevel"><a href="consumer-int-client-props.html">Client Properties</a></li> <li class="thirdlevel"><a href="consumer-int-no-headers.html">Avoid Webqasocket Headers</a></li> </ul> </li> <li class="subfolders"> <a href="#">Samples</a> <ul> <li class="thirdlevel"><a href="consumer-int-js-sample.html">JavaScript Messenger</a></li> </ul> </li> <li class="subfolders"> <a href="#">API Reference</a> <ul> <li class="thirdlevel"><a href="consumer-int-api-reference.html">Overview</a></li> <li class="thirdlevel"><a href="consumer-int-msg-reqs.html">Request Builder</a></li> <li class="thirdlevel"><a href="consumer-int-msg-resps.html">Response Builder</a></li> <li class="thirdlevel"><a href="consumer-int-msg-notifications.html">Notification Builder</a></li> <li class="thirdlevel"><a href="consumer-int-msg-req-conv.html">New Conversation</a></li> <li class="thirdlevel"><a href="consumer-int-msg-close-conv.html">Close Conversation</a></li> <li class="thirdlevel"><a href="consumer-int-msg-conv-ttr.html">Urgent Conversation</a></li> <li class="thirdlevel"><a href="consumer-int-msg-csat-conv.html">Update CSAT</a></li> <li class="thirdlevel"><a href="consumer-int-msg-sub-conv.html">Subscribe Conversations Metadata</a></li> <li class="thirdlevel"><a href="consumer-int-msg-unsub-conv.html">Unsubscribe Conversations Metadata</a></li> <li class="thirdlevel"><a href="consumer-int-msg-text-cont.html">Publish Content</a></li> <li class="thirdlevel"><a href="consumer-int-msg-sub-events.html">Subscribe Conversation Content</a></li> <li class="thirdlevel"><a href="consumer-int-msg-init-con.html">Browser Init Connection</a></li> </ul> </li> </ul> <!-- if you aren't using the accordion, uncomment this block: <p class="external"> <a href="#" id="collapseAll">Collapse All</a> | <a href="#" id="expandAll">Expand All</a> </p> --> </li> </ul> </div> <!-- this highlights the active parent class in the navgoco sidebar. this is critical so that the parent expands when you're viewing a page. This must appear below the sidebar code above. Otherwise, if placed inside customscripts.js, the script runs before the sidebar code runs and the class never gets inserted.--> <script>$("li.active").parents('li').toggleClass("active");</script> <!-- Content Column --> <div class="col-md-9"> <div class="post-header"> <h1 class="post-title-main">Event Structure</h1> </div> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-96175782-1', 'auto'); ga('send', 'pageview'); </script> <div class="post-content"> <p>Each event contains three parameters: id, type and data. They appear as follows:</p> <div class="highlighter-rouge"><pre class="highlight"><code><span class="p">{</span><span class="w"> </span><span class="err">id:</span><span class="w"> </span><span class="err">&lt;string&gt;,</span><span class="w"> </span><span class="err">type:</span><span class="w"> </span><span class="err">lpTag.LPWidgetSDK.API.events.[key],</span><span class="w"> </span><span class="err">data:</span><span class="w"> </span><span class="err">&lt;object&gt;</span><span class="w"> </span><span class="p">}</span><span class="w"> </span></code></pre> </div> <h2 id="event-types">Event types</h2> <table> <thead> <tr> <th style="text-align: left">type: lpTag.LPWidgetSDK.API.events.[key]</th> <th style="text-align: left">Type</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">“conversationInfo”</td> <td style="text-align: left">object</td> </tr> <tr> <td style="text-align: left">“messages”</td> <td style="text-align: left">object</td> </tr> <tr> <td style="text-align: left">“participants”</td> <td style="text-align: left">array</td> </tr> <tr> <td style="text-align: left">“uiWindow”</td> <td style="text-align: left">object</td> </tr> <tr> <td style="text-align: left">“uiWidget”</td> <td style="text-align: left">object</td> </tr> </tbody> </table> <h2 id="data-examples">Data examples</h2> <p><strong>“conversationInfo”</strong></p> <div class="highlighter-rouge"><pre class="highlight"><code><span class="p">{</span><span class="w"> </span><span class="err">conversationId:</span><span class="w"> </span><span class="err">&lt;string&gt;,</span><span class="w"> </span><span class="err">sessionId:</span><span class="w"> </span><span class="err">&lt;string&gt;,</span><span class="w"> </span><span class="err">*dialogId:</span><span class="w"> </span><span class="err">&lt;string&gt;,</span><span class="w"> </span><span class="err">startTime:</span><span class="w"> </span><span class="err">&lt;string&gt;,</span><span class="w"> </span><span class="err">state:</span><span class="w"> </span><span class="err">lpTag.LPWidgetSDK.API.states,</span><span class="w"> </span><span class="err">*dialogType:</span><span class="w"> </span><span class="err">&lt;string&gt;,</span><span class="w"> </span><span class="err">channelType:</span><span class="w"> </span><span class="err">&lt;string&gt;</span><span class="w"> </span><span class="err">(</span><span class="nt">"chat”/”messaging"</span><span class="err">)</span><span class="w"> </span><span class="err">}</span><span class="w"> </span></code></pre> </div> <p><em>Note: This data will be relevant for messaging in future versions.</em></p> <p><strong>“messages”</strong></p> <div class="highlighter-rouge"><pre class="highlight"><code><span class="p">{</span><span class="w"> </span><span class="err">id:</span><span class="w"> </span><span class="err">&lt;string&gt;,</span><span class="w"> </span><span class="err">ts:</span><span class="w"> </span><span class="err">1231231312,</span><span class="w"> </span><span class="err">type:</span><span class="w"> </span><span class="err">&lt;string&gt;</span><span class="w"> </span><span class="err">(</span><span class="nt">"text/message"</span><span class="w"> </span><span class="err">for</span><span class="w"> </span><span class="err">now),</span><span class="w"> </span><span class="err">content</span><span class="p">:</span><span class="w"> </span><span class="err">&lt;string&gt;</span><span class="p">,</span><span class="w"> </span><span class="err">originator</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="err">type:</span><span class="w"> </span><span class="err">&lt;string&gt;</span><span class="w"> </span><span class="err">(“visitor”/”agent”/”system”),</span><span class="w"> </span><span class="err">name:</span><span class="w"> </span><span class="err">&lt;string&gt;</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="p">}</span><span class="w"> </span></code></pre> </div> <p><strong>“participants”</strong></p> <div class="highlighter-rouge"><pre class="highlight"><code>[ { "id": &lt;string&gt;, "name": &lt;string&gt;, "type": "visitor" }, { "id": &lt;string&gt;, "name": &lt;string&gt;, "type": "agent", "imgPath": &lt;string&gt;, "description": &lt;string&gt; } ] </code></pre> </div> <p><strong>“uiWindow”</strong></p> <div class="highlighter-rouge"><pre class="highlight"><code><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nt">"isMaximized"</span><span class="p">:</span><span class="w"> </span><span class="err">&lt;boolean&gt;</span><span class="w"> </span><span class="p">}</span><span class="w"> </span></code></pre> </div> <p><strong>“uiWidget”</strong></p> <div class="highlighter-rouge"><pre class="highlight"><code><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nt">"isShown"</span><span class="p">:</span><span class="w"> </span><span class="err">&lt;boolean&gt;</span><span class="w"> </span><span class="p">}</span><span class="w"> </span></code></pre> </div> <div class="tags"> </div> </div> <hr class="shaded"/> <footer> <div class="row"> <div class="col-lg-12 footer"> &copy;2017 LivePerson. All rights reserved.<br />This documentation is subject to change without notice.<br /> Site last generated: Mar 27, 2017 <br /> <p><img src="img/company_logo.png" alt="Company logo"/></p> </div> </div> </footer> </div> <!-- /.row --> </div> <!-- /.container --> </div> </body> </html>
LivePersonInc/dev-hub
content_ga3/rt-interactions-window-sdk-event-structure.html
HTML
mit
171,734
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE 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. # # For more information, please refer to <http://unlicense.org/> import os import ycm_core # These are the compilation flags that will be used in case there's no # compilation database set (by default, one is not set). # CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. flags = [ '-Wall', '-Wextra', '-Werror', '-std=gnu11', '-x', 'c', '-isystem', '/usr/include', ] # Set this to the absolute path to the folder (NOT the file!) containing the # compile_commands.json file to use that instead of 'flags'. See here for # more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html # # You can get CMake to generate this file for you by adding: # set( CMAKE_EXPORT_COMPILE_COMMANDS 1 ) # to your CMakeLists.txt file. # # Most projects will NOT need to set this to anything; you can just change the # 'flags' list of compilation flags. Notice that YCM itself uses that approach. compilation_database_folder = '' if os.path.exists( compilation_database_folder ): database = ycm_core.CompilationDatabase( compilation_database_folder ) else: database = None SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ] def DirectoryOfThisScript(): return os.path.dirname( os.path.abspath( __file__ ) ) def MakeRelativePathsInFlagsAbsolute( flags, working_directory ): if not working_directory: return list( flags ) new_flags = [] make_next_absolute = False path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ] for flag in flags: new_flag = flag if make_next_absolute: make_next_absolute = False if not flag.startswith( '/' ): new_flag = os.path.join( working_directory, flag ) for path_flag in path_flags: if flag == path_flag: make_next_absolute = True break if flag.startswith( path_flag ): path = flag[ len( path_flag ): ] new_flag = path_flag + os.path.join( working_directory, path ) break if new_flag: new_flags.append( new_flag ) return new_flags def IsHeaderFile( filename ): extension = os.path.splitext( filename )[ 1 ] return extension in [ '.h', '.hxx', '.hpp', '.hh' ] def GetCompilationInfoForFile( filename ): # The compilation_commands.json file generated by CMake does not have entries # for header files. So we do our best by asking the db for flags for a # corresponding source file, if any. If one exists, the flags for that file # should be good enough. if IsHeaderFile( filename ): basename = os.path.splitext( filename )[ 0 ] for extension in SOURCE_EXTENSIONS: replacement_file = basename + extension if os.path.exists( replacement_file ): compilation_info = database.GetCompilationInfoForFile( replacement_file ) if compilation_info.compiler_flags_: return compilation_info return None return database.GetCompilationInfoForFile( filename ) def FlagsForFile( filename, **kwargs ): if database: # Bear in mind that compilation_info.compiler_flags_ does NOT return a # python list, but a "list-like" StringVec object compilation_info = GetCompilationInfoForFile( filename ) if not compilation_info: return None final_flags = MakeRelativePathsInFlagsAbsolute( compilation_info.compiler_flags_, compilation_info.compiler_working_dir_ ) # NOTE: This is just for YouCompleteMe; it's highly likely that your project # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT. # try: # final_flags.remove( '-stdlib=libc++' ) # except ValueError: # pass else: relative_to = DirectoryOfThisScript() final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to ) return { 'flags': final_flags, 'do_cache': True }
darthdeus/dotfiles
c_ycm_conf.py
Python
mit
5,178
'use strict'; module.exports = { db: 'mongodb://lolo:tazkypass@dogen.mongohq.com:10048/todo-database', app: { title: 'TuDu - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
pixelshade/TuDu
config/env/development.js
JavaScript
mit
1,288
#KWAD Tool [![Author](https://img.shields.io/badge/Author-Zhi--Wei_Cai-red.svg?style=flat-square)](http://vox.vg/) ![Version](https://img.shields.io/badge/Version-v0.1-green.svg?style=flat-square) [![License](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)][License] > Discussion thread on the [Klei forum][]. ###KWAD Tool This is a simple tool for listing/extracting files packed with Klei's `.kwad` format. ###Usage You have to have **Python 2.7** installed in order to use this tool. ```bash python kwad-tool.py PATH_TO_KWAD_FILE [EXTRACTING_PATH] ``` ###License See [`LICENSE`][License]. [License]: https://github.com/x43x61x69/KWAD-Tool/blob/master/LICENSE [Klei forum]: http://forums.kleientertainment.com/topic/54184-kwad/
x43x61x69/KWAD-Tool
README.md
Markdown
mit
764
# Install hook code here puts "Copying files..." dir = "/javascripts/swf" makedirs(RAILS_ROOT+"/public"+dir) ["swfupload.js", "swfupload.swf", "swfupload.cookies.js","fileprogress.js","handlers.js"].each do |js_file| dest_file = File.join(RAILS_ROOT, "public", dir, js_file) src_file = File.join(File.dirname(__FILE__) , dir, js_file) FileUtils.cp_r(src_file, dest_file) end puts "Files copied - Installation complete!"
kpitn/swfupload
install.rb
Ruby
mit
423
# James Bigler, NVIDIA Corp (nvidia.com - jbigler) # # Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved. # # This code is licensed under the MIT License. See the FindCUDA.cmake script # for the text of the license. # The MIT License # # License for the specific language governing rights and limitations under # Permission is hereby granted, free of charge, to any person obtaining 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, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE 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. ########################################################################## # This file runs the nvcc commands to produce the desired output file along with # the dependency file needed by CMake to compute dependencies. In addition the # file checks the output of each command and if the command fails it deletes the # output files. # Input variables # # verbose:BOOL=<> OFF: Be as quiet as possible (default) # ON : Describe each step # # build_configuration:STRING=<> Typically one of Debug, MinSizeRel, Release, or # RelWithDebInfo, but it should match one of the # entries in CUDA_HOST_FLAGS. This is the build # configuration used when compiling the code. If # blank or unspecified Debug is assumed as this is # what CMake does. # # generated_file:STRING=<> File to generate. This argument must be passed in. # # generated_cubin_file:STRING=<> File to generate. This argument must be passed # in if build_cubin is true. if(NOT generated_file) message(FATAL_ERROR "You must specify generated_file on the command line") endif() # Set these up as variables to make reading the generated file easier set(CMAKE_COMMAND "/usr/bin/cmake") # path set(source_file "/home/yhtsai/caffe-cedn-dev/src/caffe/layers/contrastive_loss_layer.cu") # path set(NVCC_generated_dependency_file "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/caffe_cu_generated_contrastive_loss_layer.cu.o.NVCC-depend") # path set(cmake_dependency_file "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/caffe_cu_generated_contrastive_loss_layer.cu.o.depend") # path set(CUDA_make2cmake "/usr/share/cmake-2.8/Modules/FindCUDA/make2cmake.cmake") # path set(CUDA_parse_cubin "/usr/share/cmake-2.8/Modules/FindCUDA/parse_cubin.cmake") # path set(build_cubin OFF) # bool set(CUDA_HOST_COMPILER "/usr/bin/cc") # bool # We won't actually use these variables for now, but we need to set this, in # order to force this file to be run again if it changes. set(generated_file_path "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/.") # path set(generated_file_internal "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/./caffe_cu_generated_contrastive_loss_layer.cu.o") # path set(generated_cubin_file_internal "/home/yhtsai/caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/./caffe_cu_generated_contrastive_loss_layer.cu.o.cubin.txt") # path set(CUDA_NVCC_EXECUTABLE "/usr/local/cuda/bin/nvcc") # path set(CUDA_NVCC_FLAGS -gencode;arch=compute_20,code=sm_20;-gencode;arch=compute_20,code=sm_21;-gencode;arch=compute_30,code=sm_30;-gencode;arch=compute_35,code=sm_35 ;; ) # list # Build specific configuration flags set(CUDA_NVCC_FLAGS_DEBUG ; ) set(CUDA_NVCC_FLAGS_MINSIZEREL ; ) set(CUDA_NVCC_FLAGS_RELEASE ; ) set(CUDA_NVCC_FLAGS_RELWITHDEBINFO ; ) set(nvcc_flags -m64) # list set(CUDA_NVCC_INCLUDE_ARGS "-I/usr/local/cuda/include;-I/home/yhtsai/caffe-cedn-dev/include;-I/home/yhtsai/caffe-cedn-dev/src;-I/usr/local/cuda/include;-I/usr/include;-I/usr/include/atlas;-I/usr/local/include/opencv;-I/usr/local/include") # list (needs to be in quotes to handle spaces properly). set(format_flag "-c") # string if(build_cubin AND NOT generated_cubin_file) message(FATAL_ERROR "You must specify generated_cubin_file on the command line") endif() # This is the list of host compilation flags. It C or CXX should already have # been chosen by FindCUDA.cmake. set(CMAKE_HOST_FLAGS -fPIC ) set(CMAKE_HOST_FLAGS_DEBUG -g) set(CMAKE_HOST_FLAGS_MINSIZEREL -Os -DNDEBUG) set(CMAKE_HOST_FLAGS_RELEASE -O3 -DNDEBUG) set(CMAKE_HOST_FLAGS_RELWITHDEBINFO -O2 -g -DNDEBUG) # Take the compiler flags and package them up to be sent to the compiler via -Xcompiler set(nvcc_host_compiler_flags "") # If we weren't given a build_configuration, use Debug. if(NOT build_configuration) set(build_configuration Debug) endif() string(TOUPPER "${build_configuration}" build_configuration) #message("CUDA_NVCC_HOST_COMPILER_FLAGS = ${CUDA_NVCC_HOST_COMPILER_FLAGS}") foreach(flag ${CMAKE_HOST_FLAGS} ${CMAKE_HOST_FLAGS_${build_configuration}}) # Extra quotes are added around each flag to help nvcc parse out flags with spaces. set(nvcc_host_compiler_flags "${nvcc_host_compiler_flags},\"${flag}\"") endforeach() if (nvcc_host_compiler_flags) set(nvcc_host_compiler_flags "-Xcompiler" ${nvcc_host_compiler_flags}) endif() #message("nvcc_host_compiler_flags = \"${nvcc_host_compiler_flags}\"") # Add the build specific configuration flags list(APPEND CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS_${build_configuration}}) # Any -ccbin existing in CUDA_NVCC_FLAGS gets highest priority list( FIND CUDA_NVCC_FLAGS "-ccbin" ccbin_found0 ) list( FIND CUDA_NVCC_FLAGS "--compiler-bindir" ccbin_found1 ) if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 ) if (CUDA_HOST_COMPILER STREQUAL "$(VCInstallDir)bin" AND DEFINED CCBIN) set(CCBIN -ccbin "${CCBIN}") else() set(CCBIN -ccbin "${CUDA_HOST_COMPILER}") endif() endif() # cuda_execute_process - Executes a command with optional command echo and status message. # # status - Status message to print if verbose is true # command - COMMAND argument from the usual execute_process argument structure # ARGN - Remaining arguments are the command with arguments # # CUDA_result - return value from running the command # # Make this a macro instead of a function, so that things like RESULT_VARIABLE # and other return variables are present after executing the process. macro(cuda_execute_process status command) set(_command ${command}) if(NOT _command STREQUAL "COMMAND") message(FATAL_ERROR "Malformed call to cuda_execute_process. Missing COMMAND as second argument. (command = ${command})") endif() if(verbose) execute_process(COMMAND "${CMAKE_COMMAND}" -E echo -- ${status}) # Now we need to build up our command string. We are accounting for quotes # and spaces, anything else is left up to the user to fix if they want to # copy and paste a runnable command line. set(cuda_execute_process_string) foreach(arg ${ARGN}) # If there are quotes, excape them, so they come through. string(REPLACE "\"" "\\\"" arg ${arg}) # Args with spaces need quotes around them to get them to be parsed as a single argument. if(arg MATCHES " ") list(APPEND cuda_execute_process_string "\"${arg}\"") else() list(APPEND cuda_execute_process_string ${arg}) endif() endforeach() # Echo the command execute_process(COMMAND ${CMAKE_COMMAND} -E echo ${cuda_execute_process_string}) endif() # Run the command execute_process(COMMAND ${ARGN} RESULT_VARIABLE CUDA_result ) endmacro() # Delete the target file cuda_execute_process( "Removing ${generated_file}" COMMAND "${CMAKE_COMMAND}" -E remove "${generated_file}" ) # For CUDA 2.3 and below, -G -M doesn't work, so remove the -G flag # for dependency generation and hope for the best. set(depends_CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS}") set(CUDA_VERSION 7.0) if(CUDA_VERSION VERSION_LESS "3.0") cmake_policy(PUSH) # CMake policy 0007 NEW states that empty list elements are not # ignored. I'm just setting it to avoid the warning that's printed. cmake_policy(SET CMP0007 NEW) # Note that this will remove all occurances of -G. list(REMOVE_ITEM depends_CUDA_NVCC_FLAGS "-G") cmake_policy(POP) endif() # nvcc doesn't define __CUDACC__ for some reason when generating dependency files. This # can cause incorrect dependencies when #including files based on this macro which is # defined in the generating passes of nvcc invokation. We will go ahead and manually # define this for now until a future version fixes this bug. set(CUDACC_DEFINE -D__CUDACC__) # Generate the dependency file cuda_execute_process( "Generating dependency file: ${NVCC_generated_dependency_file}" COMMAND "${CUDA_NVCC_EXECUTABLE}" -M ${CUDACC_DEFINE} "${source_file}" -o "${NVCC_generated_dependency_file}" ${CCBIN} ${nvcc_flags} ${nvcc_host_compiler_flags} ${depends_CUDA_NVCC_FLAGS} -DNVCC ${CUDA_NVCC_INCLUDE_ARGS} ) if(CUDA_result) message(FATAL_ERROR "Error generating ${generated_file}") endif() # Generate the cmake readable dependency file to a temp file. Don't put the # quotes just around the filenames for the input_file and output_file variables. # CMake will pass the quotes through and not be able to find the file. cuda_execute_process( "Generating temporary cmake readable file: ${cmake_dependency_file}.tmp" COMMAND "${CMAKE_COMMAND}" -D "input_file:FILEPATH=${NVCC_generated_dependency_file}" -D "output_file:FILEPATH=${cmake_dependency_file}.tmp" -P "${CUDA_make2cmake}" ) if(CUDA_result) message(FATAL_ERROR "Error generating ${generated_file}") endif() # Copy the file if it is different cuda_execute_process( "Copy if different ${cmake_dependency_file}.tmp to ${cmake_dependency_file}" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${cmake_dependency_file}.tmp" "${cmake_dependency_file}" ) if(CUDA_result) message(FATAL_ERROR "Error generating ${generated_file}") endif() # Delete the temporary file cuda_execute_process( "Removing ${cmake_dependency_file}.tmp and ${NVCC_generated_dependency_file}" COMMAND "${CMAKE_COMMAND}" -E remove "${cmake_dependency_file}.tmp" "${NVCC_generated_dependency_file}" ) if(CUDA_result) message(FATAL_ERROR "Error generating ${generated_file}") endif() # Generate the code cuda_execute_process( "Generating ${generated_file}" COMMAND "${CUDA_NVCC_EXECUTABLE}" "${source_file}" ${format_flag} -o "${generated_file}" ${CCBIN} ${nvcc_flags} ${nvcc_host_compiler_flags} ${CUDA_NVCC_FLAGS} -DNVCC ${CUDA_NVCC_INCLUDE_ARGS} ) if(CUDA_result) # Since nvcc can sometimes leave half done files make sure that we delete the output file. cuda_execute_process( "Removing ${generated_file}" COMMAND "${CMAKE_COMMAND}" -E remove "${generated_file}" ) message(FATAL_ERROR "Error generating file ${generated_file}") else() if(verbose) message("Generated ${generated_file} successfully.") endif() endif() # Cubin resource report commands. if( build_cubin ) # Run with -cubin to produce resource usage report. cuda_execute_process( "Generating ${generated_cubin_file}" COMMAND "${CUDA_NVCC_EXECUTABLE}" "${source_file}" ${CUDA_NVCC_FLAGS} ${nvcc_flags} ${CCBIN} ${nvcc_host_compiler_flags} -DNVCC -cubin -o "${generated_cubin_file}" ${CUDA_NVCC_INCLUDE_ARGS} ) # Execute the parser script. cuda_execute_process( "Executing the parser script" COMMAND "${CMAKE_COMMAND}" -D "input_file:STRING=${generated_cubin_file}" -P "${CUDA_parse_cubin}" ) endif()
wasidennis/ObjectFlow
caffe-cedn-dev/.build_release/src/caffe/CMakeFiles/caffe_cu.dir/layers/caffe_cu_generated_contrastive_loss_layer.cu.o.cmake
CMake
mit
12,418