code
stringlengths
4
1.01M
--- layout: post title: "Agile Iowa Social - November" categories: events social event: facebook-id: eventbrite-id: agile-iowa-social-november-2018-tickets-51480275891 date: 2018-11-08 time: 5:00 PM to 8:00 PM presenter: name: title: bio: location: name: The Walnut address: 1417 Walnut St citystatezip: Des Moines, IA 50309 instructions: description: slides: --- **{{page.event.date | date: "%A, %B %-d, %Y" }} from {{page.event.time}}** {% if page.event.slides %} **Download the slides:** [{{page.event.slides}}](p/{{page.event.slides}}) {% endif %} **Location** {{page.event.location.name}} {{page.event.location.address}} {{page.event.location.citystatezip}} {% if page.event.location.instructions %} *Additional instructions*: {{page.event.location.instructions}} {% endif %} <a class="btn" title="EventBrite Registration" href="http://www.eventbrite.com/e/{{page.event.eventbrite-id}}" target="_blank" data-eventdate="{{page.event.date | date: '%D'}}">Register on EventBrite</a> **Description** The format of this meeting is simple: - Show up - Order Drinks and/or Food (optional) - Socialize I hope to see you there! {{page.event.description | markdownify}} <a class="btn" title="EventBrite Registration" href="http://www.eventbrite.com/e/{{page.event.eventbrite-id}}" target="_blank">Register on EventBrite</a>
google-site-verification: googleaebfc6317de44561.html
import { createPlugin } from 'draft-extend'; // TODO(mime): can't we just use LINK? i forget why we're using ANCHOR separately..., something with images probably :-/ const ENTITY_TYPE = 'ANCHOR'; // TODO(mime): one day, maybe switch wholesale to draft-extend. for now, we have a weird hybrid // of draft-extend/draft-convert/draft-js-plugins export default createPlugin({ htmlToEntity: (nodeName, node, create) => { if (nodeName === 'a') { const mutable = node.firstElementChild?.nodeName === 'IMG' ? 'IMMUTABLE' : 'MUTABLE'; const { href, target } = node; return create(ENTITY_TYPE, mutable, { href, target }); } }, entityToHTML: (entity, originalText) => { if (entity.type === ENTITY_TYPE) { const { href } = entity.data; return `<a href="${href}" target="_blank" rel="noopener noreferrer">${originalText}</a>`; } return originalText; }, }); export const AnchorDecorator = (props) => { const { href } = props.contentState.getEntity(props.entityKey).getData(); return ( <a href={href} target="_blank" rel="noopener noreferrer"> {props.children} </a> ); }; export function anchorStrategy(contentBlock, callback, contentState) { contentBlock.findEntityRanges((character) => { const entityKey = character.getEntity(); return entityKey !== null && contentState.getEntity(entityKey).getType() === ENTITY_TYPE; }, callback); }
'use strict'; var assert = require('../../helpers/assert'); var commandOptions = require('../../factories/command-options'); var stub = require('../../helpers/stub').stub; var Promise = require('../../../lib/ext/promise'); var Task = require('../../../lib/models/task'); var TestCommand = require('../../../lib/commands/test'); describe('test command', function() { var tasks; var options; var buildRun; var testRun; beforeEach(function(){ tasks = { Build: Task.extend(), Test: Task.extend() }; options = commandOptions({ tasks: tasks, testing: true }); stub(tasks.Test.prototype, 'run', Promise.resolve()); stub(tasks.Build.prototype, 'run', Promise.resolve()); buildRun = tasks.Build.prototype.run; testRun = tasks.Test.prototype.run; }); it('builds and runs test', function() { return new TestCommand(options).validateAndRun([]).then(function() { assert.equal(buildRun.called, 1, 'expected build task to be called once'); assert.equal(testRun.called, 1, 'expected test task to be called once'); }); }); it('has the correct options', function() { return new TestCommand(options).validateAndRun([]).then(function() { var buildOptions = buildRun.calledWith[0][0]; var testOptions = testRun.calledWith[0][0]; assert.equal(buildOptions.environment, 'development', 'has correct env'); assert.ok(buildOptions.outputPath, 'has outputPath'); assert.equal(testOptions.configFile, './testem.json', 'has config file'); assert.equal(testOptions.port, 7357, 'has config file'); }); }); it('passes through custom configFile option', function() { return new TestCommand(options).validateAndRun(['--config-file=some-random/path.json']).then(function() { var testOptions = testRun.calledWith[0][0]; assert.equal(testOptions.configFile, 'some-random/path.json'); }); }); it('passes through custom port option', function() { return new TestCommand(options).validateAndRun(['--port=5678']).then(function() { var testOptions = testRun.calledWith[0][0]; assert.equal(testOptions.port, 5678); }); }); });
Reference of options that apply to runtime. ## Erase Empty Chunks When ticked, hints that empty chunks should be erased when they become empty when erasing tiles. > > **Note** - The value of this option is also respected when editing tile system at design > time. > ## Apply Basic Stripping Indicates whether a basic level of stripping should be applied when tile system receives the `Awake` message. ## Update Procedural at Start When ticked, procedural tiles will be updated when the tile system receives its first `Awake` message. ## Mark Procedural Dynamic Indicates whether procedurally generated meshes are likely to be updated throughout play where tiles are painted and/or erased frequently to improve performance (this may use more memory). It is useful to mark procedural meshes as dynamic when painting or erasing tiles as part of game-play or a custom in-game level designer. Avoid setting if procedural meshes are only updated at start of level when loading or generating map. ## Add Procedural Normals When ticked, indicates that normals should be added to procedural meshes which allows you to use shaders that require normals. This is required if you would like procedural tiles to respond to lighting. ## Procedural Sorting Layer The sorting layer that should be used for procedural tileset meshes. ## Procedural Order in Layer Order in sorting layer to use for procedural tileset meshes.
public class Prime { private Prime() { } public static void printPrimes(int max) { boolean[] flags = sieveOfEratosthenes(max); System.out.println("== Primes up to " + max + " =="); for (int i = 0; i < flags.length; i++) { if (flags[i]) { System.out.println("* " + i); } } } public static boolean[] sieveOfEratosthenes(int max) { boolean[] flags = new boolean[max + 1]; // initialize flags except 0 and 1 for (int i = 2; i < flags.length; i++) { flags[i] = true; } int prime = 2; while (prime * prime <= max) { crossOff(flags, prime); prime = getNextPrime(flags, prime); } return flags; } private static void crossOff(boolean[] flags, int prime) { for (int i = prime * prime; i < flags.length; i += prime) { flags[i] = false; } } private static int getNextPrime(boolean[] flags, int prime) { int next = prime + 1; while (next < flags.length && !flags[next]) { next++; } return next; } public static boolean isPrime(int num) { if (num < 2) return false; int prime = 2; while (prime * prime <= num) { if (num % prime == 0) return false; ++prime; } return true; } }
import Vector from '../prototype' import {componentOrder, allComponents} from './components' export const withInvertedCurryingSupport = f => { const curried = right => left => f(left, right) return (first, second) => { if (second === undefined) { // check for function to allow usage by the pipeline function if (Array.isArray(first) && first.length === 2 && !(first[0] instanceof Function) && !(first[0] instanceof Number)) { return f(first[0], first[1]) } // curried form uses the given single parameter as the right value for the operation f return curried(first) } return f(first, second) } } export const skipUndefinedArguments = (f, defaultValue) => (a, b) => a === undefined || b === undefined ? defaultValue : f(a, b) export const clone = v => { if (Array.isArray(v)) { const obj = Object.create(Vector.prototype) v.forEach((value, i) => { obj[allComponents[i]] = value }) return [...v] } const prototype = Object.getPrototypeOf(v) return Object.assign(Object.create(prototype === Object.prototype ? Vector.prototype : prototype), v) }
module.exports = function() { return { server: { src: ['<%= tmp %>/index.html'], ignorePath: /\.\.\// } } };
.mainCont{ width: 96%; border: 2px solid #666666; padding: 2%; background-color: #ffffff; } p{ vertical-align: middle;} p img{ width: 30px; height:30px; border-radius: 30px;}
require 'trajectory/exceptions/missing_attribute_error' require 'trajectory/exceptions/velocity_equal_to_zero_error' require 'trajectory/exceptions/velocity_always_equal_to_zero_error' require 'trajectory/exceptions/bad_environment_error'
@echo Copying Ogre Resources, configuration = %1 set Suffix=%1 set Configuration=%2 set Source=..\..\..\ThirdParty\OGRE-SDK-1.9.0-vc140-x86-09.01.2016 set OgreSource=OgreResource%Configuration%.%Suffix%.txt set Target=..\..\Output.%Suffix%\%Configuration%\bin for /F %%I in (%OgreSource%) do ( copy %Source%\%%I %Target% )
MIT License Copyright (c) 2017 Joe Davison 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.
import babylon from '../../babel-parser' import Documentation from '../../Documentation' import resolveExportedComponent from '../../utils/resolveExportedComponent' import classDisplayNameHandler from '../classDisplayNameHandler' jest.mock('../../Documentation') function parse(src: string) { const ast = babylon().parse(src) return resolveExportedComponent(ast)[0] } describe('classDisplayNameHandler', () => { let documentation: Documentation beforeEach(() => { documentation = new Documentation('dummy/path') }) it('should extract the name of the component from the classname', () => { const src = ` @Component export default class Decorum extends Vue{ } ` const def = parse(src).get('default') if (def) { classDisplayNameHandler(documentation, def) } expect(documentation.set).toHaveBeenCalledWith('displayName', 'Decorum') }) it('should extract the name of the component from the decorators', () => { const src = ` @Component({name: 'decorum'}) export default class Test extends Vue{ } ` const def = parse(src).get('default') if (def) { classDisplayNameHandler(documentation, def) } expect(documentation.set).toHaveBeenCalledWith('displayName', 'decorum') }) })
'use strict'; angular.module('mpApp') .factory( 'preloader', function($q, $rootScope) { // I manage the preloading of image objects. Accepts an array of image URLs. function Preloader(imageLocations) { // I am the image SRC values to preload. this.imageLocations = imageLocations; // As the images load, we'll need to keep track of the load/error // counts when announing the progress on the loading. this.imageCount = this.imageLocations.length; this.loadCount = 0; this.errorCount = 0; // I am the possible states that the preloader can be in. this.states = { PENDING: 1, LOADING: 2, RESOLVED: 3, REJECTED: 4 }; // I keep track of the current state of the preloader. this.state = this.states.PENDING; // When loading the images, a promise will be returned to indicate // when the loading has completed (and / or progressed). this.deferred = $q.defer(); this.promise = this.deferred.promise; } // --- // STATIC METHODS. // --- // I reload the given images [Array] and return a promise. The promise // will be resolved with the array of image locations. 111111 Preloader.preloadImages = function(imageLocations) { var preloader = new Preloader(imageLocations); return (preloader.load()); }; // --- // INSTANCE METHODS. // --- Preloader.prototype = { // Best practice for "instnceof" operator. constructor: Preloader, // --- // PUBLIC METHODS. // --- // I determine if the preloader has started loading images yet. isInitiated: function isInitiated() { return (this.state !== this.states.PENDING); }, // I determine if the preloader has failed to load all of the images. isRejected: function isRejected() { return (this.state === this.states.REJECTED); }, // I determine if the preloader has successfully loaded all of the images. isResolved: function isResolved() { return (this.state === this.states.RESOLVED); }, // I initiate the preload of the images. Returns a promise. 222 load: function load() { // If the images are already loading, return the existing promise. if (this.isInitiated()) { return (this.promise); } this.state = this.states.LOADING; for (var i = 0; i < this.imageCount; i++) { this.loadImageLocation(this.imageLocations[i]); } // Return the deferred promise for the load event. return (this.promise); }, // --- // PRIVATE METHODS. // --- // I handle the load-failure of the given image location. handleImageError: function handleImageError(imageLocation) { this.errorCount++; // If the preload action has already failed, ignore further action. if (this.isRejected()) { return; } this.state = this.states.REJECTED; this.deferred.reject(imageLocation); }, // I handle the load-success of the given image location. handleImageLoad: function handleImageLoad(imageLocation) { this.loadCount++; // If the preload action has already failed, ignore further action. if (this.isRejected()) { return; } // Notify the progress of the overall deferred. This is different // than Resolving the deferred - you can call notify many times // before the ultimate resolution (or rejection) of the deferred. this.deferred.notify({ percent: Math.ceil(this.loadCount / this.imageCount * 100), imageLocation: imageLocation }); // If all of the images have loaded, we can resolve the deferred // value that we returned to the calling context. if (this.loadCount === this.imageCount) { this.state = this.states.RESOLVED; this.deferred.resolve(this.imageLocations); } }, // I load the given image location and then wire the load / error // events back into the preloader instance. // -- // NOTE: The load/error events trigger a $digest. 333 loadImageLocation: function loadImageLocation(imageLocation) { var preloader = this; // When it comes to creating the image object, it is critical that // we bind the event handlers BEFORE we actually set the image // source. Failure to do so will prevent the events from proper // triggering in some browsers. var image = angular.element(new Image()) .bind('load', function(event) { // Since the load event is asynchronous, we have to // tell AngularJS that something changed. $rootScope.$apply( function() { preloader.handleImageLoad(event.target.src); // Clean up object reference to help with the // garbage collection in the closure. preloader = image = event = null; } ); }) .bind('error', function(event) { // Since the load event is asynchronous, we have to // tell AngularJS that something changed. $rootScope.$apply( function() { preloader.handleImageError(event.target.src); // Clean up object reference to help with the // garbage collection in the closure. preloader = image = event = null; } ); }) .attr('src', imageLocation); } }; // Return the factory instance. return (Preloader); } );
module SapphireBot module Events # Notifies user that bot is ready to use. module ReadyMessage extend Discordrb::EventContainer ready do BOT.game = nil LOGGER.info 'Bot is ready' end end end end
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // 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 was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk.Multivendor { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public partial struct PhysicalDeviceVertexAttributeDivisorProperties { /// <summary> /// /// </summary> public uint MaxVertexAttribDivisor { get; set; } /// <summary> /// /// </summary> /// <param name="pointer"> /// </param> internal static unsafe PhysicalDeviceVertexAttributeDivisorProperties MarshalFrom(SharpVk.Interop.Multivendor.PhysicalDeviceVertexAttributeDivisorProperties* pointer) { PhysicalDeviceVertexAttributeDivisorProperties result = default(PhysicalDeviceVertexAttributeDivisorProperties); result.MaxVertexAttribDivisor = pointer->MaxVertexAttribDivisor; return result; } } }
package com.sonnytron.sortatech.pantryprep.Fragments.IngredientFilters; import android.os.Bundle; import com.sonnytron.sortatech.pantryprep.Fragments.IngredientsListFragment; import com.sonnytron.sortatech.pantryprep.Models.Ingredient; import com.sonnytron.sortatech.pantryprep.Service.IngredientManager; import java.util.List; public class ProteinFragment extends IngredientsListFragment { public ProteinFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void updateUI() { IngredientManager ingredientManager = IngredientManager.get(getActivity()); List<Ingredient> ingredients = ingredientManager.getIngredientsProtein(); addAll(ingredients); setSpinner(1); } }
--- layout: emd_product status: publish published: true title: 1937 Horch 930V Limousine - S24_3420 author: make-your-life-simple author_login: picky-demo-admin author_email: admin@emarketdesign.com excerpt: Features opening hood, opening doors, opening trunk, wide white wall tires, front door arm rests, working steering system wordpress_id: 11697 wordpress_url: http://wordpressc.com/?emd_product=1937-horch-930v-limousine date: 2013-11-16 00:22:00.000000000 -05:00 categories: [] tags: [] comments: [] --- Features opening hood, opening doors, opening trunk, wide white wall tires, front door arm rests, working steering system
Bulkr = Dependencies - nodejs, dotjs. Currently the project was only tested on Google Chrome. Install - 1. Download dependencies 2. Clone github repo 3. Place flickr.com.js file into your ~/.js/ 4. Edit the service endpoint of the dotjs file 5. Go to server and start service by executing `node daemon.js`, service will be available on port 8080 by default. Authors - Daniel Ramirez (hello@danielrmz.com)
<?php namespace Brainapp\CoreBundle\Entity\GroupEntities; use Doctrine\ORM\EntityRepository; /** * GroupAccountRepository * * @author Chris Schneider */ class GroupAccountRepository extends EntityRepository { }
--- layout: post title: "JSON конфигурация списка задач Hangfire и их runtime обновление" date: 2016-06-17 23:30:29 +0300 image: "/assets/hangfire-logo.png" image_alt: "Hangfire scheduler" redirect_from: - backend/2016/06/17/hangfire-config-joblist/backend/ category: Backend author: "Artamoshkin Maxim" tags: [Hangfire, Scheduler, C#] description: "Явное описание задач в коде делает их достаточно неповоротливыми и неудобными в поддержке. Также было бы явным излишеством описывать однотипные задачи." --- Явное описание задач в коде делает их достаточно неповоротливыми и неудобными в поддержке. Также было бы явным излишеством описывать однотипные задачи. Было бы удобнее хранить их минимальное описание с параметрами в отдельном файле с JSON или XML разметкой, который бы автоматически подгружался при старте планировщика и далее уже обновлял список при условии, если он был изменен. У известного планировщика Quartz, такая фича идет уже из коробки, но к сожалению, в Hangfire ее нет. <!-- more --> Опишем общий интерфейс задачи. ```cs public interface IJob { void Execute(Dictionary<string, string> parameters); } ``` Для начала зарегистрируем имеющиеся джобы, удобным нам DI-контейнером. Для примера используем Castle Windsor. Регистрируем все джобы на базе интерфейса `IJob`. ```cs container.Register(Classes.FromThisAssembly().BasedOn<IJob>()); ``` Устанавливаем из NuGet дополнительный пакет: ``` Install-Package HangFire.Windsor ``` И подключаем `JobActivator` ```cs GlobalConfiguration.Configuration.UseActivator(new WindsorJobActivator(container.Kernel)); ``` После того как наши джобы зарегистрированы, приступим непосредственно к механизму конфигурации шедулера. Создаем файл конфигурации `config.json`. И определим формат записи задач. ```json [ { "Id": "1", "Name": "ExampleJob", "CronExpression": "0 0 * * *", "Parameters": { "Parameter1": "Text", "Parameter2": "123" } },… ] ``` `Name` будет выступать как в роли названия джобы, так и названия ее класса. `CronExpression` - `Cron` выражения. `Parameters` - неограниченный список параметров, которые можно передать в тело джобы. Создадим метод который будет загружать и сериализовать эти задачи: ```cs private IList<JobItem> GetJobsList() { using (var sr = new StreamReader(this.configPath)) { return JsonConvert.DeserializeObject<IList<JobItem>>(sr.ReadToEnd()); } } ``` После того как наш шедулер может получать конфигурацию джоб извне создадим метод который будет добавлять в расписание и обновлять их конфигурацию. ```cs private void UpdateConfiguration() { var jobs = this.GetJobsList(); foreach (var item in jobs) { var jobType = this.container.Kernel.GetAssignableHandlers(typeof(IJob)) .Single( h => h.ComponentModel.Implementation.Name .Equals(item.Name, StringComparison.InvariantCultureIgnoreCase)) .ComponentModel.Implementation; var job = (IJob) this.container.Resolve(jobType); RecurringJob.AddOrUpdate(item.Id, () => job.Execute(item.Parameters), item.CronExpression); } } ``` Напишем функцию которая будет наблюдать за файлом конфигурации и обновлять задачи, в случае его изменения. ```cs [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] private FileSystemWatcher CreateWatcher() { var path = Path.IsPathRooted(this.configPath) ? this.configPath : Path.Combine(Directory.GetCurrentDirectory(), this.configPath); var configDir = Path.GetDirectoryName(path) ?? string.Empty; var extension = Path.GetExtension(path); var watcher = new FileSystemWatcher { Path = configDir, NotifyFilter = NotifyFilters.LastWrite, Filter = "*" + extension }; watcher.Changed += this.OnConfigChanged; watcher.EnableRaisingEvents = true; return watcher; } private void OnConfigChanged(object sender, FileSystemEventArgs e) { if (DateTime.UtcNow < this.lastConfigChange.AddMilliseconds(200)) { return; } this.lastConfigChange = DateTime.UtcNow; this.UpdateConfiguration(); } ``` Если происходит изменение файла конфигурации, выполняется событие `OnConfigChanged`. И так как оно срабатывает несколько раз, то пропишем условие `if (DateTime.UtcNow < this.lastConfigChange.AddMilliseconds(200))`. Этого достаточно, чтобы оно сработало ровно один раз.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Sat Aug 22 11:52:38 EDT 2015 --> <title>A-Index</title> <meta name="date" content="2015-08-22"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="A-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../com/caseyweed/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Letter</li> <li><a href="index-2.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-1.html" target="_top">Frames</a></li> <li><a href="index-1.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">G</a>&nbsp;<a href="index-4.html">P</a>&nbsp;<a href="index-5.html">S</a>&nbsp;<a href="index-6.html">U</a>&nbsp;<a name="I:A"> <!-- --> </a> <h2 class="title">A</h2> <dl> <dt><span class="memberNameLink"><a href="../com/caseyweed/Pile.html#addImage-java.awt.image.BufferedImage-">addImage(BufferedImage)</a></span> - Method in class com.caseyweed.<a href="../com/caseyweed/Pile.html" title="class in com.caseyweed">Pile</a></dt> <dd> <div class="block">Add image to the current image list, but only doing so if there is a valid number of openings available based on the grid size.</div> </dd> <dt><span class="memberNameLink"><a href="../com/caseyweed/Pile.html#addImage-java.awt.image.BufferedImage-boolean-">addImage(BufferedImage, boolean)</a></span> - Method in class com.caseyweed.<a href="../com/caseyweed/Pile.html" title="class in com.caseyweed">Pile</a></dt> <dd> <div class="block">Optionally update the summary image if specified.</div> </dd> <dt><span class="memberNameLink"><a href="../com/caseyweed/Pile.html#addImage-java.awt.image.BufferedImage-boolean-boolean-">addImage(BufferedImage, boolean, boolean)</a></span> - Method in class com.caseyweed.<a href="../com/caseyweed/Pile.html" title="class in com.caseyweed">Pile</a></dt> <dd> <div class="block">Optionally update the summary image and wrap if specified.</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">G</a>&nbsp;<a href="index-4.html">P</a>&nbsp;<a href="index-5.html">S</a>&nbsp;<a href="index-6.html">U</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../com/caseyweed/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Letter</li> <li><a href="index-2.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-1.html" target="_top">Frames</a></li> <li><a href="index-1.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
/*! * Start Bootstrap - Stylish Portfolio (http://startbootstrap.com/) * Copyright 2013-2016 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE) */ /* Global Styles */ html, body { width: 100%; height: 100%; } body { font-family: "Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif; } .text-vertical-center { display: table-cell; text-align: center; vertical-align: middle; } .text-vertical-center h1 { margin: 0; padding: 0; font-size: 4.5em; font-weight: 600; } /* Custom Button Styles */ .btn-dark { border-radius: 0; color: #fff; background-color: rgba(0,0,0,0.4); } .btn-dark:hover, .btn-dark:focus, .btn-dark:active { color: #fff; background-color: rgba(0,0,0,0.7); } .btn-light { border-radius: 0; color: #333; background-color: rgb(255,255,255); } .btn-light:hover, .btn-light:focus, .btn-light:active { color: #333; background-color: rgba(255,255,255,0.8); } /* Custom Horizontal Rule */ hr.small { max-width: 100px; } /* Side Menu */ #sidebar-wrapper { z-index: 1000; position: fixed; right: 0; width: 250px; height: 100%; transform: translateX(250px); overflow-y: auto; background: #222; -webkit-transition: all 0.4s ease 0s; -moz-transition: all 0.4s ease 0s; -ms-transition: all 0.4s ease 0s; -o-transition: all 0.4s ease 0s; transition: all 0.4s ease 0s; } .sidebar-nav { position: absolute; top: 0; width: 250px; margin: 0; padding: 0; list-style: none; } .sidebar-nav li { text-indent: 20px; line-height: 40px; } .sidebar-nav li a { display: block; text-decoration: none; color: #999; } .sidebar-nav li a:hover { text-decoration: none; color: #fff; background: rgba(255,255,255,0.2); } .sidebar-nav li a:active, .sidebar-nav li a:focus { text-decoration: none; } .sidebar-nav > .sidebar-brand { height: 55px; font-size: 18px; line-height: 55px; } .sidebar-nav > .sidebar-brand a { color: #999; } .sidebar-nav > .sidebar-brand a:hover { color: #fff; background: none; } #menu-toggle { z-index: 1; position: fixed; top: 0; right: 0; } #sidebar-wrapper.active { right: 250px; width: 250px; -webkit-transition: all 0.4s ease 0s; -moz-transition: all 0.4s ease 0s; -ms-transition: all 0.4s ease 0s; -o-transition: all 0.4s ease 0s; transition: all 0.4s ease 0s; } .toggle { margin: 5px 5px 0 0; } /* Header */ .header { display: table; position: relative; width: 100%; height: 100%; background: url(../img/bg.jpg) no-repeat center center scroll; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } /* About */ .about { padding: 50px 0; } /* Services */ .services { padding: 50px 0; } .service-item { margin-bottom: 30px; } /* Callout */ .callout { display: table; width: 100%; height: 400px; color: #fff; background: url(../img/callout.jpg) no-repeat center center scroll; -webkit-background-size: cover; -moz-background-size: cover; background-size: cover; -o-background-size: cover; } /* Portfolio */ .portfolio { padding: 50px 0; } .portfolio-item { margin-bottom: 30px; } .img-portfolio { margin: 0 auto; } .img-portfolio:hover { opacity: 0.8; } /* Call to Action */ .call-to-action { padding: 50px 0; } .call-to-action .btn { margin: 10px; } /* Map */ .map { height: 500px; } @media(max-width:768px) { .map { height: 75%; } } .map iframe { pointer-events: none; } /* Footer */ footer { padding: 100px 0; } #to-top { display: none; position: fixed; bottom: 5px; right: 5px; }
/* * The MIT License (MIT) * Copyright (c) 2015 Peter Vanusanik <admin@en-circle.com> * * 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. * * ny_service.h * Created on: Jan 14, 2016 * Author: Peter Vanusanik * Contents: */ #pragma once #include "ny_stddef.h" #include "ny_commons.h" #include "devsys.h" bool service_exists(const char* service); int register_as_service(const char* service);
// // JWTClaimVerifierBase.h // JWT // // Created by Dmitry Lobanov on 30.05.2021. // Copyright © 2021 JWTIO. All rights reserved. // #import <Foundation/Foundation.h> #import <JWT/JWTClaimsSetsProtocols.h> NS_ASSUME_NONNULL_BEGIN @interface JWTClaimVerifierBase : NSObject <JWTClaimVerifierProtocol> @end NS_ASSUME_NONNULL_END
# frozen_string_literal: true module ProxyFetcher module Providers # FreeProxyList provider class. class Proxypedia < Base # Provider URL to fetch proxy list def provider_url "https://proxypedia.org" end # [NOTE] Doesn't support filtering def xpath "//main/ul/li[position()>1]" end # Converts HTML node (entry of N tags) to <code>ProxyFetcher::Proxy</code> # object.] # # @param html_node [Object] # HTML node from the <code>ProxyFetcher::Document</code> DOM model. # # @return [ProxyFetcher::Proxy] # Proxy object # def to_proxy(html_node) addr, port = html_node.content_at("a").to_s.split(":") ProxyFetcher::Proxy.new.tap do |proxy| proxy.addr = addr proxy.port = Integer(port) proxy.country = parse_country(html_node) proxy.anonymity = "Unknown" proxy.type = ProxyFetcher::Proxy::HTTP end end private def parse_country(html_node) text = html_node.content.to_s text[/\((.+?)\)/, 1] || "Unknown" end end ProxyFetcher::Configuration.register_provider(:proxypedia, Proxypedia) end end
namespace abremir.AllMyBricks.Data.Interfaces { public interface IReferenceDataRepository { T GetOrAdd<T>(string value) where T : IReferenceData, new(); } }
var gulp = require('gulp'); gulp.task('dist', ['setProduction', 'sass:dist', 'browserify:dist']);
/* json2.js 2013-05-26 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', { '': value }); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({ '': j }, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } } ());
\hypertarget{group___t_i_m___exported___functions___group8}{}\section{T\+I\+M\+\_\+\+Exported\+\_\+\+Functions\+\_\+\+Group8} \label{group___t_i_m___exported___functions___group8}\index{T\+I\+M\+\_\+\+Exported\+\_\+\+Functions\+\_\+\+Group8@{T\+I\+M\+\_\+\+Exported\+\_\+\+Functions\+\_\+\+Group8}} \subsection*{Functions} \begin{DoxyCompactItemize} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+O\+C\+\_\+\+Config\+Channel} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___o_c___init_type_def}{T\+I\+M\+\_\+\+O\+C\+\_\+\+Init\+Type\+Def} $\ast$s\+Config, uint32\+\_\+t Channel)\hypertarget{group___t_i_m___exported___functions___group8_ga6e22dfc93b7569da087a115348c3182f}{}\label{group___t_i_m___exported___functions___group8_ga6e22dfc93b7569da087a115348c3182f} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+P\+W\+M\+\_\+\+Config\+Channel} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___o_c___init_type_def}{T\+I\+M\+\_\+\+O\+C\+\_\+\+Init\+Type\+Def} $\ast$s\+Config, uint32\+\_\+t Channel)\hypertarget{group___t_i_m___exported___functions___group8_gac14a4959f65f51a54e8ff511242e2131}{}\label{group___t_i_m___exported___functions___group8_gac14a4959f65f51a54e8ff511242e2131} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+I\+C\+\_\+\+Config\+Channel} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___i_c___init_type_def}{T\+I\+M\+\_\+\+I\+C\+\_\+\+Init\+Type\+Def} $\ast$s\+Config, uint32\+\_\+t Channel)\hypertarget{group___t_i_m___exported___functions___group8_ga34805dabaf748c6eb823275dad2f19f5}{}\label{group___t_i_m___exported___functions___group8_ga34805dabaf748c6eb823275dad2f19f5} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+One\+Pulse\+\_\+\+Config\+Channel} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___one_pulse___init_type_def}{T\+I\+M\+\_\+\+One\+Pulse\+\_\+\+Init\+Type\+Def} $\ast$s\+Config, uint32\+\_\+t Output\+Channel, uint32\+\_\+t Input\+Channel)\hypertarget{group___t_i_m___exported___functions___group8_gaefb1913440053c45a4f9a50a8c05c6be}{}\label{group___t_i_m___exported___functions___group8_gaefb1913440053c45a4f9a50a8c05c6be} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+Config\+O\+Cref\+Clear} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___clear_input_config_type_def}{T\+I\+M\+\_\+\+Clear\+Input\+Config\+Type\+Def} $\ast$s\+Clear\+Input\+Config, uint32\+\_\+t Channel)\hypertarget{group___t_i_m___exported___functions___group8_ga0b960485369b4ebb1e5d41e5e9e49770}{}\label{group___t_i_m___exported___functions___group8_ga0b960485369b4ebb1e5d41e5e9e49770} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+Config\+Clock\+Source} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___clock_config_type_def}{T\+I\+M\+\_\+\+Clock\+Config\+Type\+Def} $\ast$s\+Clock\+Source\+Config)\hypertarget{group___t_i_m___exported___functions___group8_ga43403d13849f71285ea1da3f3cb1381f}{}\label{group___t_i_m___exported___functions___group8_ga43403d13849f71285ea1da3f3cb1381f} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+Config\+T\+I1\+Input} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, uint32\+\_\+t T\+I1\+\_\+\+Selection)\hypertarget{group___t_i_m___exported___functions___group8_ga7dfab2adafd2f2e315a9531f1150c201}{}\label{group___t_i_m___exported___functions___group8_ga7dfab2adafd2f2e315a9531f1150c201} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+Slave\+Config\+Synchronization} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___slave_config_type_def}{T\+I\+M\+\_\+\+Slave\+Config\+Type\+Def} $\ast$s\+Slave\+Config)\hypertarget{group___t_i_m___exported___functions___group8_ga07f536c10b542bc9695f23b1e84b5fce}{}\label{group___t_i_m___exported___functions___group8_ga07f536c10b542bc9695f23b1e84b5fce} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+Slave\+Config\+Synchronization\+\_\+\+IT} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, \hyperlink{struct_t_i_m___slave_config_type_def}{T\+I\+M\+\_\+\+Slave\+Config\+Type\+Def} $\ast$s\+Slave\+Config)\hypertarget{group___t_i_m___exported___functions___group8_gaba7e347f58f5e49592cc79d453ad6602}{}\label{group___t_i_m___exported___functions___group8_gaba7e347f58f5e49592cc79d453ad6602} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+D\+M\+A\+Burst\+\_\+\+Write\+Start} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, uint32\+\_\+t Burst\+Base\+Address, uint32\+\_\+t Burst\+Request\+Src, uint32\+\_\+t $\ast$Burst\+Buffer, uint32\+\_\+t Burst\+Length)\hypertarget{group___t_i_m___exported___functions___group8_ga8d1a48bb07dcf9030de10b9c6918087c}{}\label{group___t_i_m___exported___functions___group8_ga8d1a48bb07dcf9030de10b9c6918087c} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+D\+M\+A\+Burst\+\_\+\+Write\+Stop} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, uint32\+\_\+t Burst\+Request\+Src)\hypertarget{group___t_i_m___exported___functions___group8_ga8f5649baaf219f2559bbe9e8e2c3658e}{}\label{group___t_i_m___exported___functions___group8_ga8f5649baaf219f2559bbe9e8e2c3658e} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+D\+M\+A\+Burst\+\_\+\+Read\+Start} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, uint32\+\_\+t Burst\+Base\+Address, uint32\+\_\+t Burst\+Request\+Src, uint32\+\_\+t $\ast$Burst\+Buffer, uint32\+\_\+t Burst\+Length)\hypertarget{group___t_i_m___exported___functions___group8_ga39c612c473747448615e2e3cb2668224}{}\label{group___t_i_m___exported___functions___group8_ga39c612c473747448615e2e3cb2668224} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+D\+M\+A\+Burst\+\_\+\+Read\+Stop} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, uint32\+\_\+t Burst\+Request\+Src)\hypertarget{group___t_i_m___exported___functions___group8_ga41cfa290ee87229cba1962e78e2a9d01}{}\label{group___t_i_m___exported___functions___group8_ga41cfa290ee87229cba1962e78e2a9d01} \item \hyperlink{stm32f4xx__hal__def_8h_a63c0679d1cb8b8c684fbb0632743478f}{H\+A\+L\+\_\+\+Status\+Type\+Def} {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+Generate\+Event} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, uint32\+\_\+t Event\+Source)\hypertarget{group___t_i_m___exported___functions___group8_gab4a60fe7cbb64a321bdce2ee1b9c8730}{}\label{group___t_i_m___exported___functions___group8_gab4a60fe7cbb64a321bdce2ee1b9c8730} \item uint32\+\_\+t {\bfseries H\+A\+L\+\_\+\+T\+I\+M\+\_\+\+Read\+Captured\+Value} (\hyperlink{struct_t_i_m___handle_type_def}{T\+I\+M\+\_\+\+Handle\+Type\+Def} $\ast$htim, uint32\+\_\+t Channel)\hypertarget{group___t_i_m___exported___functions___group8_ga6528480e73e4e51d5ce8aaca00d64d13}{}\label{group___t_i_m___exported___functions___group8_ga6528480e73e4e51d5ce8aaca00d64d13} \end{DoxyCompactItemize} \subsection{Detailed Description}
package main import ( "fmt" "io" "log" "net/http" "os" "time" "github.com/elazarl/goproxy" ) const ( AppendLog int = iota ReopenLog int = iota ) var ( emptyResp = &http.Response{} emptyReq = &http.Request{} ) type LogData struct { action int req *http.Request resp *http.Response user string err error time time.Time } type ProxyLogger struct { path string logChannel chan *LogData errorChannel chan error } func fprintf(nr *int64, err *error, w io.Writer, pat string, a ...interface{}) { if *err != nil { return } var n int n, *err = fmt.Fprintf(w, pat, a...) *nr += int64(n) } func getAuthenticatedUserName(ctx *goproxy.ProxyCtx) string { user, ok := ctx.UserData.(string) if !ok { user = "-" } return user } func (m *LogData) writeTo(w io.Writer) (nr int64, err error) { if m.resp != nil { if m.resp.Request != nil { fprintf(&nr, &err, w, "%v %v %v %v %v %v %v\n", m.time.Format(time.RFC3339), m.resp.Request.RemoteAddr, m.resp.Request.Method, m.resp.Request.URL, m.resp.StatusCode, m.resp.ContentLength, m.user) } else { fprintf(&nr, &err, w, "%v %v %v %v %v %v %v\n", m.time.Format(time.RFC3339), "-", "-", "-", m.resp.StatusCode, m.resp.ContentLength, m.user) } } else if m.req != nil { fprintf(&nr, &err, w, "%v %v %v %v %v %v %v\n", m.time.Format(time.RFC3339), m.req.RemoteAddr, m.req.Method, m.req.URL, "-", "-", m.user) } return } func newProxyLogger(conf *Configuration) *ProxyLogger { var fh *os.File if conf.AccessLog != "" { var err error fh, err = os.OpenFile(conf.AccessLog, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { log.Fatalf("Couldn't open log file: %v", err) } } logger := &ProxyLogger{ path: conf.AccessLog, logChannel: make(chan *LogData), errorChannel: make(chan error), } go func() { for m := range logger.logChannel { if fh != nil { switch m.action { case AppendLog: if _, err := m.writeTo(fh); err != nil { log.Println("Can't write meta", err) } case ReopenLog: err := fh.Close() if err != nil { log.Fatal(err) } fh, err = os.OpenFile(conf.AccessLog, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { log.Fatalf("Couldn't reopen log file: %v", err) } } } } logger.errorChannel <- fh.Close() }() return logger } func (logger *ProxyLogger) logResponse(resp *http.Response, ctx *goproxy.ProxyCtx) { if resp == nil { resp = emptyResp } logger.writeLogEntry(&LogData{ action: AppendLog, resp: resp, user: getAuthenticatedUserName(ctx), err: ctx.Error, time: time.Now(), }) } func (logger *ProxyLogger) writeLogEntry(data *LogData) { logger.logChannel <- data } func (logger *ProxyLogger) log(ctx *goproxy.ProxyCtx) { data := &LogData{ action: AppendLog, req: ctx.Req, resp: ctx.Resp, user: getAuthenticatedUserName(ctx), err: ctx.Error, time: time.Now(), } logger.writeLogEntry(data) } func (logger *ProxyLogger) close() error { close(logger.logChannel) return <-logger.errorChannel } func (logger *ProxyLogger) reopen() { logger.writeLogEntry(&LogData{action: ReopenLog}) }
'use strict'; import Chart from 'chart.js'; import Controller from './controller'; import Scale, {defaults} from './scale'; // Register the Controller and Scale Chart.controllers.smith = Controller; Chart.defaults.smith = { aspectRatio: 1, scale: { type: 'smith', }, tooltips: { callbacks: { title: () => null, label: (bodyItem, data) => { const dataset = data.datasets[bodyItem.datasetIndex]; const d = dataset.data[bodyItem.index]; return dataset.label + ': ' + d.real + ' + ' + d.imag + 'i'; } } } }; Chart.scaleService.registerScaleType('smith', Scale, defaults);
--- st: published_at: 2016-06-16 type: "User_Guide" seo: title: Two-Factor Authentication description: Two-Factor Authentication gives you an extra layer of security to protect your SendGrid account. keywords: 2FA, two-factor authentication, authentication, security, authy title: Two-Factor Authentication weight: 0 layout: page navigation: show: true --- <iframe src="https://player.vimeo.com/video/248169751" width="700" height="400" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> Two-factor authentication, commonly referred to as multi-factor authentication, allows you to make your SendGrid account more secure by requiring authentication beyond a simple username and password when logging in. SendGrid’s Two-Factor Authentication can be configured to accept a code sent to your mobile phone either via the [Authy App](https://www.authy.com/app/mobile/), or an SMS message. * [Setting Up Two-Factor Authentication](#-Setting-Up-Two-Factor-Authentication) * [Using Two-Factor Authentication](#-Using-Two-Factor-Authentication) * [Disabling Two-Factor Authentication](#-Disabling-Two-Factor-Authentication) * [Regaining access to my account when I've been locked out by Two-Factor Authentication](#-Regaining-access-to-my-account-when-I--ve-been-locked-out-by-Two-Factor-Authentication) {% anchor h2 %} Setting Up Two-Factor Authentication {% endanchor h2 %} You may choose from two different verification methods when using two-factor authentication: 1. Generate a verification code with the [Authy App](https://www.authy.com/app/mobile/). The Authy App allows you to authenticate over WiFi if you do not have cellular service. However, you may still resort to an SMS message as a backup if you decide to use Authy. 1. Enter a code sent to your mobile phone that is generated by SendGrid. {% warning %} When authenticating via SMS message, you must have cellular service, or you will not be able to log into your account. {% endwarning %} {% info %} You can create multiple configurations of Two-Factor Authentication, allowing you to use more than one mobile device to authenticate when logging into your account. {% endinfo %} *To set up Two-Factor Authentication:* 1. Navigate to **Settings**, and click **Two-Factor Authentication**. <br>From this page, you see an overview of your Two-Factor Authentication settings, along with any settings that you have created for credentialed users. 1. Click **Add Two-Factor Authentication**. 1. Select either the Authy App or text messages (SMS) as your means of authentication. 1. Enter your **country code** and **phone number**. {% info %} Subusers and Teammates need to create their own Two-Factor Authentication settings in their account using the same steps. {% endinfo %} {% anchor h2 %} Using Two-Factor Authentication {% endanchor h2 %} After you create a setting for Two-Factor Authentication, log in as you normally would. If you opt to receive a text message with your authentication token, look for the text message and enter the code that you receive. If you have selected the Authy App, go to your app, and enter the generated code. Once set up, you will always be required to use Two-Factor Authentication to perform security-restricted actions in your SendGrid account, such as logging in or changing your Two-Factor Authentication settings. When prompted, enter the 7-digit token sent to your device, or generated by the Authy App. {% anchor h2 %} Disabling Two-Factor Authentication {% endanchor h2 %} *To disable or delete a Two-Factor Authentication setting:* 1. Navigate to **Settings**, and click **Two-Factor Authentication**. 1. Find the setting you would like to delete. 1. Click the **action menu**, and then select **Delete**. 1. Enter the 7 digit code you receive via text or Authy app into the field and then click **Delete**. {% anchor h2 %} Regaining access to my account after being locked out by Two-Factor Authentication {% endanchor h2 %} If you find that you’ve lost access to your account as a result of Two-Factor Authentication, please reach out to the [Authy Support Team](https://support.authy.com/hc/en-us). {% anchor h2 %} Additional Resources {% endanchor h2 %} * [Restoring Authy access on lost or inaccessible phones](https://support.authy.com/hc/en-us/articles/115012672088-Restoring-Authy-access-on-lost-or-inaccessible-phones)
var packageInfo = require('./package.json'); var taskList = [{name:'default'},{name:'delete'},{name:'build'},{name:'copy'},{name:'minify'}]; var gulpTalk2me = require('gulp-talk2me'); var talk2me = new gulpTalk2me(packageInfo,taskList); var del = require('del'); var gulp = require('gulp'); var runSequence = require('run-sequence'); var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); var ngAnnotate = require('gulp-ng-annotate'); var bytediff = require('gulp-bytediff'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var templateCache = require('gulp-angular-templatecache'); var series = require('stream-series'); var angularFilesort = require('gulp-angular-filesort'); console.log(talk2me.greeting); gulp.task('default',function(callback){ runSequence('build',callback); }); gulp.task('delete',function(callback){ del('dist/**/*', callback()); }); gulp.task('build',function(callback){ runSequence('delete',['copy','minify'],callback); }); gulp.task('copy',function(){ return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js'])) .pipe(sourcemaps.init()) .pipe(angularFilesort()) .pipe(concat('bs-fa-boolean-directive.js', {newLine: ';\n'})) .pipe(ngAnnotate({ add: true })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); gulp.task('minify',function(){ return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js'])) .pipe(sourcemaps.init()) .pipe(angularFilesort()) .pipe(concat('bs-fa-boolean-directive.js', {newLine: ';'})) .pipe(rename(function (path) { path.basename += ".min"; })) .pipe(ngAnnotate({ add: true })) .pipe(bytediff.start()) .pipe(uglify({mangle: true})) .pipe(bytediff.stop()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); function genTemplateStream () { return gulp.src(['src/**/*.view.html']) .pipe(templateCache({standalone:true,module:'bs-fa-boolean.template'})); }
//https://github.com/nothingrandom/project_euler.js var square=0;var sum=0;var answer=0;var number2=0;for(var i=0;i<=100;i++){var number=Math.pow(i,2);square+=number}for(var i=0;i<=100;i++){number2+=i;sum=Math.pow(number2,2)}var answer=sum-square;console.log(answer)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `getgid` fn in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, getgid"> <title>libc::funcs::posix88::unistd::getgid - Rust</title> <link rel="stylesheet" type="text/css" href="../../../../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a> <p class='location'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>funcs</a>::<wbr><a href='../index.html'>posix88</a>::<wbr><a href='index.html'>unistd</a></p><script>window.sidebarCurrent = {name: 'getgid', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'><a href='../../../index.html'>libc</a>::<wbr><a href='../../index.html'>funcs</a>::<wbr><a href='../index.html'>posix88</a>::<wbr><a href='index.html'>unistd</a>::<wbr><a class='fn' href=''>getgid</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-4108' class='srclink' href='../../../../src/libc/lib.rs.html#5835' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe extern fn getgid() -&gt; <a class='type' href='../../../../libc/types/os/arch/posix88/type.gid_t.html' title='libc::types::os::arch::posix88::gid_t'>gid_t</a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../../"; window.currentCrate = "libc"; window.playgroundUrl = "https://play.rust-lang.org/"; </script> <script src="../../../../jquery.js"></script> <script src="../../../../main.js"></script> <script src="../../../../playpen.js"></script> <script async src="../../../../search-index.js"></script> </body> </html>
package tunnel import ( "bytes" stdcrypto "crypto" "encoding/base64" "errors" "fmt" "net" "net/url" "os" "os/user" "path/filepath" "reflect" "regexp" "runtime" "strconv" "strings" "github.com/Lafeng/deblocus/auth" "github.com/Lafeng/deblocus/crypto" "github.com/Lafeng/deblocus/exception" "github.com/go-ini/ini" "github.com/kardianos/osext" ) const ( CF_CLIENT = "deblocus.Client" CF_SERVER = "deblocus.Server" CF_URL = "URL" CF_KEY = "Key" CF_CRYPTO = "Crypto" CF_PRIVKEY = "PrivateKey" CF_CREDENTIAL = "Credential" CF_PAC = "PAC.Server" CF_FILE = "File" CONFIG_NAME = "deblocus.ini" SIZE_UNIT = "BKMG" ) var ( UNRECOGNIZED_SYMBOLS = exception.New("Unrecognized symbols") LOCAL_BIND_ERROR = exception.New("Local bind error") CONF_MISS = exception.New("Missed field in config:") CONF_ERROR = exception.New("Error field in config:") ) type ServerRole uint32 const ( SR_AUTO ServerRole = ^ServerRole(0) SR_CLIENT ServerRole = 0x0f SR_SERVER ServerRole = 0xf0 ) type ConfigMan struct { filepath string iniInstance *ini.File sConf *serverConf cConf *clientConf } func DetectConfig(specifiedFile string) (*ConfigMan, error) { var paths []string if specifiedFile == NULL { paths = []string{CONFIG_NAME} // cwd var ef, home string var err error // same path with exe ef, err = osext.ExecutableFolder() if err == nil { paths = append(paths, filepath.Join(ef, CONFIG_NAME)) } // home if u, err := user.Current(); err == nil { home = u.HomeDir } else { home = os.Getenv("HOME") } if home != NULL { paths = append(paths, filepath.Join(home, CONFIG_NAME)) } // etc if runtime.GOOS != "windows" { paths = append(paths, "/etc/deblocus/"+CONFIG_NAME) } } else { paths = []string{specifiedFile} } var file *string for _, f := range paths { if f != NULL && !IsNotExist(f) { file = &f break } } if file == nil { msg := fmt.Sprintf("Not found `%s` in [ %s ]\n", CONFIG_NAME, strings.Join(paths, "; ")) msg += "Create config in typical path or specify it with option `--config/-c`." return nil, errors.New(msg) } iniInstance, err := ini.Load(*file) return &ConfigMan{ filepath: *file, iniInstance: iniInstance, }, err } func (cman *ConfigMan) InitConfigByRole(expectedRole ServerRole) (r ServerRole, err error) { if expectedRole&SR_CLIENT != 0 { if _, err = cman.iniInstance.GetSection(CF_CLIENT); err == nil { r |= SR_CLIENT cman.cConf, err = cman.ParseClientConf() } else if expectedRole == SR_AUTO { // AUTO ignore err = nil } if err != nil { goto abort } } if expectedRole&SR_SERVER != 0 { if _, err = cman.iniInstance.GetSection(CF_SERVER); err == nil { r |= SR_SERVER cman.sConf, err = cman.ParseServConf() } else if expectedRole == SR_AUTO { // AUTO ignore err = nil } if err != nil { goto abort } } cman.iniInstance = nil abort: return r, err } func (cman *ConfigMan) LogV(expectedRole ServerRole) int { if expectedRole&SR_SERVER != 0 { return cman.sConf.Verbose } if expectedRole&SR_CLIENT != 0 { return cman.cConf.Verbose } return -1 } func (cman *ConfigMan) ListenAddr(expectedRole ServerRole) *net.TCPAddr { if expectedRole&SR_SERVER != 0 { return cman.sConf.ListenAddr } if expectedRole&SR_CLIENT != 0 { return cman.cConf.ListenAddr } return nil } func (cman *ConfigMan) KeyInfo(expectedRole ServerRole) string { var buf = new(bytes.Buffer) if expectedRole&SR_SERVER != 0 { key := cman.sConf.publicKey fmt.Fprintln(buf, "Server Key in", cman.filepath) fmt.Fprintln(buf, " type:", NameOfKey(key)) fmt.Fprintln(buf, " fingerprint:", FingerprintOfKey(key)) } if expectedRole&SR_CLIENT != 0 { key := cman.cConf.connInfo.sPubKey fmt.Fprintln(buf, "Credential Key in", cman.filepath) fmt.Fprintln(buf, " type:", NameOfKey(key)) fmt.Fprintln(buf, " fingerprint:", FingerprintOfKey(key)) } return buf.String() } // client config definitions type clientConf struct { Listen string `importable:":9009"` Verbose int `importable:"1"` ListenAddr *net.TCPAddr `ini:"-"` connInfo *connectionInfo } func (c *clientConf) validate() error { if c.connInfo == nil { return CONF_MISS.Apply("Not found credential") } if c.Listen == NULL { return CONF_MISS.Apply("Listen") } a, e := net.ResolveTCPAddr("tcp", c.Listen) if e != nil { return LOCAL_BIND_ERROR.Apply(e) } pkType := NameOfKey(c.connInfo.sPubKey) if pkType != c.connInfo.pkType { return CONF_ERROR.Apply(pkType) } if c.connInfo.pacFile != NULL && IsNotExist(c.connInfo.pacFile) { return CONF_ERROR.Apply("File Not Found " + c.connInfo.pacFile) } c.ListenAddr = a return nil } type connectionInfo struct { sAddr string provider string cipher string user string pass string pkType string pacFile string sPubKey stdcrypto.PublicKey rawURL string } func (d *connectionInfo) RemoteName() string { if d.provider != NULL { return d.provider } else { return d.sAddr } } func newConnectionInfo(uri string) (*connectionInfo, error) { url, err := url.Parse(uri) if err != nil { return nil, err } if url.Scheme != "d5" { return nil, CONF_ERROR.Apply(url.Scheme) } _, err = net.ResolveTCPAddr("tcp", url.Host) if err != nil { return nil, HOST_UNREACHABLE.Apply(err) } var tmp string var info = connectionInfo{sAddr: url.Host} if len(url.Path) > 1 { info.provider, tmp = SubstringBefore(url.Path[1:], "=") } if info.provider == NULL { return nil, CONF_MISS.Apply("Provider") } info.pkType, info.cipher = SubstringBefore(tmp, "/") _, err = GetAvailableCipher(info.cipher) if err != nil { return nil, err } user := url.User if user == nil || user.Username() == NULL { return nil, CONF_MISS.Apply("user") } passwd, ok := user.Password() if !ok || passwd == NULL { return nil, CONF_MISS.Apply("passwd") } info.user = user.Username() info.pass = passwd info.rawURL = uri return &info, nil } // public for external handler func (cman *ConfigMan) CreateClientConfig(file string, user string, addonAddr string) (err error) { var f *os.File if file == NULL { f = os.Stdout } else { f, err = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644) if err != nil { return err } defer f.Close() } defer f.Sync() var sAddr string var conf = new(clientConf) var newIni = ini.Empty() setFieldsDefaultValue(conf) // client section dc, _ := newIni.NewSection(CF_CLIENT) dc.Comment = _CLT_CONF_HEADER[1:] dc.ReflectFrom(conf) // prepare server addr if addonAddr == NULL { sAddr = findFirstUnicastAddress() if sAddr == NULL { sAddr = "localhost:9008" } else { sPort := findServerListenPort(cman.sConf.Listen) sAddr = fmt.Sprint(sAddr, ":", sPort) } cman.sConf.Listen = sAddr } else { err = IsValidHost(addonAddr) cman.sConf.Listen = addonAddr if err != nil { return } } err = cman.sConf.generateConnInfoOfUser(newIni, user) if err == nil { _, err = newIni.WriteTo(f) if addonAddr == NULL { var notice = strings.Replace(_NOTICE_MOD_ADDR, "ADDR", sAddr, -1) fmt.Fprint(f, notice) } } return } // public for external func (cman *ConfigMan) ParseClientConf() (conf *clientConf, err error) { ii := cman.iniInstance secDc, err := ii.GetSection(CF_CLIENT) if err != nil { return } conf = new(clientConf) err = secDc.MapTo(conf) if err != nil { return } cr, err := ii.GetSection(CF_CREDENTIAL) if err != nil { return } url, err := cr.GetKey(CF_URL) if err != nil { return } connInfo, err := newConnectionInfo(url.String()) if err != nil { return } pubkeyObj, err := cr.GetKey(CF_KEY) if err != nil { return } pubkeyBytes, err := base64.StdEncoding.DecodeString(pubkeyObj.String()) if err != nil { return } pubkey, err := UnmarshalPublicKey(pubkeyBytes) if err != nil { return } secPac, _ := ii.GetSection(CF_PAC) if secPac != nil && secPac.Haskey(CF_FILE) { pacFile, _ := secPac.GetKey(CF_FILE) connInfo.pacFile = pacFile.String() } connInfo.sPubKey = pubkey conf.connInfo = connInfo err = conf.validate() return } // Server config definitions type serverConf struct { Listen string `importable:":9008"` Auth string `importable:"file://_USER_PASS_FILE_PATH_"` Cipher string `importable:"AES128CTR"` ServerName string `importable:"_MY_SERVER"` Parallels int `importable:"2"` Verbose int `importable:"1"` DenyDest string `importable:"OFF"` ErrorFeedback string `importable:"true"` AuthSys auth.AuthSys `ini:"-"` ListenAddr *net.TCPAddr `ini:"-"` errFeedback bool privateKey stdcrypto.PrivateKey publicKey stdcrypto.PublicKey } func (d *serverConf) validate() error { if len(d.Listen) < 1 { return CONF_MISS.Apply("Listen") } a, e := net.ResolveTCPAddr("tcp", d.Listen) if e != nil { return LOCAL_BIND_ERROR.Apply(e) } d.ListenAddr = a if len(d.Auth) < 1 { return CONF_MISS.Apply("Auth") } d.AuthSys, e = auth.GetAuthSysImpl(d.Auth) if e != nil { return e } if len(d.Cipher) < 1 { return CONF_MISS.Apply("Cipher") } _, e = GetAvailableCipher(d.Cipher) if e != nil { return e } if d.ServerName == NULL { return CONF_MISS.Apply("ServerName") } if d.Parallels < 2 || d.Parallels > 16 { return CONF_ERROR.Apply("Parallels") } if d.privateKey == nil { return CONF_MISS.Apply("PrivateKey") } if len(d.DenyDest) > 0 { if d.DenyDest == "OFF" || d.DenyDest == "off" { d.DenyDest = NULL } else if !regexp.MustCompile("[A-Za-z]{2}").MatchString(d.DenyDest) { return CONF_ERROR.Apply("DenyDest must be ISO3166-1 2-letter Country Code") } } if len(d.ErrorFeedback) > 0 { d.errFeedback, e = strconv.ParseBool(d.ErrorFeedback) if e != nil { return CONF_ERROR.Apply("ErrorFeedback") } } return nil } // public for external handler func (cman *ConfigMan) ParseServConf() (d5s *serverConf, err error) { ii := cman.iniInstance sec, err := ii.GetSection(CF_SERVER) if err != nil { return } d5s = new(serverConf) if err = sec.MapTo(d5s); err != nil { return } kSec, err := ii.GetSection(CF_PRIVKEY) if err != nil { return } key, err := kSec.GetKey(CF_KEY) if err != nil { return } keyBytes, err := base64.StdEncoding.DecodeString(key.String()) if err != nil { return } priv, err := UnmarshalPrivateKey(keyBytes) if err != nil { return } d5s.privateKey = priv d5s.publicKey = priv.(stdcrypto.Signer).Public() err = d5s.validate() return } // public for external handler func CreateServerConfigTemplate(file string, keyOpt string) (err error) { var f *os.File if file == NULL { f = os.Stdout } else { f, err = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600) if err != nil { return } defer f.Close() } defer f.Sync() d5sConf := new(serverConf) d5sConf.setDefaultValue() // uppercase algo name keyOpt = strings.ToUpper(keyOpt) d5sConf.privateKey, err = GenerateDSAKey(keyOpt) if err != nil { return } ii := ini.Empty() ds, _ := ii.NewSection(CF_SERVER) ds.Comment = _SER_CONF_HEADER[1:] err = ds.ReflectFrom(d5sConf) if err != nil { return } ks, _ := ii.NewSection(CF_PRIVKEY) keyBytes := MarshalPrivateKey(d5sConf.privateKey) ks.Comment = _SER_CONF_MIDDLE[1:] ks.NewKey(CF_KEY, base64.StdEncoding.EncodeToString(keyBytes)) _, err = ii.WriteTo(f) return } func (d *serverConf) generateConnInfoOfUser(ii *ini.File, user string) error { u, err := d.AuthSys.UserInfo(user) if err != nil { return err } keyBytes, err := MarshalPublicKey(d.publicKey) if err != nil { return err } url := fmt.Sprintf("d5://%s:%s@%s/%s=%s/%s", u.Name, u.Pass, d.Listen, d.ServerName, NameOfKey(d.publicKey), d.Cipher) sec, _ := ii.NewSection(CF_CREDENTIAL) sec.NewKey(CF_URL, url) sec.NewKey(CF_KEY, base64.StdEncoding.EncodeToString(keyBytes)) sec.Comment = _COMMENTED_PAC_SECTION return nil } // set default values by field comment // set recommended values by detecting func (d *serverConf) setDefaultValue() { setFieldsDefaultValue(d) host, err := os.Hostname() if err == nil { host = regexp.MustCompile(`\W`).ReplaceAllString(host, "") d.ServerName = strings.ToUpper(host) } if crypto.HasAESHardware() == 0 { d.Cipher = "CHACHA12" } } func setFieldsDefaultValue(str interface{}) { typ := reflect.TypeOf(str) val := reflect.ValueOf(str) if typ.Kind() == reflect.Ptr { typ = typ.Elem() val = val.Elem() } for i := 0; i < typ.NumField(); i++ { ft := typ.Field(i) fv := val.Field(i) imp := ft.Tag.Get("importable") if !ft.Anonymous && imp != NULL { k := fv.Kind() switch k { case reflect.String: fv.SetString(imp) case reflect.Int: intVal, err := strconv.ParseInt(imp, 10, 0) if err == nil { fv.SetInt(intVal) } default: panic(fmt.Errorf("unsupported %v", k)) } } } } func findServerListenPort(addr string) int { n, e := net.ResolveTCPAddr("tcp", addr) if e != nil { return 9008 } return n.Port } func findFirstUnicastAddress() string { nic, e := net.InterfaceAddrs() if nic != nil && e == nil { for _, v := range nic { if i, _ := v.(*net.IPNet); i != nil { if i.IP.IsGlobalUnicast() { return i.IP.String() } } } } return NULL } const _SER_CONF_HEADER = ` # --------------------------------------------- # deblocus server configuration # wiki: https://github.com/Lafeng/deblocus/wiki # --------------------------------------------- ` const _SER_CONF_MIDDLE = ` ### Please take good care of this secret file during the server life cycle. ### DO NOT modify the following lines, unless you known what will happen. ` const _CLT_CONF_HEADER = ` # --------------------------------------------- # deblocus client configuration # wiki: https://github.com/Lafeng/deblocus/wiki # --------------------------------------------- ` const _COMMENTED_PAC_SECTION = `# Optional # [PAC.Server] # File = mypac.js ` const _NOTICE_MOD_ADDR = ` # +-----------------------------------------------------------------+ # May need to modify the "ADDR" to your public address. # +-----------------------------------------------------------------+ `
module Fog module OpenStack class Compute class Real def get_server_details(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}" ) end end class Mock def get_server_details(server_id) response = Excon::Response.new server = list_servers_detail.body['servers'].find { |srv| srv['id'] == server_id } if server response.status = [200, 203][rand(2)] response.body = {'server' => server} response else raise Fog::OpenStack::Compute::NotFound end end end end end end
<?php /* File: class/class_api.php Created: 11/10/2016 at 1:34PM Eastern Time Info: Creates a class file to use as an API for modders who don't wish to use the main game code! Author: TheMasterGeneral Website: https://github.com/MasterGeneral156/chivalry-engine */ if (!defined('MONO_ON')) { exit; } class user { /* Tests to see if specified user has at least the specified amount of money. @param int user = User ID to test for. @param text type = Currency type. [Ex. primary or secondary] @param int money = Minimum money requied. Returns true if user has more cash than required. Returns false if user does not exist or does not have the minimum cash requred. */ function hasCurrency(int $user, string $type, int $minimum) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $minimum = (isset($minimum) && is_numeric($minimum)) ? abs(intval($minimum)) : 0; $type = $db->escape(stripslashes(strtolower($type))); $userexist = $db->fetch_single($db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}")); if ($userexist) { if ($type == 'primary' || $type == 'secondary') { $UserMoney = $db->fetch_single($db->query("SELECT `{$type}_currency` FROM `users` WHERE `userid` = {$user}")); if ($UserMoney >= $minimum) { return true; } } } } /* Gives the user the specified item and quantity @param int user = User ID to test for. @param int item = Item ID to give to the user. @param int quantity = Quantity of item to give to the user. Returns true if item successfully given to the user. Returns false if item failed to be given to user. */ function giveItem(int $user, int $item, int $quantity) { $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $item = (isset($item) && is_numeric($item)) ? abs(intval($item)) : 0; $quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0; if (addItem($user, $item, $quantity)) { return true; } } /* Removes an item from the user specified @param int user = User ID to test for. @param int item = Item ID to take from the user. @param int quantity = Quantity of item to remove from the user. Returns true if item successfully taken from the user. Returns false if item failed to be taken from user. */ function takeItem(int $user, int $item, int $quantity) { $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $item = (isset($item) && is_numeric($item)) ? abs(intval($item)) : 0; $quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0; if (takeItem($user, $item, $quantity)) { return true; } } /* Test to see whether or not the specified user has the item and optionally, an amount of the item. @param int user = User to test on. @param int item = Item ID to test for. @param int qty = Quantity to test for. Optional. [Default: 1] Returns true if the user has the item and requried quantity. False if otherwise. */ function hasItem(int $user, int $item, int $qty = 1) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $item = (isset($item) && is_numeric($item)) ? abs(intval($item)) : 0; $qty = (isset($qty) && is_numeric($qty)) ? abs(intval($qty)) : 0; if ($user > 0 || $item > 0 || $qty > 0) { $i = $db->fetch_single($db->query("SELECT `inv_qty` FROM `inventory` WHERE `inv_userid` = {$user} && `inv_itemid` = {$item}")); if ($qty == 1) if ($i >= 1) return true; else if ($i >= $qty) return true; } } /* Function to fetch item count from a user's inventory. @param int userid = User ID of the player to test inventory. @param int itemid = Item ID to count. Returns the count of Item ID found on the user. */ function countItem(int $userid, int $itemid) { global $db; $userid = (isset($userid) && is_numeric($userid)) ? abs(intval($userid)) : 0; $itemid = (isset($itemid) && is_numeric($itemid)) ? abs(intval($itemid)) : 0; if (!empty($userid) || !empty($itemid)) { $qty = $db->fetch_single($db->query("SELECT SUM(`inv_qty`) FROM `inventory` WHERE `inv_itemid` = {$itemid} AND `inv_userid` = {$userid}")); return $qty; } } /* Gives user specified amount of currency type. @param int user = User ID to give currency to. @param int type = Currency type. [Ex. primary and secondary] @param int money = Currency given. Returns true if user has received currency. Returns false if user does not receive currency. */ function giveCurrency(int $user, string $type, int $quantity) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $type = $db->escape(stripslashes(strtolower($type))); $quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0; $userexist = $db->fetch_single($db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}")); if ($userexist) { if ($type == 'primary' || $type == 'secondary') { $db->query("UPDATE `users` SET `{$type}_currency` = `{$type}_currency` + {$quantity} WHERE `userid` = {$user}"); return true; } } } /* Takes qunatity of currency type from the user specified. @param int user = User ID to give currency to. @param int type = Currency type. [Ex. primary and secondary] @param int money = Currency given. Returns true if user has lost currency. Returns false if user does not lose any currency. */ function takeCurrency(int $user, string $type, int $quantity) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $type = $db->escape(stripslashes(strtolower($type))); $quantity = (isset($quantity) && is_numeric($quantity)) ? abs(intval($quantity)) : 0; $userexist = $db->fetch_single($db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}")); if ($userexist) { if ($type == 'primary' || $type == 'secondary') { $db->query("UPDATE `users` SET `{$type}_currency` = `{$type}_currency` - {$quantity} WHERE `userid` = {$user}"); $db->query("UPDATE `users` SET `{$type}_currency` = 0 WHERE `{$type}_currency` < 0"); return true; } } } /* Tests to see what the user has equipped. @param int user = User ID to test against. @param int slot = Equipment slot to test. [Ex. Primary, Secondary, Armor] @param int itemid = Item to test for. -1 = Any Item, 0 = No Item Equipped, >0 = Specific item Returns true if user has item equipped Returns false if user does not have item equipped. */ function itemEquipped(int $user, string $slot, int $itemid = -1) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $slot = $db->escape(stripslashes(strtolower($slot))); if ($slot == 'primary' || $slot == 'secondary' || $slot == 'armor') { //Any item equipped if ($itemid == -1) { $equipped = $db->fetch_single($db->query("SELECT `equip_{$slot}` FROM `users` WHERE `userid` = {$user}")); if ($equipped > 0) { return true; } } //Specific item equipped elseif ($itemid > 0) { $itemid = (isset($itemid) && is_numeric($itemid)) ? abs(intval($itemid)) : 0; $equipped = $db->fetch_single($db->query("SELECT `equip_{$slot}` FROM `users` WHERE `userid` = {$user}")); if ($equipped == $itemid) { return true; } } //Nothing equipped elseif ($itemid == 0) { $equipped = $db->fetch_single($db->query("SELECT `equip_{$slot}` FROM `users` WHERE `userid` = {$user}")); if ($equipped == 0) { return true; } } } } /* Tests the inputted user to see if they're in the infirmary @param int user = User ID to test against. Returns true if user is in the infirmary Returns false if user is not in the infirmary */ function inInfirmary(int $user) { $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; return userInInfirmary($user); } /* Tests the inputted user to see if they're in the dungeon @param int user = User ID to test against. Returns true if user is in the dungeon. Returns false if user is not in the dungeon. */ function inDungeon(int $user) { $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; return userInDungeon($user); } /* Places or removes infirmary time on the specified user. @param int user = User ID to test against. @param int time = Minutes user is in infirmary @param text reason = Reason why user is in the infirmary Returns true if user is placed in the infirmary, or is removed from it. Returns false otherwise. */ function setInfirmary(int $user, int $time, string $reason) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $reason = $db->escape(stripslashes($reason)); if ($time >= 0) { $time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0; userPutInfirmary($user, $time, $reason); return true; } elseif ($time < 0) { $time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0; userRemoveInfirmary($user, $time); return true; } } /* Places or removes dungeon/infirmary time on the specified user. @param int user = User ID to test against. @param int time = Minutes user is in dungeon. @param text reason = Reason why user is in the dungeon. Returns true if user is placed in the dungeon, or is removed from it. Returns false otherwise. */ function setDungeon(int $user, int $time, string $reason) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $reason = $db->escape(stripslashes($reason)); if ($time >= 0) { $time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0; userPutDungeon($user, $time, $reason); return true; } elseif ($time < 0) { $time = (isset($time) && is_numeric($time)) ? abs(intval($time)) : 0; userRemoveDungeon($user, $time); return true; } } /* * Function to simulate a user training. * @param int userid = User ID of the player you wish to simulate. * @param text stat = Stat you wish for the user to train. * @param int times = How much you wish the user to train. * Returns stats gained. */ function train(int $userid, string $stat, int $times, int $multiplier = 1) { global $db; $userid = (isset($userid) && is_numeric($userid)) ? abs(intval($userid)) : 0; $stat = $db->escape(stripslashes(strtolower($stat))); $times = (isset($times) && is_numeric($times)) ? abs(intval($times)) : 0; $multiplier = (isset($multiplier) && is_numeric($multiplier)) ? abs(intval($multiplier)) : 1; //Return empty if the call isn't complete. if (empty($userid) || (empty($stat)) || (empty($times))) { return 0; } $StatArray = array("strength", "agility", "guard", "labor", "iq"); if (!in_array($stat, $StatArray)) { return -1; } $udq = $db->query("SELECT * FROM `users` WHERE `userid` = {$userid}"); $userdata = $db->fetch_row($udq); $gain = 0; //Do while value is less than the user's energy input, then add one to value. for ($i = 0; $i < $times; $i++) { //(1-4)/(600-1000)*(500-1000)*((User's Will+25)/175) $gain += randomNumber(1, 4) / randomNumber(600, 1000) * randomNumber(500, 1000) * (($userdata['will'] + 25) / 175); //Subtract a randomNumber number from user's will. $userdata['will'] -= randomNumber(1, 3); //User's will ends up negative, set to zero. if ($userdata['will'] < 0) { $userdata['will'] = 0; } } //Add multiplier, if needed. $gain *= $multiplier; //Round the gained stats. $gain = floor($gain); //Update the user's stats. $db->query("UPDATE `userstats` SET `{$stat}` = `{$stat}` + {$gain} WHERE `userid` = {$userid}"); //Update user's will and energy. $db->query("UPDATE `users` SET `will` = {$userdata['will']}, `energy` = `energy` - {$times} WHERE `userid` = {$userid}"); return $gain; } /* Get the user's member level. Can test for exact member level, or if user is above specified member level. @param int user = User to test on. @param text level = Member level to test for. [Valid: npc, member, web dev, forum moderator, assistant, admin] @param boolean exact = Return true if ranked ONLY specified level. [Default: false] Returns true if user is exactly or equal to/above specified member level. False if not. */ //This function needs refactored ASAP function getStaffLevel(int $user, string $level, bool $exact = false) { global $db; $level = $db->escape(stripslashes(strtolower($level))); $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; if ($user > 0) { $userexist = $db->query("SELECT `userid` FROM `users` WHERE `userid` = {$user}"); if ($db->num_rows($userexist) > 0) { $ulevel = $db->fetch_single($db->query("SELECT `user_level` FROM `users` WHERE `userid` = {$user}")); if ($exact == true) { if ($level == $ulevel) { return true; } } else { if ($level == 'member') { if ($ulevel == 'Member' || $ulevel == 'Forum Moderator' || $ulevel == 'Assistant' || $ulevel == 'Web Developer' || $ulevel == 'Admin' ) { return true; } } elseif ($level == 'forum moderator') { if ($ulevel == 'Forum Moderator' || $ulevel == 'Assistant' || $ulevel == 'Web Developer' || $ulevel == 'Admin') { return true; } } elseif ($level == 'assistant') { if ($ulevel == 'Assistant' || $ulevel == 'Web Developer' || $ulevel == 'Admin') { return true; } } elseif ($level == 'web dev') { if ($ulevel == 'Web Developer' || $ulevel == 'Admin') { return true; } } elseif ($level == 'npc') { if ($ulevel == 'Member' || $ulevel == 'NPC' || $ulevel == 'Forum Moderator' || $ulevel == 'Assistant' || $ulevel == 'Web Developer' || $ulevel == 'Admin' ) { return true; } } elseif ($level == 'admin') { if ($ulevel == 'Admin') { return true; } } } } } } /* Set the specified user's stat to a value. @param int user = User to test on. @param text stat = User's table row to return. @param int change = Numeric change (as a value) Returns the value in the stat specified. Throws E_ERROR if attempting to edit a sensitive field (Such as passwords) */ function setInfo(int $user, string $stat, int $change) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $stat = $db->escape(stripslashes(strtolower($stat))); $change = (isset($change) && is_numeric($change)) ? intval($change) : 0; if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes'))) { trigger_error("You do not have permission to set the {$stat} on this user.", E_ERROR); } else { $db->query("UPDATE users SET `{$stat}` = `{$stat}` + {$change} WHERE `userid` = {$user}"); $db->query("UPDATE users SET `{$stat}` = `max{$stat}` WHERE `{$stat}` > `max{$stat}`"); return true; } } /* Set the specified user's stat to a percent. @param int user = User to test on. @param text stat = User's table row to return. @param int change = Numeric change (as percent) Returns the value in the stat specified. Throws E_ERROR if attempting to edit a sensitive field (Such as passwords) */ function setInfoPercent(int $user, string $stat, int $change) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $stat = $db->escape(stripslashes(strtolower($stat))); $change = (isset($change) && is_numeric($change)) ? intval($change) : 0; if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes'))) { trigger_error("You do not have permission to set the {$stat} on this user.", E_ERROR); } else { $maxstat = $db->fetch_single($db->query("SELECT `max{$stat}` FROM `users` WHERE `userid` = {$user}")); $number = ($change / 100) * $maxstat; $db->query("UPDATE users SET `{$stat}`=`{$stat}`+{$number} WHERE `{$stat}` < `max{$stat}`"); $db->query("UPDATE users SET `{$stat}` = `max{$stat}` WHERE `{$stat}` > `max{$stat}`"); return true; } } /* Returns the specified user's stat @param int user = User to test on. @param text stat = User's table row to return. Returns the value in the stat specified. Throws E_ERROR if attempting to edit a sensitive field (Such as passwords) */ function getInfo(int $user, string $stat) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $stat = $db->escape(stripslashes(strtolower($stat))); if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes'))) { trigger_error("You do not have permission to get the {$stat} on this user.", E_ERROR); } else { return $db->fetch_single($db->query("SELECT `{$stat}` FROM `users` WHERE `userid` = {$user}")); } } /* Returns the specified user's stat as a percent @param int user = User to test on. @param text stat = User's table row to return. Returns the value in the stat specified. Throws E_ERROR if attempting to edit a sensitive field (Such as passwords) */ function getInfoPercent(int $user, string $stat) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $stat = $db->escape(stripslashes(strtolower($stat))); if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes'))) { trigger_error("You do not have permission to get the {$stat} on this user.", E_ERROR); } else { $min = $db->fetch_single($db->query("SELECT `{$stat}` FROM `users` WHERE `userid` = {$user}")); $max = $db->fetch_single($db->query("SELECT `max{$stat}` FROM `users` WHERE `userid` = {$user}")); return round($min / $max * 100); } } /* Function to set a user's info a static value. @param int user = User ID you wish to set a specific stat to. @param text stat = Stat to alter. @param int state = Value to set the stat to. Returns true if the stat was updated, false otherwise. Throws E_ERROR if attempting to edit a sensitive field (Such as passwords) */ function setInfoStatic(int $user, string $stat, int $state) { global $db, $api; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $stat = $db->escape(stripslashes(strtolower($stat))); if (in_array($stat, array('password', 'email', 'lastip', 'loginip', 'registerip', 'personal_notes', 'staff_notes'))) { trigger_error("You do not have permission to set the {$stat} on this user.", E_ERROR); } else { if (is_int($state)) { $state = (isset($state) && is_numeric($state)) ? abs(intval($state)) : 0; } else { $state = $db->escape(stripslashes($state)); } if ($user > 0) { if (!($api->user->getNamefromID($user) == false)) { $db->query("UPDATE `users` SET `{$stat}` = '{$state}' WHERE `userid` = '{$user}'"); return true; } } } } /* Adds a notification for the specified user. @param int user = User ID to send notification to. @param text text = Notification text. Returns true always. */ function addNotification(int $user, string $text) { addNotification($user, $text); return true; } /* Adds an in-game message for the player specified. @param int user = User ID message is sent to. @param text subj = Message subject. @param text msg = Message text. @param int from = User ID message is from.. Returns true when message is sent. False if message fails. */ function addMail(int $user, string $subj, string $msg, int $from) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $from = (isset($from) && is_numeric($from)) ? abs(intval($from)) : 0; $subj = $db->escape(stripslashes($subj)); $msg = $db->escape(stripslashes($msg)); $time = time(); $userexist = $db->query("SELECT `userid` FROM `users` WHERE `userid` = {$user}"); if ($db->num_rows($userexist) > 0) { $db->free_result($userexist); $userexist = $db->query("SELECT `userid` FROM `users` WHERE `userid` = {$from}"); if ($db->num_rows($userexist) > 0) { $db->query("INSERT INTO `mail` (`mail_to`, `mail_from`, `mail_status`, `mail_subject`, `mail_text`, `mail_time`) VALUES ('{$user}', '{$from}', 'unread', '{$subj}', '{$msg}', '{$time}');"); return true; } } } /* Returns the username of the user id specified. @param int user = User's name we're trying to fetch. On success, returns the user id's name, on failure, it returns false. */ function getNamefromID(int $user) { global $db; $user = (isset($user) && is_numeric($user)) ? abs(intval($user)) : 0; $name = $db->query("SELECT `username` FROM `users` WHERE `userid` = {$user}"); if ($db->num_rows($name) > 0) { $username = $db->fetch_single($name); return $username; } } /* Returns the userid of the username specified. @param string name = User's ID we're trying to fetch. On success, returns the user's id, on failure, it returns false. */ function getIDfromName(string $name) { global $db; $name = $db->escape(stripslashes($name)); $id = $db->query("SELECT `userid` FROM `users` WHERE `username` = '{$name}'"); if ($db->num_rows($id) > 0) { $usrid = $db->fetch_single($id); return $usrid; } } /* Function to test if the inputted users share IPs at all. @param int user1 = User ID of the first player. @param int user2 = User ID of the second player. Returns true if the users share an IP, false if not. Will also return false if both variables are equal. */ function checkIP(int $user1, int $user2) { global $db; $user1 = (isset($user1) && is_numeric($user1)) ? abs(intval($user1)) : 0; $user2 = (isset($user2) && is_numeric($user2)) ? abs(intval($user2)) : 0; if (!empty($user1) || !empty($user2)) { if ($user1 != $user2) { $s = $db->fetch_row($db->query("SELECT `lastip`,`loginip`,`registerip` FROM `users` WHERE `userid` = {$user1}")); $r = $db->fetch_row($db->query("SELECT `lastip`,`loginip`,`registerip` FROM `users` WHERE `userid` = {$user2}")); if ($s['lastip'] == $r['lastip'] || $s['loginip'] == $r['loginip'] || $s['registerip'] == $r['registerip']) { return true; } } } } }
package com.cinnamon.object; import com.cinnamon.system.ComponentFactory; import com.cinnamon.system.Config; import com.cinnamon.utils.Shape; /** * <p> * Provides {@link BodyComponent} lookup when computing physics updates. * </p> */ public abstract class BodyFactory extends ComponentFactory<BodyComponent, Object> { // Width to use when body's instantiated private static final float DEFAULT_WIDTH = 1f; // Height to use when body's instantiated private static final float DEFAULT_HEIGHT = 1f; /** * <p>Constructs a BodyFactory.</p> * * @param object resource for constructing {@link BodyComponent}s. * @param load initial BodyComponent capacity. * @param growth normalized capacity expansion. */ protected BodyFactory(Object object, int load, float growth) { super(object, load, growth); } /** * <p>Gets a {@link BodyComponent} of a specific mass.</p> * * @param mass in kilograms. * @return body. */ public final BodyComponent get(float mass) { final BodyComponent body = super.get(); // Set mass before being used body.setMass(mass); return body; } @Override public final BodyComponent get() { return super.get(); } @Override public final BodyComponent get(String configName) { return super.get(configName); } @Override public final BodyComponent get(int id, int version) { return super.get(id, version); } @Override public final BodyComponent get(int id) { return super.get(id); } @Override protected final BodyComponent createIdentifiable() { return new BodyComponent(new Shape(DEFAULT_WIDTH, DEFAULT_HEIGHT)); } @Override public final BodyComponent remove(int id, int version) { return super.remove(id, version); } @Override public final BodyComponent remove(int id) { return super.remove(id); } @Override public final Config<BodyComponent, Object> getConfig(String name) { return super.getConfig(name); } @Override public final Config<BodyComponent, Object> addConfig(String name, Config<BodyComponent, Object> config) { return super.addConfig(name, config); } @Override public final Config<BodyComponent, Object> removeConfig(String name) { return super.removeConfig(name); } }
[![Build Status](https://travis-ci.org/orizens/angular2-infinite-scroll.svg?branch=master)](https://travis-ci.org/orizens/angular2-infinite-scroll) # DEPRECATED - Please Use The New NGX-Infinite-Scroll [ngx-infinite-scroll](http://github.com/orizens/ngx-infinite-scroll) # Angular Infinite Scroll Inspired by [ng-infinite-scroll](https://github.com/sroze/ngInfiniteScroll) directive for angular (> 2). ## Angular Support Supports in Angular **> +2, 4** ## Angular Consulting Services I'm a Senior Javascript Engineer & A Front End Consultant at [Orizens](http://orizens.com). My services include: - consulting to companies and startups on how to approach code in their projects and keep it maintainable. - I provide project bootstrapping and development - while afterwards, I integrate it on site and guide the team on it. [Contact Me Here](http://orizens.com/contact) ## Installation ``` npm install angular2-infinite-scroll --save ``` ## Supported API Currently supported attributes: * **infiniteScrollDistance**<_number_> - (optional, default: **2**) - should get a number, the number of viewport lenghts from the bottom of the page at which the event will be triggered. * **infiniteScrollUpDistance**<_number_> - (optional, default: **1.5**) - should get a number * **infiniteScrollThrottle**<_number_> - (optional, default: **300**) - should get a number of **milliseconds** for throttle. The event will be triggered this many milliseconds after the user *stops* scrolling. * **infiniteScrollContainer**<_string|HTMLElement_> - (optional, default: null) - should get a html element or css selector for a scrollable element; window or current element will be used if this attribute is empty. * **scrolled**<_function_> - this will callback if the distance threshold has been reached on a scroll down. * **scrolledUp**<_function_> - (event: InfiniteScrollEvent) - this will callback if the distance threshold has been reached on a scroll up. * **scrollWindow**<_boolean_> - (optional, default: **true**) - listens to the window scroll instead of the actual element scroll. this allows to invoke a callback function in the scope of the element while listenning to the window scroll. * **immediateCheck**<_boolean_> - (optional, default: **false**) - invokes the handler immediately to check if a scroll event has been already triggred when the page has been loaded (i.e. - when you refresh a page that has been scrolled). * **infiniteScrollDisabled**<_boolean_> - (optional, default: **false**) - doesn't invoke the handler if set to true ## Behavior By default, the directive listens to the **window scroll** event and invoked the callback. **To trigger the callback when the actual element is scrolled**, these settings should be configured: * [scrollWindow]="false" * set an explict css "height" value to the element ## DEMO - [**Default Scroll** By Window - plunkr](https://plnkr.co/edit/DrEDetYnZkFxR7OWWrxS?p=preview) - [Scroll On a **"Modal"** - plunkr](https://plnkr.co/edit/QnQOwE9SEapwJCCFII3L?p=preview) ## Usage First, import the InfiniteScrollModule to your module: ```typescript import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { InfiniteScrollModule } from 'angular2-infinite-scroll'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppComponent } from './app'; @NgModule({ imports:[ BrowserModule, InfiniteScrollModule ], declarations: [ AppComponent, ], bootstrap: [ AppComponent ] }) export class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule); ``` In this example, the **onScroll** callback will be invoked when the window is scrolled down: ```typescript import { Component } from '@angular/core'; @Component({ selector: 'app', template: ` <div class="search-results" infinite-scroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="300" (scrolled)="onScroll()"> </div> ` }) export class AppComponent { onScroll () { console.log('scrolled!!') } } ``` in this example, whenever the "search-results" is scrolled, the callback will be invoked: ```typescript import { Component } from '@angular/core'; @Component({ selector: 'app', styles: [ `.search-results { height: 20rem; overflow: scroll; }` ], template: ` <div class="search-results" infinite-scroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="500" (scrolled)="onScroll()" [scrollWindow]="false"> </div> ` }) export class AppComponent { onScroll () { console.log('scrolled!!') } } ``` In this example, the **onScrollDown** callback will be invoked when the window is scrolled down and the **onScrollUp** callback will be invoked when the window is scrolled up: ```typescript import { Component } from '@angular/core'; import { InfiniteScroll } from 'angular2-infinite-scroll'; @Component({ selector: 'app', directives: [ InfiniteScroll ], template: ` <div class="search-results" infinite-scroll [infiniteScrollDistance]="2" [infiniteScrollUpDistance]="1.5" [infiniteScrollThrottle]="500" (scrolled)="onScrollDown()" (scrolledUp)="onScrollUp()"> </div> ` }) export class AppComponent { onScrollDown () { console.log('scrolled down!!') } onScrollUp () { console.log('scrolled up!!') } } ``` # Showcase Examples * [Echoes Player Ng2 Version](http://orizens.github.io/echoes-ng2) ([github repo for echoes player](http://github.com/orizens/echoes-ng2))
/** * Service layer beans. */ package es.cesga.hadoop.service;
var BasicMathLib = artifacts.require("./BasicMathLib.sol"); var Array256Lib = artifacts.require("./Array256Lib.sol"); var TokenLib = artifacts.require("./TokenLib.sol"); var CrowdsaleLib = artifacts.require("./CrowdsaleLib.sol"); var EvenDistroCrowdsaleLib = artifacts.require("./EvenDistroCrowdsaleLib.sol"); var CrowdsaleTestTokenEteenD = artifacts.require("./CrowdsaleTestTokenEteenD"); var EvenDistroTestEteenD = artifacts.require("./EvenDistroTestEteenD.sol"); var CrowdsaleTestTokenTenD = artifacts.require("./CrowdsaleTestTokenTenD"); var EvenDistroTestTenD = artifacts.require("./EvenDistroTestTenD.sol"); module.exports = function(deployer, network, accounts) { deployer.deploy(BasicMathLib,{overwrite: false}); deployer.deploy(Array256Lib, {overwrite: false}); deployer.link(BasicMathLib, TokenLib); deployer.deploy(TokenLib, {overwrite: false}); deployer.link(BasicMathLib,CrowdsaleLib); deployer.link(TokenLib,CrowdsaleLib); deployer.deploy(CrowdsaleLib, {overwrite: false}); deployer.link(BasicMathLib,EvenDistroCrowdsaleLib); deployer.link(TokenLib,EvenDistroCrowdsaleLib); deployer.link(CrowdsaleLib,EvenDistroCrowdsaleLib); deployer.deploy(EvenDistroCrowdsaleLib, {overwrite:false}); if(network === "development" || network === "coverage"){ deployer.link(TokenLib,CrowdsaleTestTokenEteenD); deployer.link(CrowdsaleLib,EvenDistroTestEteenD); deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestEteenD); deployer.link(TokenLib,CrowdsaleTestTokenTenD); deployer.link(CrowdsaleLib,EvenDistroTestTenD); deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestTenD); // startTime 3 days + 1 hour in the future var startTime = (Math.floor((new Date().valueOf()/1000))) + 262800; // first price step in 7 days var stepOne = startTime + 604800; // second price step in 14 days var stepTwo = stepOne + 604800; // endTime in 30 days var endTime = startTime + 2592000; deployer.deploy(CrowdsaleTestTokenEteenD, accounts[0], "Eighteen Decimals", "ETEEN", 18, 50000000000000000000000000, false, {from:accounts[5]}) .then(function() { var purchaseData =[startTime,600000000000000000000,100, stepOne,600000000000000000000,100, stepTwo,300000000000000000000,0]; return deployer.deploy(EvenDistroTestEteenD, accounts[5], purchaseData, endTime, 100, 10000000000000000000000, false, CrowdsaleTestTokenEteenD.address, {from:accounts[5]}) }) .then(function(){ return deployer.deploy(CrowdsaleTestTokenTenD, accounts[0], "Ten Decimals", "TEN", 10, 1000000000000000, false, {from:accounts[5]}) }) .then(function() { // start next sale in 7 days startTime = endTime + 604800; stepOne = startTime + 604800; stepTwo = stepOne + 604800; endTime = startTime + 2592000; purchaseData =[startTime,4000000000000,0, stepOne,8000000000000,20000000000000, stepTwo,16000000000000,0]; return deployer.deploy(EvenDistroTestTenD, accounts[0], purchaseData, endTime, 25, 0, true, CrowdsaleTestTokenTenD.address, {from:accounts[5]}) }); } };
// // Adapted from: // http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle // var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var bust = require('gulp-buster'); var streamify = require('gulp-streamify'); var htmlreplace = require('gulp-html-replace'); var fs = require('fs'); var packageJson = require('./package.json'); var dependencies = Object.keys(packageJson && packageJson.dependencies || {}); function handleErrors(error) { console.error(error.stack); // Emit 'end' as the stream wouldn't do it itself. // Without this, the gulp task won't end and the watch stops working. this.emit('end'); } gulp.task('libs', function () { return browserify({debug: true}) .require(dependencies) .bundle() .on('error', handleErrors) .pipe(source('libs.js')) .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('scripts', function () { return browserify('./src/index.js', {debug: true}) .external(dependencies) .bundle() .on('error', handleErrors) .on('end', ()=>{console.log("ended")}) .pipe(source('scripts.js')) .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('css', function () { return gulp.src('./styles/styles.css') .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('icons', function () { return gulp.src('./icons/**/*') .pipe(gulp.dest('./dist/icons')); }); gulp.task('favicons', function () { return gulp.src('./favicons/**/*') .pipe(gulp.dest('./dist/')); }); gulp.task('html', function () { var busters = JSON.parse(fs.readFileSync('busters.json')); return gulp.src('index.html') .pipe(htmlreplace({ 'css': 'styles.css?v=' + busters['dist/styles.css'], 'js': [ 'libs.js?v=' + busters['dist/libs.js'], 'scripts.js?v=' + busters['dist/scripts.js'] ] })) .pipe(gulp.dest('./dist/')); }); gulp.task('watch', function(){ gulp.watch('package.json', ['libs']); gulp.watch('src/**', ['scripts']); gulp.watch('styles/styles.css', ['css']); gulp.watch('icons/**', ['icons']); gulp.watch('favicons/**', ['favicons']); gulp.watch(['busters.json', 'index.html'], ['html']); }); gulp.task('default', ['libs', 'scripts', 'css', 'icons', 'favicons', 'html', 'watch']);
module Main where import Lib import Text.Printf import Data.Time.Clock.POSIX n = 4::Int main :: IO () main = do startTime <- getPOSIXTime printf "Maximum product of %d values taken in a straight line from array 'values':\n\t%d" n $ maxStraightProduct n stopTime <- getPOSIXTime printf "\t(%s sec)\n" $ show (stopTime - startTime)
#include "spritesheet.hpp" ////////// // Code // // Initializing the SpriteSheet sizes. void SpriteSheet::init(int cols, int rows, int width, int height) { this->cols = cols; this->rows = rows; this->width = width; this->height = height; } // Making a SpriteSheet from an existing SDL_Texture. SpriteSheet::SpriteSheet(SDL_Texture* tex, int cols , int rows, int width, int height) throw(HCException) { this->sprite = new Sprite(tex); init(cols, rows, width, height); } // Making a SpriteSheet from an SDL_Surface. SpriteSheet::SpriteSheet(SDL_Renderer* renderer, SDL_Surface* surf, int cols , int rows, int width, int height) throw(HCException) { this->sprite = new Sprite(renderer, surf); init(cols, rows, width, height); } // Loading a SpriteSheet from a location on the disk. SpriteSheet::SpriteSheet(SDL_Renderer* renderer, std::string path, int cols , int rows, int width, int height) throw(HCException) { this->sprite = new Sprite(renderer, path); init(cols, rows, width, height); } // The copy constructor. SpriteSheet::SpriteSheet(const SpriteSheet& ss) { this->sprite = ss.sprite; init(ss.rows, ss.cols, ss.width, ss.height); this->original = false; } // Destroying the SpriteSheet. SpriteSheet::~SpriteSheet() { if (this->original) delete this->sprite; } // Blitting a specific tile. void SpriteSheet::blit(Window& w, Rectangle dst, int x, int y) const { Rectangle r(x * this->width, y * this->height, this->width, this->height); this->sprite->blit(w, dst, r); } // Accessors int SpriteSheet::getCols() const { return this->cols; } int SpriteSheet::getRows() const { return this->rows; }
BrowserPolicy.content.allowOriginForAll("*.googleapis.com"); BrowserPolicy.content.allowOriginForAll("*.gstatic.com"); BrowserPolicy.content.allowOriginForAll("*.bootstrapcdn.com"); BrowserPolicy.content.allowOriginForAll("*.geobytes.com"); BrowserPolicy.content.allowFontDataUrl();
package blogr.vpm.fr.blogr.activity; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; import blogr.vpm.fr.blogr.R; import blogr.vpm.fr.blogr.format.AlignCenterTagsProvider; import blogr.vpm.fr.blogr.format.AlignLeftTagsProvider; import blogr.vpm.fr.blogr.format.AlignRightTagsProvider; import blogr.vpm.fr.blogr.insertion.Inserter; import blogr.vpm.fr.blogr.insertion.WikipediaLinkTagsProvider; /** * Created by vince on 11/05/15. */ public class PostContentEditionActions implements ActionMode.Callback { private final Inserter inserter; private final EditText editText; public PostContentEditionActions(Inserter inserter, EditText editText) { this.inserter = inserter; this.editText = editText; } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { MenuInflater inflater = actionMode.getMenuInflater(); inflater.inflate(R.menu.postcontentedition, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.action_wiki_link: if (editText.getSelectionStart() < editText.getSelectionEnd()) { String articleName = editText.getText().toString().substring(editText.getSelectionStart(), editText.getSelectionEnd()); inserter.insert(editText, new WikipediaLinkTagsProvider(articleName)); } return true; case R.id.action_align_left: inserter.insert(editText, new AlignLeftTagsProvider()); return true; case R.id.action_align_center: inserter.insert(editText, new AlignCenterTagsProvider()); return true; case R.id.action_align_right: inserter.insert(editText, new AlignRightTagsProvider()); return true; } return false; } @Override public void onDestroyActionMode(ActionMode actionMode) { } }
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> <meta charset="utf-8"> <title>Tag Index &#8211; Site Title</title> <meta name="description" content="An archive of posts sorted by tag."> <!-- Twitter Cards --> <meta name="twitter:title" content="Tag Index"> <meta name="twitter:description" content="An archive of posts sorted by tag."> <meta name="twitter:card" content="summary"> <meta name="twitter:image" content="/images/site-logo.png"> <!-- Open Graph --> <meta property="og:locale" content="en_US"> <meta property="og:type" content="article"> <meta property="og:title" content="Tag Index"> <meta property="og:description" content="An archive of posts sorted by tag."> <meta property="og:url" content="/tags/"> <meta property="og:site_name" content="Site Title"> <link rel="canonical" href="/tags/"> <link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Site Title Feed"> <!-- http://t.co/dKP3o1e --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- For all browsers --> <link rel="stylesheet" href="/assets/css/main.css"> <!-- Webfonts --> <script src="//use.edgefonts.net/source-sans-pro:n2,i2,n3,i3,n4,i4,n6,i6,n7,i7,n9,i9;source-code-pro:n4,n7;volkhov.js"></script> <meta http-equiv="cleartype" content="on"> <!-- HTML5 Shiv and Media Query Support --> <!--[if lt IE 9]> <script src="/assets/js/vendor/html5shiv.min.js"></script> <script src="/assets/js/vendor/respond.min.js"></script> <![endif]--> <!-- Modernizr --> <script src="/assets/js/vendor/modernizr-2.7.1.custom.min.js"></script> <!-- Icons --> <!-- 16x16 --> <link rel="shortcut icon" href="/favicon.ico"> <!-- 32x32 --> <link rel="shortcut icon" href="/favicon.png"> <!-- 57x57 (precomposed) for iPhone 3GS, pre-2011 iPod Touch and older Android devices --> <link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png"> <!-- 72x72 (precomposed) for 1st generation iPad, iPad 2 and iPad mini --> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png"> <!-- 114x114 (precomposed) for iPhone 4, 4S, 5 and post-2011 iPod Touch --> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png"> <!-- 144x144 (precomposed) for iPad 3rd and 4th generation --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png"> <script type="text/javascript" src="//static.qmerce.com/js/sdk/dev/apester-sdk.min.js"></script> </head> <body id="page"> <div class="navigation-wrapper"> <nav role="navigation" id="site-nav" class="animated drop"> <ul> <li><a href="/about/" >About</a></li> <li><a href="/articles/" >Articles</a></li> <li><a href="/blog/" >Blog</a></li> <li><a href="/theme-setup/" >Theme Setup</a></li> <li><a href="http://mademistakes.com" target="_blank">Made Mistakes</a></li> <li><a href="/search/" >Search</a></li> </ul> </nav> </div><!-- /.navigation-wrapper --> <!--[if lt IE 9]><div class="upgrade"><strong><a href="http://whatbrowser.org/">Your browser is quite old!</strong> Why not upgrade to a different browser to better enjoy this site?</a></div><![endif]--> <header class="masthead"> <div class="wrap"> <a href="/" class="site-logo" rel="home" title="Site Title"><img src="/images/site-logo.png" width="200" height="200" alt="Site Title logo" class="animated fadeInUp"></a> <h1 class="site-title animated fadeIn"><a href="/">Site Title</a></h1> <h2 class="site-description animated fadeIn" itemprop="description">Describe your website here.</h2> </div> </header><!-- /.masthead --> <div class="js-menu-screen menu-screen"></div> <div id="main" role="main"> <article class="entry"> <div class="entry-wrapper"> <header class="entry-header"> <h1 class="entry-title">Tag Index</h1> </header> <div class="entry-content"> New Editor: poll: 558833e217ada36c533168ed quiz: 559250bb9903ebaf49603b04 personality test: 5595463a9d29d99c594260e1 Old Editor: poll: 55895a3717ada36c53377bbd quiz: 55925284ab9dc6b4493e7c1d personality test: 559253b7ab9dc6b4493e7d71 video: 5525383a59081084b94845bf <ul class="tag-box inline"> <li><a href="#code">code <span>1</span></a></li> <li><a href="#highlighting">highlighting <span>1</span></a></li> <li><a href="#images">images <span>1</span></a></li> <li><a href="#intro">intro <span>1</span></a></li> <li><a href="#link-post">link-post <span>1</span></a></li> <li><a href="#readability">readability <span>3</span></a></li> <li><a href="#sample-post">sample-post <span>8</span></a></li> <li><a href="#test">test <span>3</span></a></li> <li><a href="#video">video <span>1</span></a></li> </ul> <h2 id="code">code</h2> <ul class="post-list"> <li><a href="/articles/code-highlighting-post/">Syntax Highlighting Post<span class="entry-date"><time datetime="2013-08-16T00:00:00+00:00">August 16, 2013</time></span></a></li> </ul> <h2 id="highlighting">highlighting</h2> <ul class="post-list"> <li><a href="/articles/code-highlighting-post/">Syntax Highlighting Post<span class="entry-date"><time datetime="2013-08-16T00:00:00+00:00">August 16, 2013</time></span></a></li> </ul> <h2 id="images">images</h2> <ul class="post-list"> <li><a href="/articles/sample-post-images/">A Post with Images<span class="entry-date"><time datetime="2013-05-22T00:00:00+00:00">May 22, 2013</time></span></a></li> </ul> <h2 id="intro">intro</h2> <ul class="post-list"> <li><a href="/articles/readability-post/">Testing Readability with a Bunch of Text<span class="entry-date"><time datetime="2012-05-22T00:00:00+00:00">May 22, 2012</time></span></a></li> </ul> <h2 id="link-post">link-post</h2> <ul class="post-list"> <li><a href="/articles/sample-link-post/">Sample Link Post<span class="entry-date"><time datetime="2013-08-12T00:00:00+00:00">August 12, 2013</time></span></a></li> </ul> <h2 id="readability">readability</h2> <ul class="post-list"> <li><a href="/articles/author-override/">Override Author Byline Test Post<span class="entry-date"><time datetime="2014-06-19T00:00:00+00:00">June 19, 2014</time></span></a></li> <li><a href="/articles/readability-feature-post/">Post with Large Feature Image and Text<span class="entry-date"><time datetime="2013-05-23T00:00:00+00:00">May 23, 2013</time></span></a></li> <li><a href="/articles/readability-post/">Testing Readability with a Bunch of Text<span class="entry-date"><time datetime="2012-05-22T00:00:00+00:00">May 22, 2012</time></span></a></li> </ul> <h2 id="sample-post">sample-post</h2> <ul class="post-list"> <li><a href="/articles/author-override/">Override Author Byline Test Post<span class="entry-date"><time datetime="2014-06-19T00:00:00+00:00">June 19, 2014</time></span></a></li> <li><a href="/articles/code-highlighting-post/">Syntax Highlighting Post<span class="entry-date"><time datetime="2013-08-16T00:00:00+00:00">August 16, 2013</time></span></a></li> <li><a href="/articles/sample-link-post/">Sample Link Post<span class="entry-date"><time datetime="2013-08-12T00:00:00+00:00">August 12, 2013</time></span></a></li> <li><a href="/articles/video-post/">A Post with a Video<span class="entry-date"><time datetime="2013-06-25T00:00:00+00:00">June 25, 2013</time></span></a></li> <li><a href="/articles/readability-feature-post/">Post with Large Feature Image and Text<span class="entry-date"><time datetime="2013-05-23T00:00:00+00:00">May 23, 2013</time></span></a></li> <li><a href="/articles/sample-post-images/">A Post with Images<span class="entry-date"><time datetime="2013-05-22T00:00:00+00:00">May 22, 2013</time></span></a></li> <li><a href="/articles/readability-post/">Testing Readability with a Bunch of Text<span class="entry-date"><time datetime="2012-05-22T00:00:00+00:00">May 22, 2012</time></span></a></li> <li><a href="/articles/sample-post/">Sample Post<span class="entry-date"><time datetime="2011-03-10T00:00:00+00:00">March 10, 2011</time></span></a></li> </ul> <h2 id="test">test</h2> <ul class="post-list"> <li><a href="/articles/author-override/">Override Author Byline Test Post<span class="entry-date"><time datetime="2014-06-19T00:00:00+00:00">June 19, 2014</time></span></a></li> <li><a href="/articles/sample-post-images/">A Post with Images<span class="entry-date"><time datetime="2013-05-22T00:00:00+00:00">May 22, 2013</time></span></a></li> <li><a href="/articles/readability-post/">Testing Readability with a Bunch of Text<span class="entry-date"><time datetime="2012-05-22T00:00:00+00:00">May 22, 2012</time></span></a></li> </ul> <h2 id="video">video</h2> <ul class="post-list"> <li><a href="/articles/video-post/">A Post with a Video<span class="entry-date"><time datetime="2013-06-25T00:00:00+00:00">June 25, 2013</time></span></a></li> </ul> </div><!-- /.entry-content --> </div><!-- /.entry-wrapper --> </article> </div><!-- /#main --> <div class="footer-wrapper"> <footer role="contentinfo" class="entry-wrapper"> <span>&copy; 2015 Your Name. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> using the <a href="http://mademistakes.com/so-simple/" rel="nofollow">So Simple Theme</a>.</span> <div class="social-icons"> <a href="/feed.xml" title="Atom/RSS feed"><i class="fa fa-rss-square fa-2x"></i></a> </div><!-- /.social-icons --> </footer> </div><!-- /.footer-wrapper --> <script type="text/javascript"> var BASE_URL = ''; </script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="/assets/js/vendor/jquery-1.9.1.min.js"><\/script>')</script> <script src="/assets/js/scripts.min.js"></script> </body> </html>
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::DataFactory::Mgmt::V2017_09_01_preview module Models # # HBase server linked service. # class HBaseLinkedService < LinkedService include MsRestAzure def initialize @type = "HBase" end attr_accessor :type # @return The IP address or host name of the HBase server. (i.e. # 192.168.222.160) attr_accessor :host # @return The TCP port that the HBase instance uses to listen for client # connections. The default value is 9090. attr_accessor :port # @return The partial URL corresponding to the HBase server. (i.e. # /gateway/sandbox/hbase/version) attr_accessor :http_path # @return [HBaseAuthenticationType] The authentication mechanism to use # to connect to the HBase server. Possible values include: 'Anonymous', # 'Basic' attr_accessor :authentication_type # @return The user name used to connect to the HBase instance. attr_accessor :username # @return [SecretBase] The password corresponding to the user name. attr_accessor :password # @return Specifies whether the connections to the server are encrypted # using SSL. The default value is false. attr_accessor :enable_ssl # @return The full path of the .pem file containing trusted CA # certificates for verifying the server when connecting over SSL. This # property can only be set when using SSL on self-hosted IR. The default # value is the cacerts.pem file installed with the IR. attr_accessor :trusted_cert_path # @return Specifies whether to require a CA-issued SSL certificate name # to match the host name of the server when connecting over SSL. The # default value is false. attr_accessor :allow_host_name_cnmismatch # @return Specifies whether to allow self-signed certificates from the # server. The default value is false. attr_accessor :allow_self_signed_server_cert # @return The encrypted credential used for authentication. Credentials # are encrypted using the integration runtime credential manager. Type: # string (or Expression with resultType string). attr_accessor :encrypted_credential # # Mapper for HBaseLinkedService class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'HBase', type: { name: 'Composite', class_name: 'HBaseLinkedService', model_properties: { additional_properties: { client_side_validation: true, required: false, type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'ObjectElementType', type: { name: 'Object' } } } }, connect_via: { client_side_validation: true, required: false, serialized_name: 'connectVia', type: { name: 'Composite', class_name: 'IntegrationRuntimeReference' } }, description: { client_side_validation: true, required: false, serialized_name: 'description', type: { name: 'String' } }, parameters: { client_side_validation: true, required: false, serialized_name: 'parameters', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'ParameterSpecificationElementType', type: { name: 'Composite', class_name: 'ParameterSpecification' } } } }, annotations: { client_side_validation: true, required: false, serialized_name: 'annotations', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ObjectElementType', type: { name: 'Object' } } } }, type: { client_side_validation: true, required: true, serialized_name: 'type', type: { name: 'String' } }, host: { client_side_validation: true, required: true, serialized_name: 'typeProperties.host', type: { name: 'Object' } }, port: { client_side_validation: true, required: false, serialized_name: 'typeProperties.port', type: { name: 'Object' } }, http_path: { client_side_validation: true, required: false, serialized_name: 'typeProperties.httpPath', type: { name: 'Object' } }, authentication_type: { client_side_validation: true, required: true, serialized_name: 'typeProperties.authenticationType', type: { name: 'String' } }, username: { client_side_validation: true, required: false, serialized_name: 'typeProperties.username', type: { name: 'Object' } }, password: { client_side_validation: true, required: false, serialized_name: 'typeProperties.password', type: { name: 'Composite', polymorphic_discriminator: 'type', uber_parent: 'SecretBase', class_name: 'SecretBase' } }, enable_ssl: { client_side_validation: true, required: false, serialized_name: 'typeProperties.enableSsl', type: { name: 'Object' } }, trusted_cert_path: { client_side_validation: true, required: false, serialized_name: 'typeProperties.trustedCertPath', type: { name: 'Object' } }, allow_host_name_cnmismatch: { client_side_validation: true, required: false, serialized_name: 'typeProperties.allowHostNameCNMismatch', type: { name: 'Object' } }, allow_self_signed_server_cert: { client_side_validation: true, required: false, serialized_name: 'typeProperties.allowSelfSignedServerCert', type: { name: 'Object' } }, encrypted_credential: { client_side_validation: true, required: false, serialized_name: 'typeProperties.encryptedCredential', type: { name: 'Object' } } } } } end end end end
# `Erichika` The game for developers. ## Koding Global Hackathon This is a project for Koding Global Hackthon. The submit page is here: https://github.com/team-kke/hackathon.submit ## License The MIT License (MIT) Copyright (c) 2014 [Team KKE](https://github.com/team-kke)
# CallingApp --- A [KBase](https://kbase.us) module generated by the [KBase SDK](https://github.com/kbase/kb_sdk).
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @protocol WCCardPkgBackTableViewDelegate <NSObject> - (void)WXCardPkgTableViewHeight:(double)arg1 scrollEnabled:(_Bool)arg2; - (double)WXCardPkgTableViewMaxHeight; @end
module ResourceAuthentication module TestCase class MockRequest # :nodoc: attr_accessor :controller def initialize(controller) self.controller = controller end def remote_ip (controller && controller.respond_to?(:env) && controller.env.is_a?(Hash) && controller.env['REMOTE_ADDR']) || "1.1.1.1" end private def method_missiing(*args, &block) end end end end
<?php /* Template Name: WP Riddle Single Page */ ?> <!DOCTYPE html> <!--[if IE 7]> <html class="ie ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="ie ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 7) | !(IE 8) ]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width"> <title><?php echo esc_attr(get_option('index_page_title')); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="stylesheet" href="<?php echo get_bloginfo('url') . '/wp-includes/css/buttons.min.css'; ?>"> <link rel="stylesheet" href="<?php echo get_bloginfo('url') . '/wp-admin/css/login.min.css'; ?>"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__);?>../css/single.css"> <link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__);?>../css/index.css"> <link rel='stylesheet' id='open-sans-css' href='//fonts.useso.com/css?family=Open+Sans%3A300italic%2C400italic%2C600italic%2C300%2C400%2C600&#038;subset=latin%2Clatin-ext&#038;ver=4.0' type='text/css' media='all' /> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script> <![endif]--> </head> <body class="login login-action-login wp-core-ui"> <ul id="pjax_nav"> <li class="left"><a href="<?php echo home_url(); ?>/" class="pjax"><?php echo esc_attr(get_option('index_page_heading')); ?></a></li> <li class="right"><a href="<?php echo wp_logout_url(); ?>">Logout</a></li> <li class="right"><?php global $current_user; get_currentuserinfo(); if (current_user_can("administrator")) echo "<a href='wp-admin/'>" . $current_user->user_login . "</a>"; else echo "<span id='username'>" . $current_user->user_login . "</span>"; ?></li> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'pjax' ) ); ?> </ul> <div id="pjax_layer" class="fade-out"></div> <div class="pjax_content"> <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> <a href="<?php echo home_url(); ?>/" class="pjax">Back</a> <?php /* The loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <form id="loginform" name="keyform" method="post" action="<?php echo admin_url();?>admin-post.php"> <p> <label for="key"><?php echo esc_attr(get_option('index_page_key_input')); ?><br/> <input type="text" name="wpr_key" id="key" class="input" value="" placeholder="<?php echo get_option('index_page_input_placeholder'); ?>" autocomplete="off" /></label> </p> <p class="submit"> <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Submit" /> <input type="hidden" name="action" value="submit_key" /> </p> </form> </div><!-- #content --> <p id="nav"><?php echo esc_attr(get_option('single_page_footer')); ?></p> </div><!-- #primary --> </div> <script src="<?php echo plugin_dir_url(__FILE__);?>../js/push_state.js"></script> </body> </html>
/* * Copyright 2015 Freescale Semiconductor * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __LS1043ARDB_H__ #define __LS1043ARDB_H__ #include "ls1043a_common.h" #define CONFIG_SYS_CLK_FREQ 100000000 #define CONFIG_DDR_CLK_FREQ 100000000 #define CONFIG_LAYERSCAPE_NS_ACCESS #define CONFIG_MISC_INIT_R #define CONFIG_DIMM_SLOTS_PER_CTLR 1 /* Physical Memory Map */ #define CONFIG_CHIP_SELECTS_PER_CTRL 4 #define CONFIG_NR_DRAM_BANKS 2 #define CONFIG_SYS_SPD_BUS_NUM 0 #ifndef CONFIG_SPL #define CONFIG_SYS_DDR_RAW_TIMING #define CONFIG_FSL_DDR_INTERACTIVE /* Interactive debugging */ #define CONFIG_FSL_DDR_BIST #define CONFIG_ECC_INIT_VIA_DDRCONTROLLER #define CONFIG_MEM_INIT_VALUE 0xdeadbeef #endif #ifdef CONFIG_RAMBOOT_PBL #define CONFIG_SYS_FSL_PBL_PBI board/freescale/ls1043ardb/ls1043ardb_pbi.cfg #endif #ifdef CONFIG_NAND_BOOT #define CONFIG_SYS_FSL_PBL_RCW board/freescale/ls1043ardb/ls1043ardb_rcw_nand.cfg #endif #ifdef CONFIG_SD_BOOT #define CONFIG_SYS_FSL_PBL_RCW board/freescale/ls1043ardb/ls1043ardb_rcw_sd.cfg #define CONFIG_CMD_SPL #define CONFIG_SYS_SPL_ARGS_ADDR 0x90000000 #define CONFIG_SYS_MMCSD_RAW_MODE_KERNEL_SECTOR 0x10000 #define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTOR 0x500 #define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTORS 30 #endif /* * NOR Flash Definitions */ #define CONFIG_SYS_NOR_CSPR_EXT (0x0) #define CONFIG_SYS_NOR_AMASK IFC_AMASK(128*1024*1024) #define CONFIG_SYS_NOR_CSPR \ (CSPR_PHYS_ADDR(CONFIG_SYS_FLASH_BASE_PHYS) | \ CSPR_PORT_SIZE_16 | \ CSPR_MSEL_NOR | \ CSPR_V) /* NOR Flash Timing Params */ #define CONFIG_SYS_NOR_CSOR (CSOR_NOR_ADM_SHIFT(4) | \ CSOR_NOR_TRHZ_80) #define CONFIG_SYS_NOR_FTIM0 (FTIM0_NOR_TACSE(0x1) | \ FTIM0_NOR_TEADC(0x1) | \ FTIM0_NOR_TAVDS(0x0) | \ FTIM0_NOR_TEAHC(0xc)) #define CONFIG_SYS_NOR_FTIM1 (FTIM1_NOR_TACO(0x1c) | \ FTIM1_NOR_TRAD_NOR(0xb) | \ FTIM1_NOR_TSEQRAD_NOR(0x9)) #define CONFIG_SYS_NOR_FTIM2 (FTIM2_NOR_TCS(0x1) | \ FTIM2_NOR_TCH(0x4) | \ FTIM2_NOR_TWPH(0x8) | \ FTIM2_NOR_TWP(0x10)) #define CONFIG_SYS_NOR_FTIM3 0 #define CONFIG_SYS_IFC_CCR 0x01000000 #define CONFIG_SYS_MAX_FLASH_BANKS 1 /* number of banks */ #define CONFIG_SYS_MAX_FLASH_SECT 1024 /* sectors per device */ #define CONFIG_SYS_FLASH_ERASE_TOUT 60000 /* Flash Erase Timeout (ms) */ #define CONFIG_SYS_FLASH_WRITE_TOUT 500 /* Flash Write Timeout (ms) */ #define CONFIG_SYS_FLASH_EMPTY_INFO #define CONFIG_SYS_FLASH_BANKS_LIST { CONFIG_SYS_FLASH_BASE_PHYS } #define CONFIG_CFI_FLASH_USE_WEAK_ACCESSORS #define CONFIG_SYS_WRITE_SWAPPED_DATA /* * NAND Flash Definitions */ #ifndef SPL_NO_IFC #define CONFIG_NAND_FSL_IFC #endif #define CONFIG_SYS_NAND_BASE 0x7e800000 #define CONFIG_SYS_NAND_BASE_PHYS CONFIG_SYS_NAND_BASE #define CONFIG_SYS_NAND_CSPR_EXT (0x0) #define CONFIG_SYS_NAND_CSPR (CSPR_PHYS_ADDR(CONFIG_SYS_NAND_BASE_PHYS) \ | CSPR_PORT_SIZE_8 \ | CSPR_MSEL_NAND \ | CSPR_V) #define CONFIG_SYS_NAND_AMASK IFC_AMASK(64*1024) #define CONFIG_SYS_NAND_CSOR (CSOR_NAND_ECC_ENC_EN /* ECC on encode */ \ | CSOR_NAND_ECC_DEC_EN /* ECC on decode */ \ | CSOR_NAND_ECC_MODE_4 /* 4-bit ECC */ \ | CSOR_NAND_RAL_3 /* RAL = 3 Bytes */ \ | CSOR_NAND_PGS_2K /* Page Size = 2K */ \ | CSOR_NAND_SPRZ_64 /* Spare size = 64 */ \ | CSOR_NAND_PB(64)) /* 64 Pages Per Block */ #define CONFIG_SYS_NAND_ONFI_DETECTION #define CONFIG_SYS_NAND_FTIM0 (FTIM0_NAND_TCCST(0x7) | \ FTIM0_NAND_TWP(0x18) | \ FTIM0_NAND_TWCHT(0x7) | \ FTIM0_NAND_TWH(0xa)) #define CONFIG_SYS_NAND_FTIM1 (FTIM1_NAND_TADLE(0x32) | \ FTIM1_NAND_TWBE(0x39) | \ FTIM1_NAND_TRR(0xe) | \ FTIM1_NAND_TRP(0x18)) #define CONFIG_SYS_NAND_FTIM2 (FTIM2_NAND_TRAD(0xf) | \ FTIM2_NAND_TREH(0xa) | \ FTIM2_NAND_TWHRE(0x1e)) #define CONFIG_SYS_NAND_FTIM3 0x0 #define CONFIG_SYS_NAND_BASE_LIST { CONFIG_SYS_NAND_BASE } #define CONFIG_SYS_MAX_NAND_DEVICE 1 #define CONFIG_MTD_NAND_VERIFY_WRITE #define CONFIG_SYS_NAND_BLOCK_SIZE (128 * 1024) #ifdef CONFIG_NAND_BOOT #define CONFIG_SPL_PAD_TO 0x20000 /* block aligned */ #define CONFIG_SYS_NAND_U_BOOT_OFFS CONFIG_SPL_PAD_TO #define CONFIG_SYS_NAND_U_BOOT_SIZE (1024 << 10) #endif /* * CPLD */ #define CONFIG_SYS_CPLD_BASE 0x7fb00000 #define CPLD_BASE_PHYS CONFIG_SYS_CPLD_BASE #define CONFIG_SYS_CPLD_CSPR_EXT (0x0) #define CONFIG_SYS_CPLD_CSPR (CSPR_PHYS_ADDR(CPLD_BASE_PHYS) | \ CSPR_PORT_SIZE_8 | \ CSPR_MSEL_GPCM | \ CSPR_V) #define CONFIG_SYS_CPLD_AMASK IFC_AMASK(64 * 1024) #define CONFIG_SYS_CPLD_CSOR (CSOR_NOR_ADM_SHIFT(4) | \ CSOR_NOR_NOR_MODE_AVD_NOR | \ CSOR_NOR_TRHZ_80) /* CPLD Timing parameters for IFC GPCM */ #define CONFIG_SYS_CPLD_FTIM0 (FTIM0_GPCM_TACSE(0xf) | \ FTIM0_GPCM_TEADC(0xf) | \ FTIM0_GPCM_TEAHC(0xf)) #define CONFIG_SYS_CPLD_FTIM1 (FTIM1_GPCM_TACO(0xff) | \ FTIM1_GPCM_TRAD(0x3f)) #define CONFIG_SYS_CPLD_FTIM2 (FTIM2_GPCM_TCS(0xf) | \ FTIM2_GPCM_TCH(0xf) | \ FTIM2_GPCM_TWP(0xff)) #define CONFIG_SYS_CPLD_FTIM3 0x0 /* IFC Timing Params */ #ifdef CONFIG_NAND_BOOT #define CONFIG_SYS_CSPR0_EXT CONFIG_SYS_NAND_CSPR_EXT #define CONFIG_SYS_CSPR0 CONFIG_SYS_NAND_CSPR #define CONFIG_SYS_AMASK0 CONFIG_SYS_NAND_AMASK #define CONFIG_SYS_CSOR0 CONFIG_SYS_NAND_CSOR #define CONFIG_SYS_CS0_FTIM0 CONFIG_SYS_NAND_FTIM0 #define CONFIG_SYS_CS0_FTIM1 CONFIG_SYS_NAND_FTIM1 #define CONFIG_SYS_CS0_FTIM2 CONFIG_SYS_NAND_FTIM2 #define CONFIG_SYS_CS0_FTIM3 CONFIG_SYS_NAND_FTIM3 #define CONFIG_SYS_CSPR1_EXT CONFIG_SYS_NOR_CSPR_EXT #define CONFIG_SYS_CSPR1 CONFIG_SYS_NOR_CSPR #define CONFIG_SYS_AMASK1 CONFIG_SYS_NOR_AMASK #define CONFIG_SYS_CSOR1 CONFIG_SYS_NOR_CSOR #define CONFIG_SYS_CS1_FTIM0 CONFIG_SYS_NOR_FTIM0 #define CONFIG_SYS_CS1_FTIM1 CONFIG_SYS_NOR_FTIM1 #define CONFIG_SYS_CS1_FTIM2 CONFIG_SYS_NOR_FTIM2 #define CONFIG_SYS_CS1_FTIM3 CONFIG_SYS_NOR_FTIM3 #else #define CONFIG_SYS_CSPR0_EXT CONFIG_SYS_NOR_CSPR_EXT #define CONFIG_SYS_CSPR0 CONFIG_SYS_NOR_CSPR #define CONFIG_SYS_AMASK0 CONFIG_SYS_NOR_AMASK #define CONFIG_SYS_CSOR0 CONFIG_SYS_NOR_CSOR #define CONFIG_SYS_CS0_FTIM0 CONFIG_SYS_NOR_FTIM0 #define CONFIG_SYS_CS0_FTIM1 CONFIG_SYS_NOR_FTIM1 #define CONFIG_SYS_CS0_FTIM2 CONFIG_SYS_NOR_FTIM2 #define CONFIG_SYS_CS0_FTIM3 CONFIG_SYS_NOR_FTIM3 #define CONFIG_SYS_CSPR1_EXT CONFIG_SYS_NAND_CSPR_EXT #define CONFIG_SYS_CSPR1 CONFIG_SYS_NAND_CSPR #define CONFIG_SYS_AMASK1 CONFIG_SYS_NAND_AMASK #define CONFIG_SYS_CSOR1 CONFIG_SYS_NAND_CSOR #define CONFIG_SYS_CS1_FTIM0 CONFIG_SYS_NAND_FTIM0 #define CONFIG_SYS_CS1_FTIM1 CONFIG_SYS_NAND_FTIM1 #define CONFIG_SYS_CS1_FTIM2 CONFIG_SYS_NAND_FTIM2 #define CONFIG_SYS_CS1_FTIM3 CONFIG_SYS_NAND_FTIM3 #endif #define CONFIG_SYS_CSPR2_EXT CONFIG_SYS_CPLD_CSPR_EXT #define CONFIG_SYS_CSPR2 CONFIG_SYS_CPLD_CSPR #define CONFIG_SYS_AMASK2 CONFIG_SYS_CPLD_AMASK #define CONFIG_SYS_CSOR2 CONFIG_SYS_CPLD_CSOR #define CONFIG_SYS_CS2_FTIM0 CONFIG_SYS_CPLD_FTIM0 #define CONFIG_SYS_CS2_FTIM1 CONFIG_SYS_CPLD_FTIM1 #define CONFIG_SYS_CS2_FTIM2 CONFIG_SYS_CPLD_FTIM2 #define CONFIG_SYS_CS2_FTIM3 CONFIG_SYS_CPLD_FTIM3 /* EEPROM */ #ifndef SPL_NO_EEPROM #define CONFIG_ID_EEPROM #define CONFIG_SYS_I2C_EEPROM_NXID #define CONFIG_SYS_EEPROM_BUS_NUM 0 #define CONFIG_SYS_I2C_EEPROM_ADDR 0x53 #define CONFIG_SYS_I2C_EEPROM_ADDR_LEN 1 #define CONFIG_SYS_EEPROM_PAGE_WRITE_BITS 3 #define CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS 5 #endif /* * Environment */ #ifndef SPL_NO_ENV #define CONFIG_ENV_OVERWRITE #endif #if defined(CONFIG_NAND_BOOT) #define CONFIG_ENV_SIZE 0x2000 #define CONFIG_ENV_OFFSET (24 * CONFIG_SYS_NAND_BLOCK_SIZE) #elif defined(CONFIG_SD_BOOT) #define CONFIG_ENV_OFFSET (3 * 1024 * 1024) #define CONFIG_SYS_MMC_ENV_DEV 0 #define CONFIG_ENV_SIZE 0x2000 #else #define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + 0x300000) #define CONFIG_ENV_SECT_SIZE 0x20000 #define CONFIG_ENV_SIZE 0x20000 #endif /* FMan */ #ifndef SPL_NO_FMAN #define AQR105_IRQ_MASK 0x40000000 #ifdef CONFIG_NET #define CONFIG_PHY_VITESSE #define CONFIG_PHY_REALTEK #endif #ifdef CONFIG_SYS_DPAA_FMAN #define CONFIG_FMAN_ENET #define CONFIG_PHYLIB_10G #define CONFIG_PHY_AQUANTIA #define RGMII_PHY1_ADDR 0x1 #define RGMII_PHY2_ADDR 0x2 #define QSGMII_PORT1_PHY_ADDR 0x4 #define QSGMII_PORT2_PHY_ADDR 0x5 #define QSGMII_PORT3_PHY_ADDR 0x6 #define QSGMII_PORT4_PHY_ADDR 0x7 #define FM1_10GEC1_PHY_ADDR 0x1 #define CONFIG_ETHPRIME "FM1@DTSEC3" #endif #endif /* QE */ #ifndef SPL_NO_QE #if !defined(CONFIG_NAND_BOOT) && !defined(CONFIG_QSPI_BOOT) #define CONFIG_U_QE #endif #endif /* SATA */ #ifndef SPL_NO_SATA #ifndef CONFIG_CMD_EXT2 #define CONFIG_CMD_EXT2 #endif #define CONFIG_SYS_SCSI_MAX_SCSI_ID 2 #define CONFIG_SYS_SCSI_MAX_LUN 2 #define CONFIG_SYS_SCSI_MAX_DEVICE (CONFIG_SYS_SCSI_MAX_SCSI_ID * \ CONFIG_SYS_SCSI_MAX_LUN) #define SCSI_VEND_ID 0x1b4b #define SCSI_DEV_ID 0x9170 #define CONFIG_SCSI_DEV_LIST {SCSI_VEND_ID, SCSI_DEV_ID} #endif #include <asm/fsl_secure_boot.h> #endif /* __LS1043ARDB_H__ */
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Memoria.Prime.Text; namespace Memoria.Assets { public sealed class ExportFieldTags : FieldTags { private readonly KeyValuePair<Regex, String>[] _complexTags; public ExportFieldTags() { _complexTags = GetComplexTags(); } public String Replace(String str) { if (String.IsNullOrEmpty(str)) return str; str = str.ReplaceAll(SimpleTags.Forward); foreach (KeyValuePair<Regex, String> pair in _complexTags) str = pair.Key.Replace(str, pair.Value); return str; } private KeyValuePair<Regex, String>[] GetComplexTags() { return new Dictionary<Regex, String> { {new Regex(@"\[STRT=([0-9]+),([0-9]+)\]"), "{W$1H$2}"}, {new Regex(@"\[NUMB=([0-9]+)\]"), "{Variable $1}"}, {new Regex(@"\[ICON=([0-9]+)\]"), "{Icon $1}"}, {new Regex(@"\[PNEW=([0-9]+)\]"), "{Icon+ $1}"}, {new Regex(@"\[SPED=(-?[0-9]+)\]"), "{Speed $1}"}, {new Regex(@"\[TEXT=([^]]+)\]"), "{Text $1}"}, {new Regex(@"\[WDTH=([^]]+)\]"), "{Widths $1}"}, {new Regex(@"\[TIME=([^]]+)\]"), "{Time $1}"}, {new Regex(@"\[WAIT=([^]]+)\]"), "{Wait $1}"}, {new Regex(@"\[CENT=([^]]+)\]"), "{Center $1}"}, {new Regex(@"\[ITEM=([^]]+)\]"), "{Item $1}"}, {new Regex(@"\[PCHC=([^]]+)\]"), "{PreChoose $1}"}, {new Regex(@"\[PCHM=([^]]+)\]"), "{PreChooseMask $1}"}, {new Regex(@"\[MPOS=([^]]+)\]"), "{Position $1}"}, {new Regex(@"\[OFFT=([^]]+)\]"), "{Offset $1}"}, {new Regex(@"\[MOBI=([^]]+)\]"), "{Mobile $1}"}, {new Regex(@"\[YADD=([^]]+)\]"), "{y$1}"}, {new Regex(@"\[YSUB=([^]]+)\]"), "{y-$1}"}, {new Regex(@"\[FEED=([^]]+)\]"), "{f$1}"}, {new Regex(@"\[XTAB=([^]]+)\]"), "{x$1}"}, {new Regex(@"\[TBLE=([^]]+)\]"), "{Table $1}"} }.ToArray(); } } }
<?php use PDFfiller\OAuth2\Client\Provider\FillableForm; use PDFfiller\OAuth2\Client\Provider\Enums\FillRequestNotifications; use PDFfiller\OAuth2\Client\Provider\DTO\NotificationEmail; use PDFfiller\OAuth2\Client\Provider\DTO\AdditionalDocument; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $fillRequestEntity = new FillableForm($provider); $fillRequestEntity->document_id = 23232323; $fillRequestEntity->access = "full"; $fillRequestEntity->status = "public"; $fillRequestEntity->email_required = true; $fillRequestEntity->name_required = true; $fillRequestEntity->custom_message = "Custom"; $fillRequestEntity->callback_url = "http://testhostexample.com"; $fillRequestEntity->notification_emails[] = new NotificationEmail(['name' => 'name', 'email' => 'email@email.com']); $fillRequestEntity->additional_documents = ['test', 'test22']; $fillRequestEntity->enforce_required_fields = true; $fillRequestEntity->welcome_screen = false; $fillRequestEntity->notifications = new FillRequestNotifications(FillRequestNotifications::WITH_PDF); $e = $fillRequestEntity->save(); dd($e);
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolDB.Models { /// <summary> /// /// </summary> public class Major { public int MajorId { get; set; } public string MajorName { get; set; } public bool Active { get; set; } } }
'use strict' if (!process.addAsyncListener) require('async-listener') var noop = function () {} module.exports = function () { return new AsyncState() } function AsyncState () { var state = this process.addAsyncListener({ create: asyncFunctionInitialized, before: asyncCallbackBefore, error: noop, after: asyncCallbackAfter }) // Record the state currently set on on the async-state object and return a // snapshot of it. The returned object will later be passed as the `data` // arg in the functions below. function asyncFunctionInitialized () { var data = {} for (var key in state) { data[key] = state[key] } return data } // We just returned from the event-loop: We'll now restore the state // previously saved by `asyncFunctionInitialized`. function asyncCallbackBefore (context, data) { for (var key in data) { state[key] = data[key] } } // Clear the state so that it doesn't leak between isolated async stacks. function asyncCallbackAfter (context, data) { for (var key in state) { delete state[key] } } }
/** Problem 9. Extract e-mails Write a function for extracting all email addresses from given text. All sub-strings that match the format @… should be recognized as emails. Return the emails as array of strings. */ console.log('Problem 9. Extract e-mails'); var text='gosho@gmail.com bla bla bla pesho_peshev@yahoo.com bla bla gosho_geshev@outlook.com' function extractEmails(text) { var result=text.match(/[A-Z0-9._-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/gi); return result; } console.log('Text: '+text); console.log('E-mail: '+extractEmails(text)); console.log('#########################################');
# frozen_string_literal: true require "rails_helper" module Socializer RSpec.describe People::ActivitiesController, type: :routing do routes { Socializer::Engine.routes } context "with routing" do it "routes to #index" do expect(get: "/people/1/activities") .to route_to("socializer/people/activities#index", person_id: "1") end it "does not route to #new" do expect(get: "/people/1/activities/new").not_to be_routable end it "does not route to #show" do expect(get: "/people/1/activities/1/show").not_to be_routable end it "does not route to #edit" do expect(get: "/people/1/activities/1/edit").not_to be_routable end it "does not route to #create" do expect(post: "/people/1/activities").not_to be_routable end context "when specify does not route to #update" do specify { expect(patch: "/people/1/activities/1").not_to be_routable } specify { expect(put: "/people/1/activities/1").not_to be_routable } end it "does not route to #destroy" do expect(delete: "/people/1/activities/1").not_to be_routable end end end end
/** * Border Left Radius */ module.exports = function (decl, args) { var radius = args[1] || '3px'; decl.replaceWith({ prop: 'border-bottom-left-radius', value: radius, source: decl.source }, { prop: 'border-top-left-radius', value: radius, source: decl.source }); };
//===================================================================== // This sample demonstrates using TeslaJS // // https://github.com/mseminatore/TeslaJS // // Copyright (c) 2016 Mark Seminatore // // Refer to included LICENSE file for usage rights and restrictions //===================================================================== "use strict"; require('colors'); var program = require('commander'); var framework = require('./sampleFramework.js'); // // // program .usage('[options]') .option('-i, --index <n>', 'vehicle index (first car by default)', parseInt) .option('-U, --uri [string]', 'URI of test server (e.g. http://127.0.0.1:3000)') .parse(process.argv); // var sample = new framework.SampleFramework(program, sampleMain); sample.run(); // // // function sampleMain(tjs, options) { var streamingOptions = { vehicle_id: options.vehicle_id, authToken: options.authToken }; console.log("\nNote: " + "Inactive vehicle streaming responses can take up to several minutes.".green); console.log("\nStreaming starting...".cyan); console.log("Columns: timestamp," + tjs.streamingColumns.toString()); tjs.startStreaming(streamingOptions, function (error, response, body) { if (error) { console.log(error); return; } // display the streaming results console.log(body); console.log("...Streaming ended.".cyan); }); }
// This file was generated based on 'C:\ProgramData\Uno\Packages\Fuse.Drawing\0.11.3\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #ifndef __APP_FUSE_DRAWING_WINDING_RULES_H__ #define __APP_FUSE_DRAWING_WINDING_RULES_H__ #include <Uno.h> namespace app { namespace Fuse { namespace Drawing { struct WindingRules__uType : ::uClassType { }; WindingRules__uType* WindingRules__typeof(); bool WindingRules__AbsoluteGreaterOrEqualsTwo(::uStatic* __this, int n); bool WindingRules__Negative(::uStatic* __this, int n); bool WindingRules__NonZero(::uStatic* __this, int n); bool WindingRules__Odd(::uStatic* __this, int n); bool WindingRules__Positive(::uStatic* __this, int n); }}} #endif
///<reference path="../node_modules/DefinitelyTyped/d3/d3.d.ts" /> interface PWInterpolatorFactory { (oldScale: D3.Scale.LinearScale) : (t: number)=>powerfocusI; } /** * A scale with polynomial zoom * @class powerfocusI * @extends D3.Scale.LinearScale */ interface powerfocusI extends D3.Scale.LinearScale { (domain: number[], range: number[], interpolate: D3.Transition.Interpolate, focus: number, exponent: number, scaleInterpolate?: PWInterpolatorFactory) : powerfocusI; focus: { (): number; (x: number): powerfocusI; }; exponent: { (): number; (x: number): powerfocusI; }; derivative(x:number): number; invDerivAtFocus(): number; scaleInterpolate: { (): PWInterpolatorFactory; (f: PWInterpolatorFactory): powerfocusI; }; regionFocus(rstart:number, rend:number, proportion:number); powerticks(m?): number[][]; copy(): powerfocusI; } declare var powerfocus: powerfocusI;
--- layout: default --- <div class="page"> <h1 class="page-title">{{ page.title }}</h1> <div id="toc"></div> {{ content }} </div>
package net.server; import java.net.Socket; import net.client.SocketClientProtocol; public abstract class SocketServerProtocol extends SocketClientProtocol { /** * Allow a sender to be added to the socket protocol's list of senders. * * This can be useful to send messages to clients which are not the current * senders, though which are affected by the actions of the current sender. * * @param sender * A Socket object which is tied to the sender object. */ public abstract void addSender(Socket sender); /** * Allow a sender to be removed from the socket protocol's list of senders. * * @param sender * A Socket object which is tied to the sender object. */ public abstract void removeSender(Socket sender); /** * Get the maximum number of allowed client connections to this protocol. * * @return an integer representing the maximum number of allowed * connections. */ public abstract int getMaxConnections(); /** * Get the current number of clients connected to this protocol. * * @return an integer representing the current number of connections. */ public abstract int getNumConnections(); }
using DrinkCounter.Models; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Data.Entity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace DrinkCounter { public class Startup { public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var connectionString = "Server=drinkcounter.database.windows.net;Database=DrinkCounterData;User ID=drink;Password=Antl123!;Trusted_Connection=False;Connect Timeout=30;Encrypt=True;MultipleActiveResultSets=False"; services.AddCors(); // Add framework services. services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<DrinkingData>(options => options.UseSqlServer(connectionString)); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors(builder => builder.WithOrigins("http://localhost:5000") .AllowAnyHeader()); app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(); } // Entry point for the application. public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } }
## Precision Calculate the precision of anything that can be converted into a decimal. ```ruby irb> Precision::Calculator.new(BigDecimal("12.12")).calculate => 2 irb> Precision::Calculator.new("12.1234").calculate => 4 irb> Precision::Calculator.new(12.123).calculate => 3 irb> Precision::Calculator.new(nil).calculate => 0 # #calculate is aliased to #to_i irb> precision = Precision::Calculator.new(1) irb> precision.to_i == precision.calculate => true ``` ### Why might this be helpful? Create the `precision` option argument using the current value of an attribute: ```ruby <%= number_to_currency @model.n, precision: Precision::Calculator.new(@model.n).to_i %> ``` ## Installation gem 'precision' ## Contributions - Created by [@barelyknown](https://twitter.com/barelyknown) - You?
require 'hatt' describe Hatt do before(:each) do Hatt.hatt_initialize end it 'should have configuration' do subject.should respond_to :hatt_configuration subject.hatt_configuration.should be_a Hash end context 'a service name yourapi is configured' do before(:each) do subject.hatt_add_service 'yourapi', 'https://yourapi.com' end it 'should get a class method for service yourapi' do subject.hatt_build_client_methods subject.should respond_to :yourapi subject.yourapi.should be_a Hatt::HTTP subject.yourapi.should respond_to :get end end context 'a hatt file is given' do before(:each) do subject.hatt_load_hatt_file SingleHattFile end it 'should have a method named gmethod' do Hatt.should respond_to :gmethod Hatt.gmethod.should == 'gmethod returned this' end end context 'initializing from the working directory' do before(:each) do @orig_working_dir = Dir.pwd Dir.chdir FullExampleDir Hatt.hatt_initialize end after(:each) do Dir.chdir @orig_working_dir end it 'should get services from the working directory' do Hatt.should respond_to :myapi end it 'should get hatt methods' do Hatt.should respond_to :a_hatt_method Hatt.a_hatt_method('x').should eql 'return value' end end context 'initializing from a config file not in working directory' do before(:each) do Hatt.hatt_config_file FullExampleFile Hatt.hatt_initialize end it 'should respond to services' do Hatt.should respond_to :myapi end it 'should get hatt methods' do Hatt.should respond_to :a_hatt_method Hatt.a_hatt_method('x').should eql 'return value' end end describe '#run_script_file' do before(:each) do Hatt.hatt_config_file FullExampleFile Hatt.hatt_initialize end it 'should produce an exception if given non-existent file' do expect { Hatt.run_script_file 'fake_file.rb' }.to raise_error(ArgumentError) end it 'should allow return what the script returns' do rtn = Hatt.run_script_file SimpleHattScript rtn.should == 42 end it 'should allow a script to call hatt dsl methods' do rtn = Hatt.run_script_file DSLCallHattScript rtn.should == 'return value' end end describe '#new method' do it 'should allow creating a new hatt instance' do new_instance = Hatt.new config_file: FullExampleFile expect(new_instance.respond_to?(:myapi)).to be true end end end
module.exports = { dist: { files: { 'dist/geo.js': ['src/index.js'], } } };
package com.onliquid.personalization; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import io.lqd.sdk.Liquid; import java.util.HashMap; public class MainActivity extends Activity { private Liquid lqd; protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_main); lqd = Liquid.getInstance(); } public void enterSecondActivity(String username) { Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("user", username); startActivity(intent); } public void login(View view) { String username = ""; HashMap attrs = new HashMap(); switch (view.getId()) { case R.id.jack: attrs.put("age", 23); attrs.put("gender", "male"); username = "Jack"; break; case R.id.jill: attrs.put("age", 32); attrs.put("gender", "female"); username = "Jill"; break; case R.id.jonas: attrs.put("age", 35); attrs.put("gender", "male"); username = "Jonas"; } lqd.identifyUser(username, attrs); enterSecondActivity(username); } }
namespace Subsonic.Client { public struct SubsonicToken { public string Token { get; set; } public string Salt { get; set; } } }
<?php /** * @author Ronald Vilbrandt <info@rvi-media.de> * @copyright 2015 Ronald Vilbrandt, RVI-Media (www.rvi-media.de) * @since 2015-08-13 */ namespace Page\Home; class HomeHtmlView extends \aRvi\View\View { /** * Runs the view * * @return string View content */ public function run() { return "This is home. :)<br />Try <a href=\"" . $this->uriFetcher->fetch("page1?param1=¯\_(ツ)_/¯#jump") . "\">Page1</a> too!"; } }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("NavigationBarTitleSample.Droid")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP Inc.")] [assembly: AssemblyProduct("NavigationBarTitleSample.Droid")] [assembly: AssemblyCopyright("Copyright © HP Inc. 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // 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")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
<?php class Question { private $connection; function __construct($mysqli) { $this->connection = $mysqli; } // Kõikide küsimustikude tõmbamine andmebaasist function getAllQuestionnaires($email){ $stmt = $this->connection->prepare("SELECT tap_questionnaires.id, tap_questionnaires.name, tap_questionnaires.active, COUNT(tap_useranswers_ip.ip) FROM TAP_questionnaires LEFT JOIN TAP_useranswers_ip ON tap_questionnaires.id = tap_useranswers_ip.questionnaire_id WHERE author_email = ? GROUP BY tap_questionnaires.id, tap_questionnaires.name, tap_questionnaires.active;"); $stmt->bind_param("s", $email); $stmt->bind_result($id, $name, $active, $count); $stmt->execute(); $result = array(); while ($stmt->fetch()) { $questionnaires = new StdClass(); $questionnaires->questionnaire_id= $id; $questionnaires->questionnaire_name = $name; $questionnaires->questionnaire_status = $active; $questionnaires->questionnaire_answercount = $count; array_push($result, $questionnaires); } $stmt->close(); return $result; } // Küsimustiku vaatamise jaoks admin panelis function viewQuestionnaireAdmin($id){ $questionStmt = $this->connection->prepare("SELECT id, type, name FROM TAP_questions WHERE questionnaire_id=?;"); $questionStmt->bind_param("i", $id); $questionStmt->bind_result($id, $type, $name); $questionStmt->execute(); $result = array(); while ($questionStmt->fetch()) { $questions = new StdClass(); $questions->question_id = $id; $questions->question_type = $type; $questions->question_name = $name; array_push($result, $questions); } $questionStmt->close(); return $result; } // Küsimustiku kustutamine function delQuestionnaire($id){ $stmt = $this->connection->prepare("DELETE FROM TAP_questionnaires WHERE id=?"); $stmt->bind_param("i", $id); $stmt->execute(); $stmt->close(); } // Küsimustiku loomine function createQuestionnaireWithNameAndEmail($name, $email, $questions){ $active = 1; $stmt = $this->connection->prepare("INSERT INTO tap_questionnaires (name, author_email, active) VALUES (?, ?, ?);"); $stmt->bind_param("ssi", $name, $email, $active); $stmt->execute(); $quizId = $stmt->insert_id; $stmt->prepare("INSERT INTO tap_questions (questionnaire_id, type, name) VALUES(?, ?, ?)"); foreach($questions as $question){ if($question->type == "0"){ $stmt->bind_param('iis', $quizId, $question->type, $question->name); $stmt->execute(); }elseif($question->type=="2"){ $stmt->bind_param('iis', $quizId, $question->type, $question->name); $stmt->execute(); $questionId = $stmt->insert_id; foreach($question->options as $opt){ $stmtOptions= $this->connection->prepare("INSERT INTO tap_options (question_id, options) VALUES (?,?)"); $stmtOptions->bind_param('is', $questionId, $opt); $stmtOptions->execute(); $stmtOptions->close(); } } } $stmt->close(); } // Küsimustiku tõmbamine /quiz/index.php lehe jaoks et kontrollida, kas küsimustik on aktiivne või mitte function loadQuestionnaireToAnswer($id){ $questionnaireStmt = $this->connection->prepare("SELECT name, active FROM TAP_questionnaires WHERE id=?;"); $questionnaireStmt->bind_param("i", $id); $questionnaireStmt->bind_result($qu_name, $active); $questionnaireStmt->execute(); while ($questionnaireStmt->fetch()){ $questionnaire = new StdClass(); $questionnaire->questionnaire_name = $qu_name; $questionnaire->questionnaire_status = $active; } $questionnaireStmt->close(); return $questionnaire; } // Küsimustiku tõmbamine /quiz/index.php lehe jaoks et vastata function viewQuestionnaireToAnswer($id) { $questionStmt = $this->connection->prepare("SELECT TAP_questions.id, TAP_questions.type, TAP_questions.name, TAP_options.id, TAP_options.options from TAP_questions LEFT JOIN TAP_options on TAP_questions.id=TAP_options.question_id WHERE TAP_questions.questionnaire_id = ?;"); $questionStmt->bind_param("i", $id); $questionStmt->bind_result($question_id, $question_type, $question_name, $option_id, $option_name); $questionStmt->execute(); $result = array(); while ($questionStmt->fetch()) { $questions = new StdClass(); $questions->question_id = $question_id; $questions->question_type = $question_type; $questions->question_name = $question_name; $questions->question_options = array(); if($question_type == 2){ $options = new StdClass(); $options->option_id = $option_id; $options->option_name = $option_name; array_push($questions->question_options, $options); } if(array_key_exists($question_id, $result) && isset($questions->question_options)){ array_push($result[$question_id]->question_options, $questions->question_options[0]); } else { $result[$question_id] = $questions; } } $questionStmt->close(); $temp = array(); foreach ($result as $key => $value) { array_push($temp, $value); } $result = $temp; return $result; } // Checkboxiga (switch) küsimustiku staatuse muutmine admin panelil function changeQuestionnaireStatus($id){ $stmt = $this->connection->prepare("SELECT active FROM TAP_questionnaires WHERE id=?;"); $stmt->bind_param("i",$id); $stmt->bind_result($qu_status); $stmt->execute(); while ($stmt->fetch()){ $questionnaire_status=$qu_status; } $stmt->close(); if($questionnaire_status==0){ $stmt2 = $this->connection->prepare("UPDATE TAP_questionnaires SET active=1 WHERE id=?;"); $stmt2->bind_param("i", $id); $stmt2->execute(); $stmt2->close(); }else{ $stmt2 = $this->connection->prepare("UPDATE TAP_questionnaires SET active=0 WHERE id=?;"); $stmt2->bind_param("i", $id); $stmt2->execute(); $stmt2->close(); } } // Kontroll, kas inimene juba vastas küsimusele või mitte function hasUserAnsweredQuiz($quizId, $userIp){ $stmt = $this->connection->prepare("SELECT EXISTS(SELECT * FROM TAP_useranswers_ip WHERE questionnaire_id = ? AND ip = ?);"); $stmt->bind_param("is", $quizId, $userIp); $stmt->bind_result($exists); $stmt->execute(); $stmt->fetch(); $stmt->close(); return boolval($exists); } // Küsimustikule vastuste lisamine andmebaasi function addAnswersToDb($quizId, $userIp, $answers){ $stmt = $this->connection->prepare("INSERT INTO tap_useranswers_ip (questionnaire_id, ip) VALUES (?, ?);"); $stmt->bind_param('is', $quizId, $userIp); $stmt->execute(); $stmt->prepare("INSERT INTO tap_useranswers (questionnaire_id, question_id, answer) VALUES (?, ?, ?)"); foreach($answers as $answer){ $stmt->bind_param('iis', $quizId, $answer->id, $answer->value); $stmt->execute(); } $stmt->close(); } }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Oakcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "merkleblock.h" #include "hash.h" #include "consensus/consensus.h" #include "utilstrencodings.h" CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter) { header = block.GetBlockHeader(); std::vector<bool> vMatch; std::vector<uint256> vHashes; vMatch.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size()); for (unsigned int i = 0; i < block.vtx.size(); i++) { const uint256& hash = block.vtx[i]->GetHash(); if (filter.IsRelevantAndUpdate(*block.vtx[i])) { vMatch.push_back(true); vMatchedTxn.push_back(std::make_pair(i, hash)); } else vMatch.push_back(false); vHashes.push_back(hash); } txn = CPartialMerkleTree(vHashes, vMatch); } CMerkleBlock::CMerkleBlock(const CBlock& block, const std::set<uint256>& txids) { header = block.GetBlockHeader(); std::vector<bool> vMatch; std::vector<uint256> vHashes; vMatch.reserve(block.vtx.size()); vHashes.reserve(block.vtx.size()); for (unsigned int i = 0; i < block.vtx.size(); i++) { const uint256& hash = block.vtx[i]->GetHash(); if (txids.count(hash)) vMatch.push_back(true); else vMatch.push_back(false); vHashes.push_back(hash); } txn = CPartialMerkleTree(vHashes, vMatch); } uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) { if (height == 0) { // hash at height 0 is the txids themself return vTxid[pos]; } else { // calculate left hash uint256 left = CalcHash(height-1, pos*2, vTxid), right; // calculate right hash if not beyond the end of the array - copy left hash otherwise if (pos*2+1 < CalcTreeWidth(height-1)) right = CalcHash(height-1, pos*2+1, vTxid); else right = left; // combine subhashes return Hash(BEGIN(left), END(left), BEGIN(right), END(right)); } } void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) { // determine whether this node is the parent of at least one matched txid bool fParentOfMatch = false; for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++) fParentOfMatch |= vMatch[p]; // store as flag bit vBits.push_back(fParentOfMatch); if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, store hash and stop vHash.push_back(CalcHash(height, pos, vTxid)); } else { // otherwise, don't store any hash, but descend into the subtrees TraverseAndBuild(height-1, pos*2, vTxid, vMatch); if (pos*2+1 < CalcTreeWidth(height-1)) TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch); } } uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { if (nBitsUsed >= vBits.size()) { // overflowed the bits array - failure fBad = true; return uint256(); } bool fParentOfMatch = vBits[nBitsUsed++]; if (height==0 || !fParentOfMatch) { // if at height 0, or nothing interesting below, use stored hash and do not descend if (nHashUsed >= vHash.size()) { // overflowed the hash array - failure fBad = true; return uint256(); } const uint256 &hash = vHash[nHashUsed++]; if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid vMatch.push_back(hash); vnIndex.push_back(pos); } return hash; } else { // otherwise, descend into the subtrees to extract matched txids and hashes uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right; if (pos*2+1 < CalcTreeWidth(height-1)) { right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex); if (right == left) { // The left and right branches should never be identical, as the transaction // hashes covered by them must each be unique. fBad = true; } } else { right = left; } // and combine them before returning return Hash(BEGIN(left), END(left), BEGIN(right), END(right)); } } CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) { // reset state vBits.clear(); vHash.clear(); // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree TraverseAndBuild(nHeight, 0, vTxid, vMatch); } CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {} uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) { vMatch.clear(); // An empty set will not work if (nTransactions == 0) return uint256(); // check for excessively high numbers of transactions if (nTransactions > MAX_BLOCK_BASE_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction return uint256(); // there can never be more hashes provided than one for every txid if (vHash.size() > nTransactions) return uint256(); // there must be at least one bit per node in the partial tree, and at least one node per hash if (vBits.size() < vHash.size()) return uint256(); // calculate height of tree int nHeight = 0; while (CalcTreeWidth(nHeight) > 1) nHeight++; // traverse the partial tree unsigned int nBitsUsed = 0, nHashUsed = 0; uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex); // verify that no problems occurred during the tree traversal if (fBad) return uint256(); // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence) if ((nBitsUsed+7)/8 != (vBits.size()+7)/8) return uint256(); // verify that all hashes were consumed if (nHashUsed != vHash.size()) return uint256(); return hashMerkleRoot; }
var Model = require('./model'); var schema = { name : String, stuff: { electronics: [{ type: String }], computing_dev: [{ type: String }] }, age:{ biological: Number }, fruits: [ { name: String, fav: Boolean, about: [{ type: String }] } ] }; var person = function(data){ Model.call(this, schema, data); } person.prototype = Object.create(Model.prototype); module.exports = person;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div class="SRResult" id="SR_cap"> <div class="SREntry"> <a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_line_style.html#aa2023f2a4d7c26a6a95a1d1485307e85" target="basefrm">cap</a> <span class="SRScope">VSTGUI::CLineStyle</span> </div> </div> <div class="SRResult" id="SR_character"> <div class="SREntry"> <a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../struct_vst_key_code.html#ae76851c804f88de843ab6325faef23a0" target="basefrm">character</a> <span class="SRScope">VstKeyCode</span> </div> </div> <div class="SRResult" id="SR_checkerboardback"> <div class="SREntry"> <a id="Item2" onkeydown="return searchResults.Nav(event,2)" onkeypress="return searchResults.Nav(event,2)" onkeyup="return searchResults.Nav(event,2)" class="SRSymbol" href="../struct_v_s_t_g_u_i_1_1_c_color_chooser_u_i_settings.html#a3e21f7141966a030d2f12697fe12d9d9" target="basefrm">checkerBoardBack</a> <span class="SRScope">VSTGUI::CColorChooserUISettings</span> </div> </div> <div class="SRResult" id="SR_checkerboardcolor1"> <div class="SREntry"> <a id="Item3" onkeydown="return searchResults.Nav(event,3)" onkeypress="return searchResults.Nav(event,3)" onkeyup="return searchResults.Nav(event,3)" class="SRSymbol" href="../struct_v_s_t_g_u_i_1_1_c_color_chooser_u_i_settings.html#a658ad2ac3541c73346fc9dbbad6eb00b" target="basefrm">checkerBoardColor1</a> <span class="SRScope">VSTGUI::CColorChooserUISettings</span> </div> </div> <div class="SRResult" id="SR_checkerboardcolor2"> <div class="SREntry"> <a id="Item4" onkeydown="return searchResults.Nav(event,4)" onkeypress="return searchResults.Nav(event,4)" onkeyup="return searchResults.Nav(event,4)" class="SRSymbol" href="../struct_v_s_t_g_u_i_1_1_c_color_chooser_u_i_settings.html#a152e6aa403c04a7ac531975130ffea16" target="basefrm">checkerBoardColor2</a> <span class="SRScope">VSTGUI::CColorChooserUISettings</span> </div> </div> <div class="SRResult" id="SR_checkmarkcolor"> <div class="SREntry"> <a id="Item5" onkeydown="return searchResults.Nav(event,5)" onkeypress="return searchResults.Nav(event,5)" onkeyup="return searchResults.Nav(event,5)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_check_box.html#a26c887534e5c0e18ac093f72cde46d87" target="basefrm">checkMarkColor</a> <span class="SRScope">VSTGUI::CCheckBox</span> </div> </div> <div class="SRResult" id="SR_children"> <div class="SREntry"> <a id="Item6" onkeydown="return searchResults.Nav(event,6)" onkeypress="return searchResults.Nav(event,6)" onkeyup="return searchResults.Nav(event,6)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_view_container_1_1_iterator.html#a7d7e8ea48212b8a765026d35378fa9ed" target="basefrm">children</a> <span class="SRScope">VSTGUI::CViewContainer::Iterator</span> </div> </div> <div class="SRResult" id="SR_color1"> <div class="SREntry"> <a id="Item7" onkeydown="return searchResults.Nav(event,7)" onkeypress="return searchResults.Nav(event,7)" onkeyup="return searchResults.Nav(event,7)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_gradient.html#a85d2c87e0727bbb9444b6d70477e59e6" target="basefrm">color1</a> <span class="SRScope">VSTGUI::CGradient</span> </div> </div> <div class="SRResult" id="SR_color1start"> <div class="SREntry"> <a id="Item8" onkeydown="return searchResults.Nav(event,8)" onkeypress="return searchResults.Nav(event,8)" onkeyup="return searchResults.Nav(event,8)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_gradient.html#a696f05be9b01d4e662f8d5fbe2e43dfb" target="basefrm">color1Start</a> <span class="SRScope">VSTGUI::CGradient</span> </div> </div> <div class="SRResult" id="SR_color2"> <div class="SREntry"> <a id="Item9" onkeydown="return searchResults.Nav(event,9)" onkeypress="return searchResults.Nav(event,9)" onkeyup="return searchResults.Nav(event,9)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_gradient.html#ad11ec3c45a6279ccb1abc3439331440c" target="basefrm">color2</a> <span class="SRScope">VSTGUI::CGradient</span> </div> </div> <div class="SRResult" id="SR_color2start"> <div class="SREntry"> <a id="Item10" onkeydown="return searchResults.Nav(event,10)" onkeypress="return searchResults.Nav(event,10)" onkeyup="return searchResults.Nav(event,10)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_gradient.html#a3899418147af0a7a1f84d030ca8e94d1" target="basefrm">color2Start</a> <span class="SRScope">VSTGUI::CGradient</span> </div> </div> <div class="SRResult" id="SR_colorhandle"> <div class="SREntry"> <a id="Item11" onkeydown="return searchResults.Nav(event,11)" onkeypress="return searchResults.Nav(event,11)" onkeyup="return searchResults.Nav(event,11)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_knob.html#a418d1b806931b98d211ecc0af342dbc0" target="basefrm">colorHandle</a> <span class="SRScope">VSTGUI::CKnob</span> </div> </div> <div class="SRResult" id="SR_colorshadowhandle"> <div class="SREntry"> <a id="Item12" onkeydown="return searchResults.Nav(event,12)" onkeypress="return searchResults.Nav(event,12)" onkeyup="return searchResults.Nav(event,12)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_knob.html#a939210e3ee965525376d4dd3bb337e14" target="basefrm">colorShadowHandle</a> <span class="SRScope">VSTGUI::CKnob</span> </div> </div> <div class="SRResult" id="SR_column"> <div class="SREntry"> <a id="Item13" onkeydown="return searchResults.Nav(event,13)" onkeypress="return searchResults.Nav(event,13)" onkeyup="return searchResults.Nav(event,13)" class="SRSymbol" href="../struct_v_s_t_g_u_i_1_1_c_data_browser_1_1_cell.html#a195211ed0f0ffdbca091d00a42efedcc" target="basefrm">column</a> <span class="SRScope">VSTGUI::CDataBrowser::Cell</span> </div> </div> <div class="SRResult" id="SR_commandcategory"> <div class="SREntry"> <a id="Item14" onkeydown="return searchResults.Nav(event,14)" onkeypress="return searchResults.Nav(event,14)" onkeyup="return searchResults.Nav(event,14)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_command_menu_item.html#ab1c8ab3081ae2c96a4ebe9ed2ab49519" target="basefrm">commandCategory</a> <span class="SRScope">VSTGUI::CCommandMenuItem</span> </div> </div> <div class="SRResult" id="SR_commandname"> <div class="SREntry"> <a id="Item15" onkeydown="return searchResults.Nav(event,15)" onkeypress="return searchResults.Nav(event,15)" onkeyup="return searchResults.Nav(event,15)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_command_menu_item.html#aaeb16723070f85c3a89a82459ecaff69" target="basefrm">commandName</a> <span class="SRScope">VSTGUI::CCommandMenuItem</span> </div> </div> <div class="SRResult" id="SR_containersize"> <div class="SREntry"> <a id="Item16" onkeydown="return searchResults.Nav(event,16)" onkeypress="return searchResults.Nav(event,16)" onkeyup="return searchResults.Nav(event,16)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_scroll_view.html#acc639bfdaf5f4b9cde46e48d6e47943c" target="basefrm">containerSize</a> <span class="SRScope">VSTGUI::CScrollView</span> </div> </div> <div class="SRResult" id="SR_controller"> <div class="SREntry"> <a id="Item17" onkeydown="return searchResults.Nav(event,17)" onkeypress="return searchResults.Nav(event,17)" onkeyup="return searchResults.Nav(event,17)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_controller')">controller</a> <div class="SRChildren"> <a id="Item17_c0" onkeydown="return searchResults.NavChild(event,17,0)" onkeypress="return searchResults.NavChild(event,17,0)" onkeyup="return searchResults.NavChild(event,17,0)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_u_i_description.html#aa611c25d4b4cb60fddc1925a2907524f" target="basefrm">VSTGUI::UIDescription::controller()</a> <a id="Item17_c1" onkeydown="return searchResults.NavChild(event,17,1)" onkeypress="return searchResults.NavChild(event,17,1)" onkeyup="return searchResults.NavChild(event,17,1)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_delegation_controller.html#aa611c25d4b4cb60fddc1925a2907524f" target="basefrm">VSTGUI::DelegationController::controller()</a> <a id="Item17_c2" onkeydown="return searchResults.NavChild(event,17,2)" onkeypress="return searchResults.NavChild(event,17,2)" onkeyup="return searchResults.NavChild(event,17,2)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_u_i_view_switch_container.html#a717bbbc5618e104128f353409bdce01f" target="basefrm">VSTGUI::UIViewSwitchContainer::controller()</a> </div> </div> </div> <div class="SRResult" id="SR_controls"> <div class="SREntry"> <a id="Item18" onkeydown="return searchResults.Nav(event,18)" onkeypress="return searchResults.Nav(event,18)" onkeyup="return searchResults.Nav(event,18)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_controls')">controls</a> <div class="SRChildren"> <a id="Item18_c0" onkeydown="return searchResults.NavChild(event,18,0)" onkeypress="return searchResults.NavChild(event,18,0)" onkeyup="return searchResults.NavChild(event,18,0)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_parameter_change_listener.html#a187e38cb07c75c6f05a3b5f7c1634a3e" target="basefrm">VSTGUI::ParameterChangeListener::controls()</a> <a id="Item18_c1" onkeydown="return searchResults.NavChild(event,18,1)" onkeypress="return searchResults.NavChild(event,18,1)" onkeyup="return searchResults.NavChild(event,18,1)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_group_controller.html#a187e38cb07c75c6f05a3b5f7c1634a3e" target="basefrm">VSTGUI::GroupController::controls()</a> </div> </div> </div> <div class="SRResult" id="SR_coronacolor"> <div class="SREntry"> <a id="Item19" onkeydown="return searchResults.Nav(event,19)" onkeypress="return searchResults.Nav(event,19)" onkeyup="return searchResults.Nav(event,19)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_knob.html#ae2309083da3ff181d292a78966dcc800" target="basefrm">coronaColor</a> <span class="SRScope">VSTGUI::CKnob</span> </div> </div> <div class="SRResult" id="SR_coronainset"> <div class="SREntry"> <a id="Item20" onkeydown="return searchResults.Nav(event,20)" onkeypress="return searchResults.Nav(event,20)" onkeyup="return searchResults.Nav(event,20)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_knob.html#aac7ace36dc86727e892be559c715e5e2" target="basefrm">coronaInset</a> <span class="SRScope">VSTGUI::CKnob</span> </div> </div> <div class="SRResult" id="SR_currentchild"> <div class="SREntry"> <a id="Item21" onkeydown="return searchResults.Nav(event,21)" onkeypress="return searchResults.Nav(event,21)" onkeyup="return searchResults.Nav(event,21)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_tab_view.html#adc79eeea30fdbbaa88f73ef0667e19f3" target="basefrm">currentChild</a> <span class="SRScope">VSTGUI::CTabView</span> </div> </div> <div class="SRResult" id="SR_currentdragview"> <div class="SREntry"> <a id="Item22" onkeydown="return searchResults.Nav(event,22)" onkeypress="return searchResults.Nav(event,22)" onkeyup="return searchResults.Nav(event,22)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_view_container.html#a3bdf352a921a7c724261b057e99d9c52" target="basefrm">currentDragView</a> <span class="SRScope">VSTGUI::CViewContainer</span> </div> </div> <div class="SRResult" id="SR_currentindex"> <div class="SREntry"> <a id="Item23" onkeydown="return searchResults.Nav(event,23)" onkeypress="return searchResults.Nav(event,23)" onkeyup="return searchResults.Nav(event,23)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_currentindex')">currentIndex</a> <div class="SRChildren"> <a id="Item23_c0" onkeydown="return searchResults.NavChild(event,23,0)" onkeypress="return searchResults.NavChild(event,23,0)" onkeyup="return searchResults.NavChild(event,23,0)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_c_option_menu.html#aa9f724afe491a4aa3e3689f0a83f59c0" target="basefrm">VSTGUI::COptionMenu::currentIndex()</a> <a id="Item23_c1" onkeydown="return searchResults.NavChild(event,23,1)" onkeypress="return searchResults.NavChild(event,23,1)" onkeyup="return searchResults.NavChild(event,23,1)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_u_i_description_view_switch_controller.html#aa9f724afe491a4aa3e3689f0a83f59c0" target="basefrm">VSTGUI::UIDescriptionViewSwitchController::currentIndex()</a> </div> </div> </div> <div class="SRResult" id="SR_currentpos"> <div class="SREntry"> <a id="Item24" onkeydown="return searchResults.Nav(event,24)" onkeypress="return searchResults.Nav(event,24)" onkeyup="return searchResults.Nav(event,24)" class="SRSymbol" href="javascript:searchResults.Toggle('SR_currentpos')">currentPos</a> <div class="SRChildren"> <a id="Item24_c0" onkeydown="return searchResults.NavChild(event,24,0)" onkeypress="return searchResults.NavChild(event,24,0)" onkeyup="return searchResults.NavChild(event,24,0)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_c_bitmap_pixel_access.html#a4401caa753d152ea2061b99f0761fc88" target="basefrm">VSTGUI::CBitmapPixelAccess::currentPos()</a> <a id="Item24_c1" onkeydown="return searchResults.NavChild(event,24,1)" onkeypress="return searchResults.NavChild(event,24,1)" onkeyup="return searchResults.NavChild(event,24,1)" class="SRScope" href="../class_v_s_t_g_u_i_1_1_u_t_f8_character_iterator.html#a4401caa753d152ea2061b99f0761fc88" target="basefrm">VSTGUI::UTF8CharacterIterator::currentPos()</a> </div> </div> </div> <div class="SRResult" id="SR_currentstate"> <div class="SREntry"> <a id="Item25" onkeydown="return searchResults.Nav(event,25)" onkeypress="return searchResults.Nav(event,25)" onkeyup="return searchResults.Nav(event,25)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_draw_context.html#a60bc442b10c4c7035b1fba29fc232158" target="basefrm">currentState</a> <span class="SRScope">VSTGUI::CDrawContext</span> </div> </div> <div class="SRResult" id="SR_currenttab"> <div class="SREntry"> <a id="Item26" onkeydown="return searchResults.Nav(event,26)" onkeypress="return searchResults.Nav(event,26)" onkeyup="return searchResults.Nav(event,26)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_tab_view.html#a892f79cd72c099da161916e45f9c46bc" target="basefrm">currentTab</a> <span class="SRScope">VSTGUI::CTabView</span> </div> </div> <div class="SRResult" id="SR_currentview"> <div class="SREntry"> <a id="Item27" onkeydown="return searchResults.Nav(event,27)" onkeypress="return searchResults.Nav(event,27)" onkeyup="return searchResults.Nav(event,27)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_c_tooltip_support.html#a7ce97521eac28552ba3b017a500f4511" target="basefrm">currentView</a> <span class="SRScope">VSTGUI::CTooltipSupport</span> </div> </div> <div class="SRResult" id="SR_currentviewindex"> <div class="SREntry"> <a id="Item28" onkeydown="return searchResults.Nav(event,28)" onkeypress="return searchResults.Nav(event,28)" onkeyup="return searchResults.Nav(event,28)" class="SRSymbol" href="../class_v_s_t_g_u_i_1_1_u_i_view_switch_container.html#acee01fd179fb587a5703cf9a1e60bbfc" target="basefrm">currentViewIndex</a> <span class="SRScope">VSTGUI::UIViewSwitchContainer</span> </div> </div> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
#include <cstdlib> #include <iostream> #include <vector> #include <sys/time.h> #include <omp.h> #include <hbwmalloc.h> using namespace std; double drand() { return double(rand()) / double(RAND_MAX); } double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } const int n_task =2048; const int n_time = 8192; typedef double *double_ptr; typedef double task_ar[n_task]; void compute (task_ar aar, task_ar bar, int n_time, int n_task) { const int t_unroll=4; for (int t = 0; t < n_time; t+=t_unroll) { for(int t2=0;t2<t_unroll; ++t2) { for (int i = 1; i < n_task-1; ++i) { double l = aar[i-1]; double c = aar[i]; double r = aar[i+1]; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; bar[i] = c; } for (int i = 1; i < n_task-1; ++i) { double l = bar[i-1]; double c = bar[i]; double r = bar[i+1]; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; aar[i] = c; } } #pragma omp barrier } } int main () { const int n_thre = omp_get_max_threads(); cout << "n_thre " << n_thre << " " <<flush; vector<double_ptr> ptra; vector<double_ptr> ptrb; for (int i=0;i<n_thre;++i) { ptra.push_back((double*)hbw_malloc(sizeof(double) * n_task)); ptrb.push_back((double*)hbw_malloc(sizeof(double) * n_task)); for (int x=0;x<n_task;++x) { ptra[i][x] = drand(); ptrb[i][x] = drand(); } } double time_begin = wctime(); #pragma omp parallel { int tid=omp_get_thread_num(); compute(ptra[tid], ptrb[tid], n_time, n_task); } double time_end = wctime(); double gflop = double(108)/1e9 * n_time * n_task * n_thre; double sum = 0; for (int i=0;i<n_thre;++i) { for (int x=0;x<n_task;++x) { sum += ptra[i][x]; } } cout << sum << "\tGflop " << gflop << "\ttime " << (time_end - time_begin) << "\tGflops " << gflop/(time_end - time_begin) << " n_barrier " << n_time << endl; }
import java.util.HashMap; import java.util.Map; public class LeetCode171 { public int titleToNumber(String s) { char[] chars = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 1; i <= chars.length; i++) { map.put(chars[i-1], i); } int result = 0; for (int i = s.length() -1; i >= 0; i--) { int num1 = map.get(s.charAt(i)); int pow = (int) Math.pow(26, s.length() -1 -i); result += num1 * pow; } return result; } public static void main(String[] args) { LeetCode171 leetCode171 = new LeetCode171(); System.out.println(leetCode171.titleToNumber("ZY")); } }
// Depends on jsbn.js and rng.js // Version 1.1: support utf-8 encoding in pkcs1pad2 // convert a (hex) string to a bignum object function parseBigInt(str,r) { return new BigInteger(str,r); } function linebrk(s,n) { var ret = ""; var i = 0; while(i + n < s.length) { ret += s.substring(i,i+n) + "\n"; i += n; } return ret + s.substring(i,s.length); } function byte2Hex(b) { if(b < 0x10) return "0" + b.toString(16); else return b.toString(16); } // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s,n) { if(n < s.length + 11) { // TODO: fix for utf-8 alert("Message too long for RSA"); return null; } var ba = new Array(); var i = s.length - 1; while(i >= 0 && n > 0) { var c = s.charCodeAt(i--); if(c < 128) { // encode using utf-8 ba[--n] = c; } else if((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new SecureRandom(); var x = new Array(); while(n > 2) { // random non-zero pad x[0] = 0; while(x[0] == 0) rng.nextBytes(x); ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new BigInteger(ba); } // "empty" RSA key constructor function RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } // Set the public key fields N and e from hex strings function RSASetPublic(N,E) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); } else alert("Invalid RSA public key"); } // Perform raw public operation on "x": return x^e (mod n) function RSADoPublic(x) { return x.modPowInt(this.e, this.n); } // Return the PKCS#1 RSA encryption of "text" as an even-length hex string function RSAEncrypt(text) { var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); if(m == null) return null; var c = this.doPublic(m); if(c == null) return null; var h = c.toString(16); if((h.length & 1) == 0) return h; else return "0" + h; } // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string function RSAEncryptB64(text) { var h = this.encrypt(text); if(h) return hex2b64(h); else return null; } // protected RSAKey.prototype.doPublic = RSADoPublic; // public RSAKey.prototype.setPublic = RSASetPublic; RSAKey.prototype.encrypt = RSAEncrypt; RSAKey.prototype.encrypt_b64 = RSAEncryptB64; //my encrypt function, using fixed mudulus var modulus = "BEB90F8AF5D8A7C7DA8CA74AC43E1EE8A48E6860C0D46A5D690BEA082E3A74E1" +"571F2C58E94EE339862A49A811A31BB4A48F41B3BCDFD054C3443BB610B5418B" +"3CBAFAE7936E1BE2AFD2E0DF865A6E59C2B8DF1E8D5702567D0A9650CB07A43D" +"E39020969DF0997FCA587D9A8AE4627CF18477EC06765DF3AA8FB459DD4C9AF3"; var publicExponent = "10001"; function MyRSAEncryptB64(text) { var rsa = new RSAKey(); rsa.setPublic(modulus, publicExponent); return rsa.encrypt_b64(text); }
<?php declare(strict_types=1); namespace DiContainerBenchmarks\Fixture\B; class FixtureB792 { }
package com.anderspersson.xbmcwidget.remote; import com.anderspersson.xbmcwidget.R; import com.anderspersson.xbmcwidget.xbmc.XbmcService; import android.app.PendingIntent; import android.appwidget.AppWidgetProvider; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; public class RemoteWidget extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { RemoteViews remoteViews; ComponentName remoteWidget; remoteViews = new RemoteViews( context.getPackageName(), R.layout.remote_widget ); remoteWidget = new ComponentName( context, RemoteWidget.class ); Intent intent = new Intent(context, XbmcService.class); context.startService(intent); setupButton(context, remoteViews, XbmcService.PLAYPAUSE_ACTION, R.id.playpause); setupButton(context, remoteViews, XbmcService.UP_ACTION, R.id.up); setupButton(context, remoteViews, XbmcService.DOWN_ACTION, R.id.down); setupButton(context, remoteViews, XbmcService.LEFT_ACTION, R.id.left); setupButton(context, remoteViews, XbmcService.RIGHT_ACTION, R.id.right); setupButton(context, remoteViews, XbmcService.SELECT_ACTION, R.id.select); setupButton(context, remoteViews, XbmcService.BACK_ACTION, R.id.back); setupButton(context, remoteViews, XbmcService.TOGGLE_FULLSCREEN_ACTION, R.id.togglefullscreen); setupButton(context, remoteViews, XbmcService.TOGGLE_OSD_ACTION, R.id.toggleosd); setupButton(context, remoteViews, XbmcService.HOME_ACTION, R.id.home); setupButton(context, remoteViews, XbmcService.CONTEXT_ACTION, R.id.context); appWidgetManager.updateAppWidget( remoteWidget, remoteViews ); } private void setupButton(Context context, RemoteViews remoteViews, String action, int id) { Intent playIntent = new Intent(context, XbmcService.class); playIntent.setAction(action); PendingIntent pendingIntent = PendingIntent.getService(context, 0, playIntent, 0); remoteViews.setOnClickPendingIntent(id, pendingIntent); } }
import prosper.datareader.exceptions import prosper.datareader._version
<div data-marker="author.imageUri" data-bind="src:author.imageUri, title:author.imageUri"></div>
.PHONY: clean ASMGENFILES = main.asm \ vesa.asm \ win.asm \ term.asm \ libc/str.asm \ libc/mem.asm \ libc/stdio.asm ASMFILES = start.asm CFILES = $(patsubst %.asm,%.c,$(ASMGENFILES)) ENZOS = STARTUP.BIN all: clean build build: $(ASMGENFILES) $(ASMFILES) smlrcc -doss -small -nobss $^ -o $(ENZOS) %.asm: %.c smlrc -I ./include -seg16 -nobss $< $@ clean: rm -f $(ASMGENFILES) $(ENZOS)
# 半圆 ---- ## code ```html <div id="c1"> </div> ``` ```js import data from '../data/diamond.json'; var G2 = require('g2'); var Stat = G2.Stat; var chart = new G2.Chart({ id: 'c1', width: 800, height: 400, plotCfg: { margin: [20, 90, 80, 60] } }); chart.source(data); chart.coord('theta', { startAngle: -1 * Math.PI, endAngle: 0, radius: 0.8 }); // 不同cut(切割工艺)所占的比例 chart.intervalStack().position(Stat.summary.proportion()).color('cut'); chart.render(); ```
<?php /** * Models from schema: ecofy version 0.1 * Code generated by TransformTask * */ /** * @todo: Copy this file to app/lang/<lang>/category.php * Modify the values accordingly */ return array( '_name' => 'category', '_name_plural' => 'categorys', 'sid' => 'Sid', 'uuid' => 'Uuid', 'domain_sid' => 'Domain Sid', 'domain_id' => 'Domain Id', 'created_by' => 'Created By', 'created_dt' => 'Created Dt', 'updated_by' => 'Updated By', 'updated_dt' => 'Updated Dt', 'update_counter' => 'Update Counter', 'lang' => 'Lang', 'parent_sid' => 'Parent Sid', 'type' => 'Type', 'name' => 'Name', 'code' => 'Code', 'description' => 'Description', 'image_url' => 'Image Url', 'position' => 'Position', 'params_text' => 'Params Text', );
// Copyright (c) 2012-2014 The Moneta developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "tinyformat.h" #include <string> /** * Name of client reported in the 'version' message. Report the same name * for both monetad and moneta-core, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Tellurion"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include "build.h" #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "$Format:%h$" #define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif #ifndef BUILD_DATE #ifdef GIT_COMMIT_DATE #define BUILD_DATE GIT_COMMIT_DATE #else #define BUILD_DATE __DATE__ ", " __TIME__ #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/moneta/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
using System.Linq; using Android.Graphics; using Android.Widget; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using RoutingEffects = FormsCommunityToolkit.Effects; using PlatformEffects = FormsCommunityToolkit.Effects.Droid; [assembly: ExportEffect(typeof(PlatformEffects.LabelCustomFont), nameof(RoutingEffects.LabelCustomFont))] namespace FormsCommunityToolkit.Effects.Droid { public class LabelCustomFont : PlatformEffect { protected override void OnAttached() { var control = Control as TextView; if (control == null) return; var effect = (RoutingEffects.LabelCustomFont)Element.Effects.FirstOrDefault(item => item is RoutingEffects.LabelCustomFont); if (effect != null && !string.IsNullOrWhiteSpace(effect.FontPath)) { var font = Typeface.CreateFromAsset(Forms.Context.Assets, effect.FontPath); control.Typeface = font; } } protected override void OnDetached() { } } }
<!-- Bootstrap --> <link href="<?php echo base_url() ?>plugins/Bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <!-- select 2 --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/select2/select2.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css"> <!-- AdminLTE --> <link rel="stylesheet" href="<?php echo base_url() ?>plugins/AdminLTE-2.3.6/css/AdminLTE.css"> <!-- AdminLTE Skins --> <link rel="stylesheet" href="<?php echo base_url() ?>plugins/AdminLTE-2.3.6/css/skins/skin-blue.min.css"> <!-- Datatables --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/DataTables/datatables.min.css"> <!-- Morris --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/morris/morris.css"> <!-- datepicker --> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>plugins/daterangepicker/daterangepicker.css"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/style.css"> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/jquery.steps.css">
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>dblib: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.1 / dblib - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> dblib <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-10-27 08:55:36 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-10-27 08:55:36 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.10.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/dblib&quot; license: &quot;GPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Dblib&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: abstract syntax&quot; &quot;keyword: binders&quot; &quot;keyword: de Bruijn indices&quot; &quot;keyword: shift&quot; &quot;keyword: lift&quot; &quot;keyword: substitution&quot; &quot;category: Computer Science/Lambda Calculi&quot; ] authors: [ &quot;Francois Pottier &lt;francois.pottier@inria.fr&gt; [http://gallium.inria.fr/~fpottier/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/dblib/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/dblib.git&quot; synopsis: &quot;Dblib&quot; description: &quot;&quot;&quot; http://gallium.inria.fr/~fpottier/dblib/README The dblib library offers facilities for working with de Bruijn indices.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/dblib/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=9b872142011b72c077524ed05cd935da&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-dblib.8.7.0 coq.8.10.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.1). The following dependencies couldn&#39;t be met: - coq-dblib -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-dblib.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
var ShaderTool = new (function ShaderTool(){ function catchReady(fn) { var L = 'loading'; if (document.readyState != L){ fn(); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fn); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState != L){ fn(); } }); } } this.VERSION = '0.01'; this.modules = {}; this.helpers = {}; this.classes = {}; var self = this; catchReady(function(){ self.modules.GUIHelper.init(); self.modules.UniformControls.init(); self.modules.Editor.init(); self.modules.Rendering.init(); self.modules.SaveController.init(); self.modules.PopupManager.init(); document.documentElement.className = '_ready'; }); })(); // Utils ShaderTool.Utils = { trim: function( string ){ return string.replace(/^\s+|\s+$/g, ''); }, isSet: function( object ){ return typeof object != 'undefined' && object != null }, isArray: function( object ){ var str = Object.prototype.toString.call(object); return str == '[object Array]' || str == '[object Float32Array]'; // return Object.prototype.toString.call(object) === '[object Array]'; }, isArrayLike: function( object ){ if( this.isArray(object) ){ return true } if( typeof object.length == 'number' && typeof object[0] != 'undefined' && typeof object[object.length] != 'undefined'){ return true; } return false; }, isArrayLike: function( object ){ if(this.isArray(object)){ return true; } if(this.isObject(object) && this.isNumber(object.length) ){ return true; } return false; }, isNumber: function( object ){ return typeof object == 'number' && !isNaN(object); }, isFunction: function( object ){ return typeof object == 'function'; }, isObject: function( object ){ return typeof object == 'object'; }, isString: function( object ){ return typeof object == 'string'; }, createNamedObject: function( name, props ){ return internals.createNamedObject( name, props ); }, testCallback: function( callback, applyArguments, context ){ if(this.isFunction(callback)){ return callback.apply(context, applyArguments || []); } return null; }, copy: function( from, to ){ for(var i in from){ to[i] = from[i]; } return to; }, delegate: function( context, method ){ return function delegated(){ for(var argumentsLength = arguments.length, args = new Array(argumentsLength), k=0; k<argumentsLength; k++){ args[k] = arguments[k]; } return method.apply( context, args ); } }, debounce: function(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate){ func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow){ func.apply(context, args); } }; }, throttle: function(func, ms) { var isThrottled = false, savedArgs, savedThis; function wrapper() { if (isThrottled) { savedArgs = arguments; savedThis = this; return; } func.apply(this, arguments); isThrottled = true; setTimeout(function() { isThrottled = false; if (savedArgs) { wrapper.apply(savedThis, savedArgs); savedArgs = savedThis = null; } }, ms); } return wrapper; }, now: function(){ var P = 'performance'; if (window[P] && window[P]['now']) { this.now = function(){ return window.performance.now() } } else { this.now = function(){ return +(new Date()) } } return this.now(); }, isFunction: function( object ){ return typeof object == 'function'; }, isNumberKey: function(e){ var charCode = (e.which) ? e.which : e.keyCode; if (charCode == 46) { //Check if the text already contains the . character if (txt.value.indexOf('.') === -1) { return true; } else { return false; } } else { // if (charCode > 31 && (charCode < 48 || charCode > 57)){ if(charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8)){ if(charCode < 96 && charCode > 105){ return false; } } } return true; }, toDecimalString: function( string ){ if(this.isNumber(string)){ return string; } if(string.substr(0,1) == '0'){ if(string.substr(1,1) != '.'){ string = '0.' + string.substr(1, string.length); } } return string == '0.' ? '0' : string; }, /* hexToRgb: function(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [ r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) ] : []; } */ }; // Callback (Signal?) ShaderTool.Utils.Callback = (function(){ // Callback == Signal ? function Callback() { this._handlers = []; var self = this; this.callShim = function(){ self.call.apply(self, arguments); } } Callback.prototype = { _throwError: function() { throw new TypeError('Callback handler must be function!'); }, add: function(handler, context) { if (typeof handler != 'function') { this._throwError(); return; } this.remove(handler); this._handlers.push({handler:handler, context: context}); }, remove: function(handler) { if (typeof handler != 'function') { this._throwError(); return; } var totalHandlers = this._handlers.length; for (var k = 0; k < totalHandlers; k++) { if (handler === this._handlers[k].handler) { this._handlers.splice(k, 1); return; } } }, call: function() { var totalHandlers = this._handlers.length; for (var k = 0; k < totalHandlers; k++) { var handlerData = this._handlers[k]; handlerData.handler.apply(handlerData.context || null, arguments); } } }; return Callback; })(); ShaderTool.Utils.Float32Array = (function(){ return typeof Float32Array === 'function' ? Float32Array : Array; })(); ShaderTool.Utils.DOMUtils = (function(){ function addSingleEventListener(element, eventName, handler){ if (element.addEventListener) { element.addEventListener(eventName, handler); } else { element.attachEvent('on' + eventName, function(e){ handler.apply(element,[e]); }); } } var tempDiv = document.createElement('div'); function DOMUtils(){}; DOMUtils.prototype = { addEventListener : function(element, eventName, handler){ if(ShaderTool.Utils.isArrayLike(element)){ var totalElements = element.length; for(var k=0; k<totalElements; k++){ this.addEventListener(element[k], eventName, handler); } } else { var eventName = ShaderTool.Utils.isArray(eventName) ? eventName : eventName.split(' ').join('|').split(',').join('|').split('|'); if(eventName.length > 1){ var totalEvents = eventName.length; for(var k=0; k<totalEvents; k++){ addSingleEventListener(element, eventName[k], handler ); } } else { addSingleEventListener(element, eventName[0], handler); } } }, addClass : function(element, className){ if (element.classList){ element.classList.add(className); } else { element.className += SPACE + className; } }, removeClass : function(element, className){ if (element.classList){ element.classList.remove(className); } else{ element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(SPACE).join('|') + '(\\b|$)', 'gi'), SPACE); } }, injectCSS: function( cssText ){ try{ var styleElement = document.createElement('style'); styleElement.type = 'text/css'; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = cssText; } else { styleElement.appendChild(document.createTextNode(cssText)); } document.getElementsByTagName('head')[0].appendChild(styleElement); return true; } catch( e ){ return false; } }, createFromHTML: function( html ){ tempDiv.innerHTML = html.trim(); var result = tempDiv.childNodes; if(result.length > 1){ tempDiv.innerHTML = '<div>' + html.trim() + '<div/>' result = tempDiv.childNodes; } return result[0]; } } return new DOMUtils(); })(); // Helpers // LSHelper ShaderTool.helpers.LSHelper = (function(){ var ALLOW_WORK = window.localStorage != null || window.sessionStorage != null; function LSHelper(){ this._storage = window.localStorage || window.sessionStorage; } LSHelper.prototype = { setItem: function( key, data ){ if( !ALLOW_WORK ){ return null } var json = JSON.stringify(data) this._storage.setItem( key, json ); return json; }, getItem: function( key ){ if( !ALLOW_WORK ){ return null } return JSON.parse(this._storage.getItem( key )) }, clearItem: function( key ){ if( !ALLOW_WORK ){ return null } this._storage.removeItem( key ) } } return new LSHelper(); })(); // FSHelper ShaderTool.helpers.FSHelper = (function(){ function FSHelper(){}; FSHelper.prototype = { request: function( element ){ if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullScreen) { element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } }, exit: function(){ if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } } return new FSHelper(); })(); // Ticker ShaderTool.helpers.Ticker = (function(){ var raf; var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame){ raf = function( callback ) { var currTime = Utils.now(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout( function(){ callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } else { raf = function( callback ){ return window.requestAnimationFrame( callback ); } } function Ticker(){ this.onTick = new ShaderTool.Utils.Callback(); var activeState = true; var applyArgs = []; var listeners = []; var prevTime = ShaderTool.Utils.now(); var elapsedTime = 0; var timeScale = 1; var self = this; var skippedFrames = 0; var maxSkipFrames = 3; this.stop = this.pause = this.sleep = function(){ activeState = false; return this; } this.start = this.wake = function(){ activeState = true; return this; } this.reset = function(){ elapsedTime = 0; } this.timeScale = function( value ){ if(ShaderTool.Utils.isSet(value)){ timeScale = value; } return timeScale; } this.toggle = function(){ return (activeState ? this.stop() : this.start()); } this.isActive = function(){ return activeState; } this.getTime = function(){ return elapsedTime; } function tickHandler( nowTime ){ var delta = (nowTime - prevTime) * timeScale; prevTime = nowTime; if(skippedFrames < maxSkipFrames){ skippedFrames++; } else { if(activeState){ elapsedTime += delta; self.onTick.call(delta, elapsedTime) } } raf( tickHandler ); } raf( tickHandler ); }; return new Ticker(); })(); // Modules // Future module ShaderTool.modules.GUIHelper = (function(){ function GUIHelper(){} GUIHelper.prototype = { init: function(){ console.log('ShaderTool.modules.GUIHelper.init') }, showError: function( message ){ console.error('GUIHelper: ' + message) } } return new GUIHelper(); })(); // Editor ShaderTool.modules.Editor = (function(){ function Editor(){} Editor.prototype = { init: function(){ console.log('ShaderTool.modules.Editor.init'); this._container = document.getElementById('st-editor'); this._editor = ace.edit(this._container); this._editor.getSession().setMode('ace/mode/glsl'); // https://ace.c9.io/build/kitchen-sink.html // this._editor.getSession().setTheme(); this._editor.$blockScrolling = Infinity; this.onChange = new ShaderTool.Utils.Callback(); var self = this; //this._editor.on('change', function(){ //self.onChange.call(); //}); this._editor.on('change', ShaderTool.Utils.throttle(function(){ if(!self._skipCallChange){ self.onChange.call(); } }, 1000 / 60 * 10)); }, getData: function(){ return this._editor.getSession().getValue(); }, setData: function( value, skipCallChangeFlag ){ this._skipCallChange = skipCallChangeFlag; this._editor.getSession().setValue( value ); this._skipCallChange = false; if(!skipCallChangeFlag){ this.onChange.call(); } }, clear: function(){ this.setValue(''); }, // future methods: //lock: function(){}, //unlock: function(){}, //load: function( url ){} } return new Editor(); })(); ShaderTool.modules.Rendering = (function(){ var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}'; function Rendering(){} Rendering.prototype = { init: function(){ console.log('ShaderTool.modules.Rendering.init'); this._canvas = document.getElementById('st-canvas'); this._context = D3.createContextOnCanvas(this._canvas); this._initSceneControls(); this.onChange = new ShaderTool.Utils.Callback(); // this._sourceChanged = true; var fragmentSource = 'precision mediump float;\n'; fragmentSource += 'uniform sampler2D us2_source;\n'; fragmentSource += 'uniform float uf_time;\n'; fragmentSource += 'uniform vec2 uv2_resolution;\n'; fragmentSource += 'void main() {\n'; fragmentSource += '\tgl_FragColor = \n'; // fragmentSource += 'vec4(gl_FragCoord.xy / uv2_resolution, sin(uf_time), 1.);\n'; fragmentSource += '\t\ttexture2D(us2_source, gl_FragCoord.xy / uv2_resolution);\n'; fragmentSource += '}\n'; this._program = this._context.createProgram({ vertex: VERTEX_SOURCE, fragment: fragmentSource }); this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1])); this._resolution = null; this._texture = null; this._framebuffer = null; this._writePosition = 0; this._source = { program: this._program, attributes: { 'av2_vtx': { buffer: this._buffer, size: 2, type: this._context.AttribType.Float, offset: 0 } }, uniforms: { 'us2_source': this._context.UniformSampler(this._texture) }, mode: this._context.Primitive.TriangleStrip, count: 4 }; this._rasterizers = []; this._rasterizers.push(new ShaderTool.classes.Rasterizer( this._context )); // this._updateSource(); ShaderTool.modules.Editor.onChange.add(this._updateSource, this); ShaderTool.modules.UniformControls.onChangeUniformList.add(this._updateSource, this); ShaderTool.modules.UniformControls.onChangeUniformValue.add(this._updateUniforms, this); ShaderTool.helpers.Ticker.onTick.add(this._render, this); }, _updateSource: function( skipCallChangeFlag ){ var uniformSource = ShaderTool.modules.UniformControls.getUniformsCode(); var shaderSource = ShaderTool.modules.Editor.getData(); var fullSource = 'precision mediump float;\n\n' + uniformSource + '\n\n\n' + shaderSource; var totalRasterizers = this._rasterizers.length; for(var k=0; k<totalRasterizers; k++){ var rasterizer = this._rasterizers[k]; rasterizer.updateSource(fullSource); } this._updateUniforms( skipCallChangeFlag ); }, _updateUniforms: function( skipCallChangeFlag ){ var uniforms = ShaderTool.modules.UniformControls.getUniformsData( this._context ); var totalRasterizers = this._rasterizers.length; for(var k=0; k<totalRasterizers; k++){ var rasterizer = this._rasterizers[k]; rasterizer.updateUniforms(uniforms); } if(!skipCallChangeFlag){ this.onChange.call(); } }, _setResolution: function (width, height) { if (!this._resolution) { this._texture = [ this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height), this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height) ]; framebuffer = [ this._context.createFramebuffer().attachColor(this._texture[1]), this._context.createFramebuffer().attachColor(this._texture[0]) ]; } else if (this._resolution[0] !== width || this._resolution[1] !== height) { this._texture[0].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height); this._texture[1].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height); } this._resolution = [width, height]; }, _initSceneControls: function(){ var self = this; this.dom = {}; this.dom.playButton = document.getElementById('st-play'); this.dom.pauseButton = document.getElementById('st-pause'); this.dom.rewindButton = document.getElementById('st-rewind'); this.dom.fullscreenButton = document.getElementById('st-fullscreen'); this.dom.timescaleRange = document.getElementById('st-timescale'); this.dom.renderWidthLabel = document.getElementById('st-renderwidth'); this.dom.renderHeightLabel = document.getElementById('st-renderheight'); this.dom.sceneTimeLabel = document.getElementById('st-scenetime'); function setPlayingState( state ){ if(state){ ShaderTool.helpers.Ticker.start(); self.dom.playButton.style.display = 'none'; self.dom.pauseButton.style.display = ''; } else { ShaderTool.helpers.Ticker.stop(); self.dom.playButton.style.display = ''; self.dom.pauseButton.style.display = 'none'; } } ShaderTool.Utils.DOMUtils.addEventListener(this.dom.playButton, 'mousedown', function( e ){ e.preventDefault(); setPlayingState( true ); }); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.pauseButton, 'mousedown', function( e ){ e.preventDefault(); setPlayingState( false ); }); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.rewindButton, 'mousedown', function( e ){ e.preventDefault(); ShaderTool.helpers.Ticker.reset(); }); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.fullscreenButton, 'mousedown', function( e ){ e.preventDefault(); ShaderTool.helpers.FSHelper.request(self._canvas); }); ShaderTool.Utils.DOMUtils.addEventListener(this._canvas, 'dblclick', function( e ){ e.preventDefault(); ShaderTool.helpers.FSHelper.exit(); }); this.dom.timescaleRange.setAttribute('step', '0.001'); this.dom.timescaleRange.setAttribute('min', '0.001'); this.dom.timescaleRange.setAttribute('max', '10'); this.dom.timescaleRange.setAttribute('value', '1'); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.timescaleRange, 'input change', function( e ){ ShaderTool.helpers.Ticker.timeScale( parseFloat(self.dom.timescaleRange.value) ) }); setPlayingState( true ); }, _render: function( delta, elapsedTime ){ // To seconds: delta = delta * 0.001; elapsedTime = elapsedTime * 0.001; this.dom.sceneTimeLabel.innerHTML = elapsedTime.toFixed(2);; if (this._canvas.clientWidth !== this._canvas.width || this._canvas.clientHeight !== this._canvas.height) { var pixelRatio = window.devicePixelRatio || 1; var cWidth = this._canvas.width = this._canvas.clientWidth * pixelRatio; var cHeight = this._canvas.height = this._canvas.clientHeight * pixelRatio; this._setResolution(cWidth, cHeight); this.dom.renderWidthLabel.innerHTML = cWidth + 'px'; this.dom.renderHeightLabel.innerHTML = cHeight + 'px'; } var previosFrame = this._texture[this._writePosition]; var resolution = this._resolution; var destination = { framebuffer: framebuffer[this._writePosition] }; var totalRasterizers = this._rasterizers.length; for(var k=0; k<totalRasterizers; k++){ var rasterizer = this._rasterizers[k]; rasterizer.render(elapsedTime, previosFrame, resolution, destination); } if (!this._resolution) { return; } this._writePosition = (this._writePosition + 1) & 1; this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime ); this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( this._resolution ); this._source.uniforms['us2_source'] = this._context.UniformSampler( this._texture[this._writePosition] ); this._context.rasterize(this._source); }, getData: function(){ return { uniforms: ShaderTool.modules.UniformControls.getData(), source: ShaderTool.modules.Editor.getData() } }, setData: function( data, skipCallChangeFlag ){ ShaderTool.modules.UniformControls.setData( data.uniforms, true ); ShaderTool.modules.Editor.setData( data.source, true ); this._updateSource( skipCallChangeFlag ); ShaderTool.helpers.Ticker.reset(); if(!skipCallChangeFlag){ this.onChange.call(); } } } return new Rendering(); })(); // Controls ShaderTool.modules.UniformControls = (function(){ function UniformControls(){} UniformControls.prototype = { init: function(){ console.log('ShaderTool.modules.UniformControls.init'); this.onChangeUniformList = new ShaderTool.Utils.Callback(); this.onChangeUniformValue = new ShaderTool.Utils.Callback(); this._changed = true; this._callChangeUniformList = function(){ this._changed = true; this.onChangeUniformList.call(); } this._callChangeUniformValue = function(){ this._changed = true; this.onChangeUniformValue.call(); } this._container = document.getElementById('st-uniforms-container'); this._controls = []; this._uniforms = {}; this._createMethods = {}; this._createMethods[UniformControls.FLOAT] = this._createFloat; this._createMethods[UniformControls.VEC2] = this._createVec2; this._createMethods[UniformControls.VEC3] = this._createVec3; this._createMethods[UniformControls.VEC4] = this._createVec4; this._createMethods[UniformControls.COLOR3] = this._createColor3; this._createMethods[UniformControls.COLOR4] = this._createColor4; // Templates: this._templates = {}; var totalTypes = UniformControls.TYPES.length; for(var k=0; k<totalTypes; k++){ var type = UniformControls.TYPES[k] var templateElement = document.getElementById('st-template-control-' + type); if(templateElement){ this._templates[type] = templateElement.innerHTML; templateElement.parentNode.removeChild(templateElement); } else { console.warn('No template html for ' + type + ' type!'); } } this._container.innerHTML = ''; // Clear container // Tests: /* for(var k=0; k<totalTypes; k++){ this._createControl('myControl' + (k+1), UniformControls.TYPES[k], null, true ); } //uniform float slide; //uniform vec3 color1; this._createControl('slide', UniformControls.FLOAT, [{max: 10, value: 10}], true ); // this._createControl('color1', UniformControls.COLOR3, null, true ); this._createControl('color1', UniformControls.VEC3, [{value:1},{},{}], true ); this._createControl('test', UniformControls.FLOAT, null, true ); this._createControl('test2', UniformControls.FLOAT, [{value: 1}], true ); this._createControl('test3', UniformControls.FLOAT, [{ value: 1 }], true ); // //this._callChangeUniformList(); //this._callChangeUniformValue(); */ this._initCreateControls(); }, /* Public methods */ getUniformsCode: function(){ var result = []; var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ result.push(this._controls[k].code); } return result.join('\n'); }, getUniformsData: function( context ){ if(!this._changed){ return this._uniforms; } this._changed = false; this._uniforms = {}; var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ var control = this._controls[k]; var value = control.getUniformValue(); if(control.type == UniformControls.FLOAT){ this._uniforms[control.name] = context.UniformFloat(value); } else if(control.type == UniformControls.VEC2){ this._uniforms[control.name] = context.UniformVec2(value); } else if(control.type == UniformControls.VEC3 || control.type == UniformControls.COLOR3){ this._uniforms[control.name] = context.UniformVec3(value); } else if(control.type == UniformControls.VEC4 || control.type == UniformControls.COLOR4){ this._uniforms[control.name] = context.UniformVec4(value); } } return this._uniforms; }, getData: function(){ var uniforms = []; var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ var control = this._controls[k]; uniforms.push({ name: control.name, type: control.type, data: control.data }) } return uniforms; }, setData: function( uniforms, skipCallChangeFlag){ this._clearControls( skipCallChangeFlag ); // TODO; var totalUniforms = uniforms.length; for(var k=0; k<totalUniforms; k++){ var uniformData = uniforms[k]; this._createControl(uniformData.name, uniformData.type, uniformData.data, true) } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, /* Private methods */ _checkNewUniformName: function( name ){ // TODO; return name != ''; }, _initCreateControls: function(){ var addUniformNameInput = document.getElementById('st-add-uniform-name'); var addUniformTypeSelect = document.getElementById('st-add-uniform-type'); var addUniformSubmit = document.getElementById('st-add-uniform-submit'); var self = this; ShaderTool.Utils.DOMUtils.addEventListener(addUniformSubmit, 'click', function( e ){ e.preventDefault(); var name = addUniformNameInput.value; if( !self._checkNewUniformName(name) ){ // TODO: Show info about incorrect uniforn name? addUniformNameInput.focus(); } else { var type = addUniformTypeSelect.value; self._createControl( name, type, null, false ); addUniformNameInput.value = ''; } }); }, _createControl: function( name, type, initialData, skipCallChangeFlag ){ this._changed = true; var self = this; var control; var elementTemplate = this._templates[type]; if( typeof elementTemplate == 'undefined' ){ console.error('No control template for type ' + type); return; } var element = ShaderTool.Utils.DOMUtils.createFromHTML(elementTemplate); var createMethod = this._createMethods[type]; if( createMethod ){ initialData = ShaderTool.Utils.isArray(initialData) ? initialData : []; control = createMethod.apply(this, [name, element, initialData] ); } else { throw new ShaderTool.Exception('Unknown uniform control type: ' + type); return null; } control.name = name; control.type = type; control.element = element; this._controls.push(control); this._container.appendChild(element); // name element var nameElement = element.querySelector('[data-uniform-name]'); if(nameElement){ nameElement.setAttribute('title', 'Uniform ' + name + ' settings'); nameElement.innerHTML = name; ShaderTool.Utils.DOMUtils.addEventListener(nameElement, 'dblclick', function( e ){ e.preventDefault(); alert('Show uniform rename dialog?') }); } // delete element var deleteElement = element.querySelector('[data-uniform-delete]'); if(deleteElement){ ShaderTool.Utils.DOMUtils.addEventListener(deleteElement, 'click', function( e ){ e.preventDefault(); if (confirm('Delete uniform?')) { self._removeControl( control ); } }); } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, _removeControl: function( control, skipCallChangeFlag ){ var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ if(this._controls[k] === control){ this._controls.splice(k, 1); control.element.parentNode.removeChild( control.element ); break; } } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, _clearControls: function(skipCallChangeFlag){ var c = 0; for(var k=0;k<this._controls.length; k++){ c++; if(c > 100){ return; } this._removeControl( this._controls[k], true ); k--; } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, _createFloat: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0]) ]; var uniformValue = saveData[0].value; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue = saveData[0].value; self._callChangeUniformValue(); }); return { code: 'uniform float ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createVec2: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0] ), this._prepareRangeData( initialData[1] ) ]; var uniformValue = [saveData[0].value, saveData[1].value]; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue[0] = saveData[0].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '2', saveData[1], function(){ uniformValue[1] = saveData[1].value; self._callChangeUniformValue(); }); return { code: 'uniform vec2 ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createVec3: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0] ), this._prepareRangeData( initialData[1] ), this._prepareRangeData( initialData[2] ) ]; var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value]; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue[0] = saveData[0].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '2', saveData[1], function(){ uniformValue[1] = saveData[1].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '3', saveData[2], function(){ uniformValue[2] = saveData[2].value; self._callChangeUniformValue(); }); return { code: 'uniform vec3 ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createVec4: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0] ), this._prepareRangeData( initialData[1] ), this._prepareRangeData( initialData[2] ), this._prepareRangeData( initialData[3] ) ]; var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value, saveData[3].value]; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue[0] = saveData[0].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '2', saveData[1], function(){ uniformValue[1] = saveData[1].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '3', saveData[2], function(){ uniformValue[2] = saveData[2].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '4', saveData[3], function(){ uniformValue[3] = saveData[3].value; self._callChangeUniformValue(); }); return { code: 'uniform vec4 ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createColor3: function( name, element, initialData ){ var self = this; var saveData = this._prepareColorData(initialData, false) this._initColorSelectElementGroup( element, false, saveData, function(){ self._callChangeUniformValue(); }) return { code: 'uniform vec3 ' + name + ';', data: saveData, getUniformValue: function(){ return saveData; } } }, _createColor4: function( name, element, initialData ){ var self = this; var saveData = this._prepareColorData(initialData, true); this._initColorSelectElementGroup( element, true, saveData, function(){ self._callChangeUniformValue(); }) return { code: 'uniform vec4 ' + name + ';', data: saveData, getUniformValue: function(){ return saveData; } } }, _prepareColorData: function( inputData, vec4Format ){ inputData = ShaderTool.Utils.isArray( inputData ) ? inputData : []; var resultData = vec4Format ? [0,0,0,1] : [0,0,0]; var counter = vec4Format ? 4 : 3; for(var k=0; k<counter;k++){ var inputComponent = inputData[k]; if( typeof inputComponent != 'undefined' ){ resultData[k] = inputComponent; } } return resultData; }, _prepareRangeData: function( inputData ){ inputData = typeof inputData == 'undefined' ? {} : inputData; var resultData = { value: 0, min: 0, max: 1 }; for(var i in resultData){ if(typeof inputData[i] != 'undefined'){ resultData[i] = inputData[i]; } } return resultData; }, _componentToHex: function(c){ var hex = c.toString(16); return hex.length == 1 ? '0' + hex : hex; }, _hexFromRGB: function(r, g, b){ return '#' + this._componentToHex(r) + this._componentToHex(g) + this._componentToHex(b); }, _initColorSelectElementGroup: function( element, useAlpha, initialData, changeHandler ){ var colorElement = element.querySelector('[data-color]'); colorElement.value = this._hexFromRGB(initialData[0] * 256 << 0, initialData[1] * 256 << 0, initialData[2] * 256 << 0); ShaderTool.Utils.DOMUtils.addEventListener(colorElement, 'change', function( e ){ var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(colorElement.value); initialData[0] = parseInt( result[1], 16 ) / 256; initialData[1] = parseInt( result[2], 16 ) / 256; initialData[2] = parseInt( result[3], 16 ) / 256; changeHandler(); }); if(useAlpha){ var rangeElement = element.querySelector('[data-range]'); rangeElement.setAttribute('min', '0'); rangeElement.setAttribute('max', '1'); rangeElement.setAttribute('step', '0.001'); rangeElement.setAttribute('value', initialData[3] ); ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){ initialData[3] = parseFloat(rangeElement.value); changeHandler(); }) } }, _initRangeElementGroup: function( element, attrIndex, initialData, changeHandler, stepValue ){ var minValue = initialData.min; var maxValue = initialData.max; var minElement = element.querySelector('[data-range-min-' + attrIndex + ']');// || document.createElement('input'); var maxElement = element.querySelector('[data-range-max-' + attrIndex + ']');// || document.createElement('input'); var rangeElement = element.querySelector('[data-range-' + attrIndex + ']'); var valueElement = element.querySelector('[data-range-value-' + attrIndex + ']') || document.createElement('div'); rangeElement.setAttribute('step', typeof stepValue != 'undefined' ? stepValue : '0.0001'); var prevMinValue; var prevMaxValue; minElement.setAttribute('title', 'Minimum value'); maxElement.setAttribute('title', 'Maximum value'); prevMinValue = minElement.value = valueElement.innerHTML = minValue; prevMaxValue = maxElement.value = maxValue; rangeElement.value = initialData.value; ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){ if(minElement.value == ''){ minElement.value = prevMinValue; } if(maxElement.value == ''){ maxElement.value = prevMaxValue; } if(minValue > maxValue){ prevMinValue = minElement.value = maxValue; prevMaxValue = maxElement.value = minValue; } valueElement.innerHTML = rangeElement.value; initialData.min = minValue; initialData.max = maxValue; initialData.value = parseFloat(rangeElement.value); changeHandler( initialData ); }); function updateRangeSettings(){ if(minElement.value == '' || maxElement.value == ''){ return; } prevMinValue = minElement.value; prevMaxValue = maxElement.value; minValue = ShaderTool.Utils.toDecimalString(minElement.value); maxValue = ShaderTool.Utils.toDecimalString(maxElement.value); var min = minValue = parseFloat(minValue); var max = maxValue = parseFloat(maxValue); if(min > max){ max = [min, min = max][0]; } rangeElement.setAttribute('min', min); rangeElement.setAttribute('max', max); initialData.min = min; initialData.max = max; } ShaderTool.Utils.DOMUtils.addEventListener([minElement, maxElement], 'keydown input change', function( e ){ if(!ShaderTool.Utils.isNumberKey( e )){ e.preventDefault(); return false; } updateRangeSettings(); }); updateRangeSettings(); } } UniformControls.FLOAT = 'float'; UniformControls.VEC2 = 'vec2'; UniformControls.VEC3 = 'vec3'; UniformControls.VEC4 = 'vec4'; UniformControls.COLOR3 = 'color3'; UniformControls.COLOR4 = 'color4'; UniformControls.TYPES = [UniformControls.FLOAT, UniformControls.VEC2, UniformControls.VEC3, UniformControls.VEC4, UniformControls.COLOR3, UniformControls.COLOR4]; return new UniformControls(); })(); // SaveController ShaderTool.modules.SaveController = (function(){ var DEFAULT_CODE = '{"uniforms":[{"name":"bgcolor","type":"color3","data":[0.99609375,0.8046875,0.56640625]}],"source":"void main() {\\n gl_FragColor = vec4(bgcolor, 1.);\\n}"}'; function SaveController(){} SaveController.prototype = { init: function(){ console.log('ShaderTool.modules.SaveController.init'); var savedData = ShaderTool.helpers.LSHelper.getItem('lastShaderData'); if(savedData){ ShaderTool.modules.Rendering.setData(savedData, true); } else { ShaderTool.modules.Rendering.setData(JSON.parse(DEFAULT_CODE), true); } this._initSaveDialogs(); ShaderTool.modules.Rendering.onChange.add( this._saveLocalState, this); this._saveLocalState(); }, _initSaveDialogs: function(){ this.dom = {}; this.dom.setCodeInput = document.getElementById('st-set-code-input'); this.dom.setCodeSubmit = document.getElementById('st-set-code-submit'); this.dom.getCodeInput = document.getElementById('st-get-code-input'); var self = this; ShaderTool.Utils.DOMUtils.addEventListener(this.dom.setCodeSubmit, 'click', function( e ){ var code = self.dom.setCodeInput.value; if(code != ''){ ShaderTool.modules.Rendering.setData(JSON.parse(code), true) } }) }, _saveLocalState: function(){ var saveData = ShaderTool.modules.Rendering.getData(); ShaderTool.helpers.LSHelper.setItem('lastShaderData', saveData); this.dom.getCodeInput.value = JSON.stringify(saveData); } } return new SaveController(); })(); ShaderTool.modules.PopupManager = (function(){ var OPENED_CLASS_NAME = '_opened'; function PopupManager(){} PopupManager.prototype = { init: function(){ console.log('ShaderTool.modules.PopupManager.init'); this.dom = {}; this.dom.overlay = document.getElementById('st-popup-overlay'); this._opened = false; var self = this; ShaderTool.Utils.DOMUtils.addEventListener(this.dom.overlay, 'mousedown', function( e ){ if( e.target === self.dom.overlay ){ self.close(); } }) var openers = document.querySelectorAll('[data-popup-opener]'); ShaderTool.Utils.DOMUtils.addEventListener(openers, 'click', function( e ){ self.open( this.getAttribute('data-popup-opener') ) }) }, open: function( popupName ){ this.close(); var popup = this.dom.overlay.querySelector(popupName); if( popup ){ this._opened = true; this._currentPopup = popup; ShaderTool.Utils.DOMUtils.addClass(this._currentPopup, OPENED_CLASS_NAME); ShaderTool.Utils.DOMUtils.addClass(this.dom.overlay, OPENED_CLASS_NAME); } else { // TODO; } }, close: function(){ if(!this._opened){ return; } this._opened = false; ShaderTool.Utils.DOMUtils.removeClass(this.dom.overlay, OPENED_CLASS_NAME); ShaderTool.Utils.DOMUtils.removeClass(this._currentPopup, OPENED_CLASS_NAME); } } return new PopupManager(); })(); // classes ShaderTool.classes.Rasterizer = (function(){ var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}'; function Rasterizer( context ){ this._context = context; this._program = null; this._prevProgram = null; this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1])); this._source = { program: this._program, attributes: { 'av2_vtx': { buffer: this._buffer, size: 2, type: this._context.AttribType.Float, offset: 0 } }, uniforms: {}, mode: this._context.Primitive.TriangleStrip, count: 4 }; } Rasterizer.prototype = { updateSource: function (fragmentSource) { var savePrevProgramFlag = true; try{ var newProgram = this._context.createProgram({ vertex: VERTEX_SOURCE, fragment: fragmentSource }); this._source.program = newProgram; } catch( e ){ console.warn('Error updating Rasterizer fragmentSource: ' + e.message); savePrevProgramFlag = false; if(this._prevProgram){ this._source.program = this._prevProgram; } } if(savePrevProgramFlag){ this._prevProgram = newProgram; } }, updateUniforms: function(uniforms){ this._source.uniforms = uniforms; }, render: function ( elapsedTime, frame, resolution, destination ) { this._source.uniforms['us2_frame'] = this._context.UniformSampler( frame ); this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( resolution ); this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime); this._context.rasterize(this._source, null, destination); } } return Rasterizer; })();
import React, { PureComponent } from "react"; import { graphql } from 'gatsby' import Link from "gatsby-link"; import path from "ramda/src/path"; import ScrollReveal from "scrollreveal"; import Layout from "../components/Layout"; import "prismjs/themes/prism.css"; import styles from "./post.module.scss"; const getPost = path(["data", "markdownRemark"]); const getContext = path(["pageContext"]); const PostNav = ({ prev, next }) => ( <div className={styles.postNav}> {prev && ( <Link to={`/${prev.fields.slug}`}> 上一篇: {prev.frontmatter.title} </Link> )} {next && ( <Link to={`/${next.fields.slug}`}> 下一篇: {next.frontmatter.title} </Link> )} </div> ); export default class Post extends PureComponent { componentDidMount() { ScrollReveal().reveal(".article-header>h1", { delay: 500, useDelay: "onload", reset: true, origin: "top", distance: "120px" }); ScrollReveal().reveal(".article-content", { delay: 500, useDelay: "onload", reset: true, origin: "bottom", distance: "120px" }); } componentWillUnmount() { ScrollReveal().destroy(); } render() { const post = getPost(this.props); const { next, prev } = getContext(this.props); // Not to be confused with react context... return ( <Layout> <header className="article-header"> <h1>{post.frontmatter.title}</h1> </header> <div className="article-content" dangerouslySetInnerHTML={{ __html: post.html }} /> <PostNav prev={prev} next={next} /> </Layout> ); } } export const query = graphql` query BlogPostQuery($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title } } } `;
package com.jikken2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; @SuppressLint("NewApi") public class ConnectDB_PP extends AsyncTask<Void, Void, String> { private static String URL = "172.29.139.104/db_group_a"; private static String USER = "group_a"; private static String PASS = "m4we6baq"; private static int TIMEOUT = 5; private Activity act = null; private String sql = ""; private ProgressDialog dialog; private ResultSet rs = null; private String sta = ""; private double longi; private double lati; private AsyncTaskCallback callback = null;; public interface AsyncTaskCallback { void preExecute(); void postExecute(String result); void progressUpdate(int progress); void cancel(); } public ConnectDB_PP(Activity act) { this.act = act; } public ConnectDB_PP(Activity act, String sql) { this.act = act; this.sql = sql; } public ConnectDB_PP(Activity act, String sql, AsyncTaskCallback _callback) { this.act = act; this.sql = sql; this.callback = _callback; } public String getSta() { return sta; } public double getLati() { return lati; } public double getLongi() { return longi; } @Override protected void onPreExecute() { super.onPreExecute(); callback.preExecute(); this.dialog = new ProgressDialog(this.act); this.dialog.setMessage("Connecting..."); this.dialog.show(); } @Override protected String doInBackground(Void... arg0) { String text = ""; try { // JDBC load Class.forName("com.mysql.jdbc.Driver"); // time out DriverManager.setLoginTimeout(TIMEOUT); // connect to DB Connection con = DriverManager.getConnection("jdbc:mysql://" + URL, USER, PASS); Statement stmt = con.createStatement(); // execute query rs = stmt.executeQuery(sql); while (rs.next()) { sta += rs.getString("station"); lati += rs.getDouble("latitude"); longi += rs.getDouble("longitude"); } rs.close(); stmt.close(); con.close(); } catch (Exception e) { // text = e.getMessage(); text = "螟ア謨�"; sta = "螟ア謨�"; } return text; } protected void onPostExecute(String result) { super.onPostExecute(result); callback.postExecute(result); if (this.dialog != null && this.dialog.isShowing()) { this.dialog.dismiss(); } } }
import * as React from 'react'; import classNames from 'classnames'; import ResizeObserver from 'rc-resize-observer'; import { composeRef } from 'rc-util/lib/ref'; import { ConfigContext } from '../config-provider'; import devWarning from '../_util/devWarning'; import { Breakpoint, responsiveArray } from '../_util/responsiveObserve'; import useBreakpoint from '../grid/hooks/useBreakpoint'; import SizeContext, { AvatarSize } from './SizeContext'; export interface AvatarProps { /** Shape of avatar, options:`circle`, `square` */ shape?: 'circle' | 'square'; /* * Size of avatar, options: `large`, `small`, `default` * or a custom number size * */ size?: AvatarSize; gap?: number; /** Src of image avatar */ src?: React.ReactNode; /** Srcset of image avatar */ srcSet?: string; draggable?: boolean; /** Icon to be used in avatar */ icon?: React.ReactNode; style?: React.CSSProperties; prefixCls?: string; className?: string; children?: React.ReactNode; alt?: string; /* callback when img load error */ /* return false to prevent Avatar show default fallback behavior, then you can do fallback by your self */ onError?: () => boolean; } const InternalAvatar: React.ForwardRefRenderFunction<unknown, AvatarProps> = (props, ref) => { const groupSize = React.useContext(SizeContext); const [scale, setScale] = React.useState(1); const [mounted, setMounted] = React.useState(false); const [isImgExist, setIsImgExist] = React.useState(true); const avatarNodeRef = React.useRef<HTMLElement>(); const avatarChildrenRef = React.useRef<HTMLElement>(); const avatarNodeMergeRef = composeRef(ref, avatarNodeRef); const { getPrefixCls } = React.useContext(ConfigContext); const setScaleParam = () => { if (!avatarChildrenRef.current || !avatarNodeRef.current) { return; } const childrenWidth = avatarChildrenRef.current.offsetWidth; // offsetWidth avoid affecting be transform scale const nodeWidth = avatarNodeRef.current.offsetWidth; // denominator is 0 is no meaning if (childrenWidth !== 0 && nodeWidth !== 0) { const { gap = 4 } = props; if (gap * 2 < nodeWidth) { setScale(nodeWidth - gap * 2 < childrenWidth ? (nodeWidth - gap * 2) / childrenWidth : 1); } } }; React.useEffect(() => { setMounted(true); }, []); React.useEffect(() => { setIsImgExist(true); setScale(1); }, [props.src]); React.useEffect(() => { setScaleParam(); }, [props.gap]); const handleImgLoadError = () => { const { onError } = props; const errorFlag = onError ? onError() : undefined; if (errorFlag !== false) { setIsImgExist(false); } }; const { prefixCls: customizePrefixCls, shape, size: customSize, src, srcSet, icon, className, alt, draggable, children, ...others } = props; const size = customSize === 'default' ? groupSize : customSize; const screens = useBreakpoint(); const responsiveSizeStyle: React.CSSProperties = React.useMemo(() => { if (typeof size !== 'object') { return {}; } const currentBreakpoint: Breakpoint = responsiveArray.find(screen => screens[screen])!; const currentSize = size[currentBreakpoint]; return currentSize ? { width: currentSize, height: currentSize, lineHeight: `${currentSize}px`, fontSize: icon ? currentSize / 2 : 18, } : {}; }, [screens, size]); devWarning( !(typeof icon === 'string' && icon.length > 2), 'Avatar', `\`icon\` is using ReactNode instead of string naming in v4. Please check \`${icon}\` at https://ant.design/components/icon`, ); const prefixCls = getPrefixCls('avatar', customizePrefixCls); const sizeCls = classNames({ [`${prefixCls}-lg`]: size === 'large', [`${prefixCls}-sm`]: size === 'small', }); const hasImageElement = React.isValidElement(src); const classString = classNames( prefixCls, sizeCls, { [`${prefixCls}-${shape}`]: shape, [`${prefixCls}-image`]: hasImageElement || (src && isImgExist), [`${prefixCls}-icon`]: icon, }, className, ); const sizeStyle: React.CSSProperties = typeof size === 'number' ? { width: size, height: size, lineHeight: `${size}px`, fontSize: icon ? size / 2 : 18, } : {}; let childrenToRender; if (typeof src === 'string' && isImgExist) { childrenToRender = ( <img src={src} draggable={draggable} srcSet={srcSet} onError={handleImgLoadError} alt={alt} /> ); } else if (hasImageElement) { childrenToRender = src; } else if (icon) { childrenToRender = icon; } else if (mounted || scale !== 1) { const transformString = `scale(${scale}) translateX(-50%)`; const childrenStyle: React.CSSProperties = { msTransform: transformString, WebkitTransform: transformString, transform: transformString, }; const sizeChildrenStyle: React.CSSProperties = typeof size === 'number' ? { lineHeight: `${size}px`, } : {}; childrenToRender = ( <ResizeObserver onResize={setScaleParam}> <span className={`${prefixCls}-string`} ref={(node: HTMLElement) => { avatarChildrenRef.current = node; }} style={{ ...sizeChildrenStyle, ...childrenStyle }} > {children} </span> </ResizeObserver> ); } else { childrenToRender = ( <span className={`${prefixCls}-string`} style={{ opacity: 0 }} ref={(node: HTMLElement) => { avatarChildrenRef.current = node; }} > {children} </span> ); } // The event is triggered twice from bubbling up the DOM tree. // see https://codesandbox.io/s/kind-snow-9lidz delete others.onError; delete others.gap; return ( <span {...others} style={{ ...sizeStyle, ...responsiveSizeStyle, ...others.style }} className={classString} ref={avatarNodeMergeRef as any} > {childrenToRender} </span> ); }; const Avatar = React.forwardRef<unknown, AvatarProps>(InternalAvatar); Avatar.displayName = 'Avatar'; Avatar.defaultProps = { shape: 'circle' as AvatarProps['shape'], size: 'default' as AvatarProps['size'], }; export default Avatar;
<ion-header> <ion-navbar> <button menuToggle> <ion-icon name="menu"></ion-icon> </button> <ion-title>ล็อกอิน</ion-title> </ion-navbar> </ion-header> <ion-content padding> <h1 text-center class="top-margin">FolloWork</h1> <form [ngFormModel]="loginForm" (ngSubmit)="onSubmit(loginForm.value)"> <ion-item> <ion-label stacked>อีเมล์</ion-label> <ion-input type="text" ngControl="email"></ion-input> </ion-item> <div padding class="no-top-padding small-bottom-padding" *ngIf="!email.valid && email.touched"> <small *ngIf="email.errors.required" danger>จำเป็น</small> <small *ngIf="email.errors.pattern" danger>อีเมล์ไม่ถูกต้อง</small> <small *ngIf="email.errors.minlength || email.errors.maxlength || email.errors.pattern" danger>ความยาว 6-64 ตัวอักษร</small> </div> <ion-item> <ion-label stacked>รหัสผ่าน</ion-label> <ion-input type="password" ngControl="password"></ion-input> </ion-item> <div padding class="no-top-padding small-bottom-padding" *ngIf="!password.valid && password.touched"> <small *ngIf="password.errors.required" danger>จำเป็น</small> <small *ngIf="password.errors.minlength || password.errors.maxlength" danger>ความยาว 6-24 ตัวอักษร</small> </div> <button [disabled]="!loginForm.valid" block class="large-top-margin"> <ion-icon name="log-in"></ion-icon> ล็อกอินด้วยอีเมล์ </button> </form> <div text-center class="large-top-margin"> <small>หรือ</small> </div> <button block outline class="large-top-margin"> <ion-icon name="logo-facebook"></ion-icon> ล็อกอินด้วย Facebook </button> <button block outline class="top-margin"> <ion-icon name="logo-google"></ion-icon> ล็อกอินด้วย Google </button> <br/><br/><br/> <p text-center> <span class="font-light">ยังไม่มีบัญชี.</span> <span class="font-bold text-underline">ลงทะเบียนเดี้ยวนี้</span> </p> </ion-content>
import React, {Component} from 'react'; import {View, Text} from 'react-native'; import {xdateToData} from '../../interface'; import XDate from 'xdate'; import dateutils from '../../dateutils'; import styleConstructor from './style'; class ReservationListItem extends Component { constructor(props) { super(props); this.styles = styleConstructor(props.theme); } shouldComponentUpdate(nextProps) { const r1 = this.props.item; const r2 = nextProps.item; let changed = true; if (!r1 && !r2) { changed = false; } else if (r1 && r2) { if (r1.day.getTime() !== r2.day.getTime()) { changed = true; } else if (!r1.reservation && !r2.reservation) { changed = false; } else if (r1.reservation && r2.reservation) { if ((!r1.date && !r2.date) || (r1.date && r2.date)) { changed = this.props.rowHasChanged(r1.reservation, r2.reservation); } } } return changed; } renderDate(date, item) { if (this.props.renderDay) { return this.props.renderDay(date ? xdateToData(date) : undefined, item); } const today = dateutils.sameDate(date, XDate()) ? this.styles.today : undefined; if (date) { return ( <View style={this.styles.day}> <Text style={[this.styles.dayNum, today]}>{date.getDate()}</Text> <Text style={[this.styles.dayText, today]}>{XDate.locales[XDate.defaultLocale].dayNamesShort[date.getDay()]}</Text> </View> ); } else { return ( <View style={this.styles.day}/> ); } } render() { const {reservation, date} = this.props.item; let content; if (reservation) { const firstItem = date ? true : false; content = this.props.renderItem(reservation, firstItem); } else { content = this.props.renderEmptyDate(date); } return ( <View style={this.styles.container}> {this.renderDate(date, reservation)} <View style={{flex:1}}> {content} </View> </View> ); } } export default ReservationListItem;